Hive - Renaming Fields With Same Name As A Datatype - sql

I have a Hive table like such:
CREATE TABLE mytest (name int, timestamp bigint, donation int);
I am using Hive 0.12. Note the field "timestamp". Incidentally, Hive 0.12+ introduced a new data type called timestamp. Say I want to rename this field to time_stamp
I tried these:
ALTER TABLE mytest CHANGE timestamp time_stamp BIGINT;
ALTER TABLE mytest CHANGE COLUMN timestamp time_stamp BIGINT;
ALTER TABLE mytest CHANGE [timestamp] time_stamp BIGINT;
ALTER TABLE mytest CHANGE `timestamp` time_stamp BIGINT;
However, all of them give me the following error:
FAILED: ParseException line 1:38 mismatched input 'CHANGE' expecting KW_EXCHANGE near 'mytest' in alter exchange partition
I am dead sure this is because of the fact that my field name is the same as a data type name. How can I alter the schema for mytest without having to do the following?
CREATE mytest_cpy AS SELECT mytest.name, mytest.timestamp AS time_stamp,
mytest.donation FROM mytest;
DROP TABLE mytest;
ALTER TABLE mytest_cpy RENAME TO mytest;
Thanks! Any/all help is appreciated!

Use backticks for any unusal column names, either containing weird symbols or the same as data types. This works for Hive 0.14:
ALTER TABLE mytest CHANGE COLUMN `timestamp` time_stamp BIGINT;

in MS SQL use:
EXECUTE sp_rename 'dbo.mytest.timestamp', 'time_stamp', 'COLUMN'
in MYSQL try:
USE database_name;
ALTER TABLE mytest CHANGE timestamp time_stamp BIGINT;
or:
ALTER TABLE database_name.mytest CHANGE timestamp time_stamp BIGINT;

