1-- Adding Using alter
2ALTER TABLE table_name
3ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n);
1-- Dropping Using alter
2ALTER TABLE table_name
3DROP CONSTRAINT constraint_name;
1-- Primary key in a table
2SELECT * FROM ALL_CONSTRAINTS -- or DBA_CONSTRAINTS or UESR_CONSTRAINTS
3WHERE TABLE_NAME= 'table_name' AND CONSTRAINT_TYPE = 'P';
4-- With columns names:
5SELECT c.OWNER, c.TABLE_NAME, c.CONSTRAINT_NAME, c.CONSTRAINT_TYPE,
6 col.COLUMN_NAME
7FROM ALL_CONSTRAINTS c
8JOIN ALL_CONS_COLUMNS col ON c.TABLE_NAME = col.TABLE_NAME
9 AND c.CONSTRAINT_NAME = col.CONSTRAINT_NAME
10WHERE c.TABLE_NAME= 'table_name' AND c.CONSTRAINT_TYPE = 'P'
11ORDER BY c.TABLE_NAME, c.CONSTRAINT_NAME, col.COLUMN_NAME;
1-- syntax:
2SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner
3FROM all_constraints cons, all_cons_columns cols
4WHERE cols.table_name = '<table-name>' -- Replace <table-name> with your table-name
5AND cons.constraint_type = 'P'
6AND cons.constraint_name = cols.constraint_name
7AND cons.owner = cols.owner
8
9
10-- example:
11SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner
12FROM all_constraints cons, all_cons_columns cols
13WHERE cols.table_name = 'CUSTOMERS'
14AND cons.constraint_type = 'P'
15AND cons.constraint_name = cols.constraint_name
16AND cons.owner = cols.owner
17
1CREATE TABLE table_name
2(
3 column1 datatype null/not null,
4 column2 datatype null/not null,
5 ...
6 CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n)
7);