Why is the column not altering when I try to convert it to UUID? - sql

I have a primary key column in my SQL table in PostgreSQL named "id". It is a "bigseries" column. I want to convert the column to a "UUID" column. It entered the below command in the terminal:
alter table people alter column id uuid;
and
alter table people alter column id uuid using (uuid_generate_v4());
but neither of them worked.
In both tries I got the error message
ERROR: syntax error at or near "uuid"
LINE 1: alter table people alter column id uuid using (uuid_generate...
What is the correct syntax?

First of all uuid_generate_v4() is a function which is provided by an extension called uuid-ossp. You should have install that extension by using;
CREATE EXTENSION uuid-ossp;
Postgresql 13 introduced a new function which does basically the same without installing extension. The function is called gen_random_uuid()
Suppose that we have a table like the one below;
CREATE TABLE people (
id bigserial primary key,
data text
);
The bigserial is not a real type. It's a macro which basically creates bigint column with default value and a sequence. The default value is next value of that sequence.
For your use case, to change data type, you first should drop the old default value. Then, alter the type and finally add new default value expression. Here is the sample:
ALTER TABLE people
ALTER id DROP DEFAULT,
ALTER id TYPE uuid using (gen_random_uuid() /* or uuid_generate_v4() */ ),
ALTER id SET DEFAULT gen_random_uuid() /* or uuid_generate_v4() */ ;

CREATE TABLE IF NOT EXISTS people (
id uuid NOT NULL CONSTRAINT people_pkey PRIMARY KEY,
address varchar,
city varchar(255),
country varchar(255),
email varchar(255),
phone varchar(255)
);
This is the correct syntax to create table in postgres SQL, it's better to do these constraints at beginning to avoid any error.
For using alter command you would do the following:
ALTER TABLE customer ADD COLUMN cid uuid PRIMARY KEY;
Most of errors that you could find while writing command either lower case or undefined correct the table name or column.

Related

How to modify column to auto increment in PL SQL Developer?

I have created one table in PL SQL Developer.
CREATE TABLE Patient_List
(
Patient_ID number NOT NULL,
Patient_Name varchar(50) NOT NULL,
Patient_Address varchar(100) NULL,
App_Date date NULL,
Descr varchar(50),
CONSTRAINT patient_pk PRIMARY KEY(Patient_ID)
);
I want to auto increment Patient_ID, I tried altering the table and modifying the Patient_ID column but it's showing an error "invalid ALTER TABLE option"
ALTER TABLE Patient_List
MODIFY Patient_ID NUMBER NOT NULL GENERATED ALWAYS AS IDENTITY;
Please help, Thanks in advance.
This is not possible.
Oracle 10g didn't even have identity columns, they were introduced in Oracle 12.1
But even with a current Oracle version, you can't convert a regular column to an identity column. You would need to add a new one.
Before identity columns, the usual way was to create a sequence and a trigger to populate the column.
See here: How to create id with AUTO_INCREMENT on Oracle?
If anybody wants to modify existing column as auto_increment use this three lines
alter table Product drop column test_id;
create sequence Product_test_id_seq INCREMENT BY 1 nocache;
alter table Product add test_id Number default Product_test_id_seq.nextval not null;

SQLite - NOT NULL constraint failed

I am trying to create a simple SQLite database that will allow me to store email addresses and timestamps. I have created the table like this:
$sql =<<<EOF
CREATE TABLE ENTRIES
(ID INT PRIMARY KEY NOT NULL,
EMAIL EMAIL NOT NULL,
TIMESTAMP DATETIME DEFAULT CURRENT_TIMESTAMP);
EOF;
And I am trying to insert an email like this:
$sql =<<<EOF
INSERT INTO ENTRIES (EMAIL)
VALUES (test#test.com);
EOF;
I am getting an error
NOT NULL constraint failed: ENTRIES.ID
I am assuming this is to do with the ID and autoincrement? I have read the docs and it advises against using autoincrement. Where am I going wrong?
The docs say:
If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID.
And because it becomes an alias for the ROWID, it's not necessary to explicitly specify a value.
You have INT PRIMARY KEY, not INTEGER PRIMARY KEY. If you change it to INTEGER PRIMARY KEY, it works the way you expect.

Adding a NOT NULL column to a Redshift table

I'd like to add a NOT NULL column to a Redshift table that has records, an IDENTITY field, and that other tables have foreign keys to.
In PostgreSQL, you can add the column as NULL, fill it in, then ALTER it to be NOT NULL.
In Redshift, the best I've found so far is:
ALTER TABLE my_table ADD COLUMN new_column INTEGER;
-- Fill that column
CREATE TABLE my_table2 (
id INTEGER IDENTITY NOT NULL SORTKEY,
(... all the fields ... )
new_column INTEGER NOT NULL,
PRIMARY KEY(id)
) DISTSTYLE all;
UNLOAD ('select * from my_table')
to 's3://blah' credentials '<aws-auth-args>' ;
COPY my_table2
from 's3://blah' credentials '<aws-auth-args>'
EXPLICIT_IDS;
DROP table my_table;
ALTER TABLE my_table2 RENAME TO my_table;
-- For each table that had a foreign key to my_table:
ALTER TABLE another_table ADD FOREIGN KEY(my_table_id) REFERENCES my_table(id)
Is this the best way of achieving this?
You can achieve this w/o having to load to S3.
modify the existing table to create the desired column w/ a default value
update that column in some way (in my case it was copying from another column)
create a new table with the column w/o a default value
insert into the new table (you must list out the columns rather than using (*) since the order may be the same (say if you want the new column in position 2)
drop the old table
rename the table
alter table to give correct owner (if appropriate)
ex:
-- first add the column w/ a default value
alter table my_table_xyz
add visit_id bigint NOT NULL default 0; -- not null but default value
-- now populate the new column with whatever is appropriate (the key in my case)
update my_table_xyz
set visit_id = key;
-- now create the new table with the proper constraints
create table my_table_xzy_new
(
key bigint not null,
visit_id bigint NOT NULL, -- here it is not null and no default value
adt_id bigint not null
);
-- select all from old into new
insert into my_table_xyz_new
select key, visit_id, adt_id
from my_table_xyz;
-- remove the orig table
DROP table my_table_xzy_events;
-- rename the newly created table to the desired table
alter table my_table_xyz_new rename to my_table_xyz;
-- adjust any views, foreign keys or permissions as required

Link a sequence with to an identity in hsqldb

In PostgreSql, one can define a sequence and use it as the primary key of a table. In HsqlDB, one can still accomplish creating an auto-increment identity column which doesn't link to any user defined sequence. Is it possible to use a user defined sequence as the generator of an auto-increment identity column in HsqlDB?
Sample sql in PostgreSql:
CREATE SEQUENCE seq_company_id START WITH 1;
CREATE TABLE company (
id bigint PRIMARY KEY DEFAULT nextval('seq_company_id'),
name varchar(128) NOT NULL CHECK (name <> '')
);
What's the equivalent in HsqlDB?
Thanks.
In version 2.0, there is no direct feature for this. You can define a BEFORE INSERT trigger on the table to do this:
CREATE TABLE company ( id bigint PRIMARY KEY, name varchar(128) NOT NULL CHECK (name <> '') );
CREATE TRIGGER trigg BEFORE INSERT
ON company REFERENCING NEW ROW AS newrow
FOR EACH ROW
SET newrow.id = NEXT VALUE FOR seq_company_id;
and insert without using any vlue for id
INSERT INTO company VALUES null, 'test'
Update for HSQLDB 2.1 and later: A feature has been added to support this.
CREATE SEQUENCE SEQU
CREATE TABLE company ( id bigint GENERATED BY DEFAULT AS SEQUENCE SEQU PRIMARY KEY, name varchar(128) NOT NULL CHECK (name <> '') );
See the Guide under CREATE TABLE http://hsqldb.org/doc/2.0/guide/databaseobjects-chapt.html#dbc_table_creation
In addition, 2.1 and later has a PostgreSQL compatibility mode in which it accepts the PostgreSQL CREATE TABLE statement that references the sequence in the DEFAULT clause and translates it to HSQLDB syntax.

Alter a MySQL column to be AUTO_INCREMENT

I’m trying to modify a table to make its primary key column AUTO_INCREMENT after the fact. I have tried the following SQL, but got a syntax error notification.
ALTER TABLE document
ALTER COLUMN document_id AUTO_INCREMENT
Am I doing something wrong or is this not possible?
+--------------------+
| VERSION() |
+--------------------+
| 5.0.75-0ubuntu10.2 |
+--------------------+
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment
Roman is right, but note that the auto_increment column must be part of the PRIMARY KEY or a UNIQUE KEY (and in almost 100% of the cases, it should be the only column that makes up the PRIMARY KEY):
ALTER TABLE document MODIFY document_id INT AUTO_INCREMENT PRIMARY KEY
In my case it only worked when I put not null. I think this is a constraint.
ALTER TABLE document MODIFY COLUMN document_id INT NOT NULL AUTO_INCREMENT;
You can apply the atuto_increment constraint to the data column by the following query:
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
But, if the columns are part of a foreign key constraint you, will most probably receive an error. Therefore, it is advised to turn off foreign_key_checks by using the following query:
SET foreign_key_checks = 0;
Therefore, use the following query instead:
SET foreign_key_checks = 0;
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
SET foreign_key_checks = 1;
The SQL to do this would be:
ALTER TABLE `document` MODIFY COLUMN `document_id` INT AUTO_INCREMENT;
There are a couple of reasons that your SQL might not work. First, you must re-specify the data type (INT in this case). Also, the column you are trying to alter must be indexed (it does not have to be the primary key, but usually that is what you would want). Furthermore, there can only be one AUTO_INCREMENT column for each table. So, you may wish to run the following SQL (if your column is not indexed):
ALTER TABLE `document` MODIFY `document_id` INT AUTO_INCREMENT PRIMARY KEY;
You can find more information in the MySQL documentation: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html for the modify column syntax and http://dev.mysql.com/doc/refman/5.1/en/create-table.html for more information about specifying columns.
You must specify the type of the column before the auto_increment directive, i.e. ALTER TABLE document MODIFY COLUMN document_id INT AUTO_INCREMENT.
AUTO_INCREMENT is part of the column's datatype, you have to define the complete datatype for the column again:
ALTER TABLE document
ALTER COLUMN document_id int AUTO_INCREMENT
(int taken as an example, you should set it to the type the column had before)
You can do it like this:
alter table [table_name] modify column [column_name] [column_type] AUTO_INCREMENT;
You can use the following query to make document_id to increment automatically
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment
It is preferred to make document_id primary key as well
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment PRIMARY KEY;
Below statement works. Note that you need to mention the data type again for the column name (redeclare the data type the column was before).
ALTER TABLE document
MODIFY COLUMN document_id int AUTO_INCREMENT;
AUTO_INCREMENT is part of the column's datatype, you have to define the complete datatype for the column again:
ALTER TABLE document
MODIFY COLUMN document_id int AUTO_INCREMENT
(int taken as an example, you should set it to the type the column had before)
If none of the above works try this. This is what I did in MYSQL and yes, you need to write the column name (document_id) twice.
ALTER TABLE document
CHANGE COLUMN document_id document_id INT(11) NOT NULL AUTO_INCREMENT ;
Setting column as primary key and auto_increment at the same time:
mysql> ALTER TABLE persons MODIFY COLUMN personID INT auto_increment PRIMARY KEY;
Query OK, 10 rows affected (0.77 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql>
To modify the column in mysql we use alter and modify keywords. Suppose we have created a table like:
create table emp(
id varchar(20),
ename varchar(20),
salary float
);
Now we want to modify type of the column id to integer with auto increment. You could do this with a command like:
alter table emp modify column id int(10) auto_increment;
Previous Table syntax:
CREATE TABLE apim_log_request (TransactionId varchar(50) DEFAULT NULL);
For changing the TransactionId to auto increment use this query
ALTER TABLE apim_log_request MODIFY COLUMN TransactionId INT auto_increment;
alter table tbl_user MODIFY COLUMN id int(10) auto_increment;
Just like this:
alter table document modify column id int(11) auto_increment;
As you are redefining the column again, you have to specify the datatype again and add auto_increment to it as it's a part of datatype.
ALTER TABLE `document` MODIFY COLUMN `document_id` INT AUTO_INCREMENT;
Try the following:
ALTER TABLE table_name MODIFY COLUMN id datatype auto_increment;
Since SQL tag is attached to the question I really think all answers missed one major point.
MODIFY command does not exist in SQL server So you will be getting an error when you run the
ALTER TABLE Satellites MODIFY COLUMN SatelliteID INT auto_increment PRIMARY KEY;
In this case you can either add new column as INT IDENTITY
ALTER TABLE Satellites
ADD ID INT IDENTITY
CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED;
OR
Fill the existing null index with incremental numbers using this method,
DECLARE #id INT
SET #id = 0
UPDATE Satellites SET #id = SatelliteID = #id + 1
Use the following queries:
ALTER TABLE YourTable DROP COLUMN IDCol
ALTER TABLE YourTable ADD IDCol INT IDENTITY(1,1)