Although this post have answers but still:
If you try to give column name which is Reserved Keywords for HIVE then error will occur.
For overriding the reserved keywords use can use backtick(`) this is the character below your tilde key or left to 1 key.

Related

Error in changing column length in Postgres

I am trying to change the column size from 100 to 150 varchar data type using following query:
alter table data_warehouse.tbl_abc
alter column first_nm varchar(150) null;
Getting the following error:
SQL Error [42601]: ERROR: syntax error at or near "varchar"
Position: 77
The syntax is a bit different, so try this:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm type varchar(120);
The error in your syntax is that you missed a TYPE keyword:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm TYPE varchar(150);
and if you have a NOT NULL constraint you want to remove, add a new ALTER COLUMN inside the same ALTER TABLE statement:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm TYPE varchar(150),
ALTER COLUMN first_nm DROP NOT NULL;
for reference look here: https://www.postgresql.org/docs/current/sql-altertable.html
Edit: as in the comment, if you have a view which involves the same column, drop it and re-create it under transaction:
BEGIN TRANSACTION;
DROP VIEW [...];
ALTER TABLE [...];
CREATE VIEW [...];
COMMIT;
Be aware that to alter a table, you must acquire an exclusive lock on it, so during the whole process, all the queries over the same table and on the views of the table are locked, also if they don't read from the altered column (because the whole table is locked) - use with caution in production environment

How to set datatype of SQL column in Alias?

If I have a query such as:
select name as first_name
from my_table
How can I set the datatype of that column in Postgresql to be character varying or anything in future - is there a way such as:
select name as first_name character varying
from my_table
I assume there is a way to set a datatype of a column after the aliasing - unsure how in postgresql
I am using postgresql and pgadmin4
Use cast to change the data type:
select cast(name as character varying(100)) as first_name
from my_table
But I'd consider altering the table column instead, to be varchar(100):
alter table my_table alter column name type character varying(100)
Use new datatype for column after TYPE keyword in PostgreSQL
ALTER TABLE table_name ALTER COLUMN column_name TYPE new_datatype;
Let's take an example -
CREATE TABLE Test (
emp_id serial PRIMARY KEY,
emp_name TEXT NOT NULL,
);
INSERT INTO Test (emp_id, emp_name) VALUES ('abc00012','Shubham');
ALTER TABLE Test ALTER COLUMN emp_name TYPE VARCHAR;
In Postgres, I would use the short-hand syntax for type conversion :::
select name::varchar as first_name
Of course, the right thing to do is to fix the type in the table, but that is already covered by other answers.
To easily cast your result to any datatype use :: datatype as in below:
select name as first_name ::varchar from my_table

Convert bit column to integer

I am converting bit columns of a particular table to integer through an SQL script (this table has some default constraints for default value).
I have to alter the columns for the table, not runtime casting, What script can be used to accomplish this?
Try using CAST(columnName AS INT) AS IntValue.
e.g.
SELECT columnName, CAST(columnName AS INT) AS IntValue
FROM table
OR you can use CONVERT(INT, columnName) AS IntValue.
UPDATE: If you need to alter the actual metadata of the table, then you first need to drop the constraints then alter the column:
i.e.
ALTER TABLE [Table] DROP CONSTRAINT [ConstraintName];
GO
ALTER TABLE [Table] ALTER COLUMN [ColumnName] INT;
Then recreate any constraints that you need.
If you are concerned about changing the datatype of the column you can use an ALTER query as follows.
ALTER TableName ALTER COLUMN ColumnName INT
Else, only for display purposes, you can use either the CAST or CONVERT function:
CAST(columnName AS INT) AS IntegerVal
CONVERT(int, columnName) AS IntValue
None of the provided solutions worked for me. I had to used Signed or Unsigned instead of INT e.g.
SELECT columnName, CAST(columnName AS SIGNED) AS IntValue
FROM table
Hope this helps for new users.
SELECT CONVERT(BIT,'False') AS test1
SELECT CONVERT(BIT,'True') AS test2
We can't simply alter the BIT column to INT. So I suggest to create the new integer column in the table and then using the CAST, update the new integer column with the existing bit values. Then at last you can drop the BIT column from the table.
Finally I managed to get it working:
ALTER TABLE tblname DROP CONSTRAINT DF_tbl_tblname_tblcol
ALTER TABLE tblname ALTER COLUMN tblcol int not null
ALTER TABLE tblname WITH NOCHECK ADD CONSTRAINT [DF_tbl_tblname_tblcol] DEFAULT (0) FOR tblcol
I have used the above SQL statements to alter the table column along with its constructor.
I believe you could extract the bit column as an integer by just using standard CAST() command:
SELECT
CAS(Bit_Column AS int) AS Int_Column
FROM
YourTable
However, I'm not sure I understand what you're trying to achieve, probably you could get a better answer if you provided more details, such as the structure of the table and its constraints.
You are getting an error related to a default constraint. Thus you have to drop that constraint before altering the column data type...
Try this to find all the constraints based on this table (you just need to find the proper default on your column) or use SQL Server Management Studio (SSMS) to generate the script for the table, and this will have the default constraint defintion.
select * from sys.all_objects where parent_object_id = object_id('<tablename>')
go
Then first drop the constraint and then alter the column and add the default again.
alter table bittoint drop constraint DF__bittoint__col2__45D500F0
go
alter table bittoint alter column col2 int
go
alter table bittoint add constraint DF__bittoint__col2__45D500F0 default 0 for col2
go

How to alter a column's data type in a PostgreSQL table?

Entering the following command into a PostgreSQL interactive terminal results in an error:
ALTER TABLE tbl_name ALTER COLUMN col_name varchar (11);
What is the correct command to alter the data type of a column?
See documentation here: http://www.postgresql.org/docs/current/interactive/sql-altertable.html
ALTER TABLE tbl_name ALTER COLUMN col_name TYPE varchar (11);
If data already exists in the column you should do:
ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;
As pointed out by #nobu and #jonathan-porter in the comments to #derek-kromm's answer, somewhat cryptically.
Cool #derek-kromm, Your answer is accepted and correct, But I am wondering if we need to alter more than the column. Here is how we can do.
ALTER TABLE tbl_name
ALTER COLUMN col_name TYPE varchar (11),
ALTER COLUMN col_name2 TYPE varchar (11),
ALTER COLUMN col_name3 TYPE varchar (11);
Documentation
Cheers!! Read Simple Write Simple

Altering a column to be nullable

I want to alter a table column to be nullable. I have used:
ALTER TABLE Merchant_Pending_Functions Modify NumberOfLocations NULL
This gives an error at Modify. What is the correct syntax?
Assuming SQL Server (based on your previous questions):
ALTER TABLE Merchant_Pending_Functions ALTER COLUMN NumberOfLocations INT NULL
Replace INT with your actual datatype.
If this was MySQL syntax, the type would have been missing, as some other responses point out.
Correct MySQL syntax would have been:
ALTER TABLE Merchant_Pending_Functions MODIFY NumberOfLocations INT NULL
Posting here for clarity to MySQL users.
In PostgresQL it is:
ALTER TABLE tableName ALTER COLUMN columnName DROP NOT NULL;
for Oracle Database 10g users:
alter table mytable modify(mycolumn null);
You get "ORA-01735: invalid ALTER TABLE option" when you try otherwise
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
Although I don't know what RDBMS you are using, you probably need to give the whole column specification, not just say that you now want it to be nullable. For example, if it's currently INT NOT NULL, you should issue ALTER TABLE Merchant_Pending_Functions Modify NumberOfLocations INT.
As others have observed, the precise syntax for the command varies across different flavours of DBMS. The syntax you use works in Oracle:
SQL> desc MACAddresses
Name Null? Type
----------------------------------------- -------- ----------------------------
COMPUTER NUMBER
MACADDRESS VARCHAR2(12)
CORRECTED_MACADDRESS NOT NULL VARCHAR2(17)
SQL> alter table MACAddresses
2 modify corrected_MACAddress null
3 /
Table altered.
SQL> desc MACAddresses
Name Null? Type
----------------------------------------- -------- ----------------------------
COMPUTER NUMBER
MACADDRESS VARCHAR2(12)
CORRECTED_MACADDRESS VARCHAR2(17)
SQL>
For SQL Server or TSQL
ALTER TABLE Complaint.HelplineReturn ALTER COLUMN IsDisposed BIT NULL
This depends on what SQL Engine you are using, in Sybase your command works fine:
ALTER TABLE Merchant_Pending_Functions
Modify NumberOfLocations NULL;
For HSQLDB:
ALTER TABLE tableName ALTER COLUMN columnName SET NULL;
ALTER TABLE Merchant_Pending_Functions MODIFY COLUMN `NumberOfLocations` INT null;
This will work for you.
If you want to change a not null column to allow null, no need to include not null clause. Because default columns get not null.
ALTER TABLE Merchant_Pending_Functions MODIFY COLUMN `NumberOfLocations` INT;
Oracle
ALTER TABLE Merchant_Pending_Functions MODIFY([column] NOT NULL);
SQLite
The ALTER TABLE command is a bit special. There is no possibility to modify a column. You have to create a new column, migrate the data, and then drop the column:
-- 1. First rename
ALTER TABLE
Merchant_Pending_Functions
RENAME COLUMN
NumberOfLocations
TO
NumberOfLocations_old
-- 2. Create new column
ALTER TABLE
Merchant_Pending_Functions
ADD COLUMN
NumberOfLocations INT NULL
-- 3. Migrate data - you need to write code for that
-- 4. Drop the old column
ALTER TABLE
Merchant_Pending_Functions
DROP COLUMN
NumberOfLocations_old
Make sure you add the data_type of the column to modify.
ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME DATA_TYPE NULL;