How do I ALTER a PostgreSQL table and make a column unique? - sql

I have a table in PostgreSQL where the schema looks like this:
CREATE TABLE "foo_table" (
"id" serial NOT NULL PRIMARY KEY,
"permalink" varchar(200) NOT NULL,
"text" varchar(512) NOT NULL,
"timestamp" timestamp with time zone NOT NULL
)
Now I want to make the permalink unique across the table by ALTER-ing the table.

I figured it out from the PostgreSQL docs, the exact syntax is:
ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);
Thanks Fred.

Or, have the DB automatically assign a constraint name using:
ALTER TABLE foo ADD UNIQUE (thecolumn);

it's also possible to create a unique constraint of more than 1 column:
ALTER TABLE the_table
ADD CONSTRAINT constraint_name UNIQUE (column1, column2);

Try the following
ALTER TABLE table_name ADD UNIQUE (column_name);

Related

How to change the column length of a primary key in SQL Server?

I know how to change the length of a column, but my SQL statement fails because the column I'm trying to change is a PK, so I get the following error:
Msg 5074, Level 16, State 1, Line 1
The object 'PK_TableName' is dependent on column 'PersonID'.
PersonID = PK.
I've read What is the sql to change the field length of a table column in sql server which only applies to non-PK columns.
I tried this:
ALTER TABLE table_name
ALTER COLUMN column_name <new datatype>
See below sample example how to increase size of the primary column
Create a sample table
create table abc (id varchar(10) primary key)
Find primary constraint in key constraints tables
select object_name(object_id),* from sys.key_constraints where object_name(parent_object_id) = 'abc
Drop constraint
ALTER TABLE abc
DROP CONSTRAINT PK__abc__3213E83F74EAC69B
(Replace PK__abc__3213E83F74EAC69B with constraint name you receive.)
Add not null
ALTER TABLE abc alter column id varchar(20) NOT NULL;
Add primary key again
ALTER TABLE abc
ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (id)
ALTER TABLE <Table_Name>
DROP CONSTRAINT <constraint_name>
ALTER TABLE table_name
ALTER COLUMN column_name datatype
ALTER TABLE <Table_Name>
ADD CONSTRAINT <constraint_name> PRIMARY KEY (<Column1>,<Column2>)
SQLServer 2008 did not allow me to change a primary key with data so I deactivated all the constraints, performed the command and activated all the constraints again. The commands are:
EXEC sp_MSforeachtable #command1="ALTER TABLE ? NOCHECK CONSTRAINT ALL"
-- commands here
EXEC sp_MSforeachtable #command1="ALTER TABLE ? CHECK CONSTRAINT ALL"

How to Write a Script to add extra columns for my primary key

I have the following table in SQL Server 2008 R2
Now I need to write a script to add a new column cusomerVLANID as part of the primary key, so that the three columns becomes the primary key, is there a way to write such script.
Second thing I want to write a script to remove the Allow Null, check box from the CustomerVLANID columns ?
Thanks
ALTER TABLE <Table_Name>
DROP CONSTRAINT <constraint_name>
ALTER TABLE <Table_Name>
ADD CONSTRAINT <constraint_name> PRIMARY KEY ([ID], [CustomerName], [CustomerVLANSID])
Run this statement separately to set up the NOT NULL constraint:
ALTER TABLE <Table_Name>
ALTER COLUMN [CustomerVLANSID] INT NOT NULL
alter table TABLE1
alter column [CustomerVLANID] int not null
I hope this helps,
-Thomas
RosSQL.blogspot.com

Alter a table column with auto increment by 1 in derby

I have created a table in derby Netbeans and now i realize that i need to make a column as auto incremented by 1 which is a primary key. How can i do so? I tried the following code but was in vain.
ALTER TABLE ISSUERECIPT ALTER IRCODE SET INCREMENT BY 1;
Do i need to create the table once again or can it be possible some other way?
I have found an alternate solution, i dropped the column from the database (thanks vels4j) added the column once again from the netbeans derby UI as shown below:
To alter the column to be auto-generated, the code is
ALTER TABLE ISSUERECIPT ALTER IRCODE SET INCREMENT BY 1;
BUT the column must already be defined with the IDENTITY attribute (as written in this documentation).
In most cases (assuming that you too), the primary key column is not set as IDENTITY. Therefore, you may intend to alter the column to IDENTITY, but that is impossible.
The only way is to drop the table and create it again, as written here.
ALTER TABLE ISSUERECIPT ADD IRCODE INTEGER NOT NULL primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
I guess could do the things for you
Check this
ALTER TABLE ISSUERECIPT
ALTER IRCODE INTEGER NOT NULL
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1);
If your table is empty, Try this
ALTER TABLE DROP PRIMARY KEY your_primaryKeyContrainName ;
ALTER TABLE ISSUERECIPT DROP COLUMN IRCODE ;
ALTER TABLE ISSUERECIPT ADD COLUMN
IRCODE PRIMARY KEY INTEGER NOT NULL
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1);
See Also : Derby ALTER TABLE Syntax
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;
The ALTER TABLE statement cannot add an IDENTITY column to a table
If your table is empty or is not in production. drop table and create again, example:
DROP TABLE CUSTOMER;
CREATE TABLE CUSTOMER
(CUSTOMER_ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY
1),
FIRSTNAME VARCHAR(100) NOT NULL,VARCHAR(100),
PREFERRED_ID INTEGER,
CONSTRAINT primary_key PRIMARY KEY (CUSTOMER_ID)
);
Try this :
alter table ISSUERECIPT modify column IRCODE int(4) auto_increment
Recreate the table again see example below:
CREATE TABLE students
(
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
name VARCHAR(24) NOT NULL,
address VARCHAR(1024),
CONSTRAINT primary_key PRIMARY KEY (id)
) ;

Add primary key to PostgreSQL table only if it does not exist

I have simple table creating script in Postgres 9.1. I need it to create the table with
2-attributes PK only if it does not exist.
CREATE TABLE IF NOT EXISTS "mail_app_recipients"
(
"id_draft" Integer NOT NULL,
"id_person" Integer NOT NULL
) WITH (OIDS=FALSE); -- this is OK
ALTER TABLE "mail_app_recipients" ADD PRIMARY KEY IF NOT EXISTS ("id_draft","id_person");
-- this is problem since "IF NOT EXISTS" is not allowed.
Any solution how to solve this problem? Thanks in advance.
You could do something like the following, however it is better to include it in the create table as a_horse_with_no_name suggests.
if NOT exists (select constraint_name from information_schema.table_constraints where table_name = 'table_name' and constraint_type = 'PRIMARY KEY') then
ALTER TABLE table_name
ADD PRIMARY KEY (id);
end if;
Why not include the PK definition inside the CREATE TABLE:
CREATE TABLE IF NOT EXISTS mail_app_recipients
(
id_draft Integer NOT NULL,
id_person Integer NOT NULL,
constraint pk_mail_app_recipients primary key (id_draft, id_person)
)
You can try to DROP it before creating it (DROP has the IF EXISTS clause):
ALTER TABLE mail_app_recipients DROP CONSTRAINT IF EXISTS mail_app_recipients_pkey;
ALTER TABLE mail_app_recipients ADD CONSTRAINT mail_app_recipients_pkey PRIMARY KEY ("id_draft","id_person");
Note that this require that you give a name to the primary key constraint - in this example mail_app_recipients_pkey.

General error: 1 OCIStmtExecute: ORA-00001: unique constraint (HR.SYS_C004023) violated?

I can identify the error message that its due to unique value constraint, my table is 'branches',and where did SYS_C004023 come. I have checked the branches table and there is no value duplication. What could be the issue.
where did SYS_C004023 come
This is a system-generated constraint name, which Oracle creates when a constraint is created without being explicitly named e.g.
create table mytable (col1 integer primary key);
The primary key constraint on mytable will be system-generated since I didn't explicitly name it like this:
create table mytable (col1 integer constraint mytable_pk primary key);
You can find out what table this constraint is on like this:
select table_name
from all_constraints
where owner = 'HR'
and constraint_name = 'SYS_C004023';
And you can find out which columns it makes unique like this:
select column_name
from all_cons_columns
where owner = 'HR'
and constraint_name = 'SYS_C004023';
there is no value duplication
No, there won't be, thanks to the constraint. What there has been is a failed attempt to insert or update a row so that the uniqueness constraint is violatedd.