SlideShare a Scribd company logo
1 of 28
LECTURE -4
S T R U C T U R E D Q U E R Y L A N G U A G E
( K E Y S & C O N S T R A I N T S )
D e l i v e r e d B y :
M r . S h u b h a m S h u k l a
PRIMARY KEYS
Note
• In Oracle, a primary key can not contain more than 32 columns.
• A primary key can be defined in either a CREATE TABLE statement or an ALTER TABLE
statement.
Create Primary Key - Using CREATE TABLE statement
Syntax
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n)
);
Example:
CREATE TABLE supplier
(
supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name)
);
Create Primary Key - Using ALTER TABLE statement
Syntax
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ...
column_n);
Example
ALTER TABLE supplier
ADD CONSTRAINT supplier_pk PRIMARY KEY (supplier_id);
• Drop Primary Key
Syntax
• ALTER TABLE table_name DROP CONSTRAINT constraint_name;
Example:
ALTER TABLE supplier DROP CONSTRAINT supplier_pk;
Disable Primary Key
Syntax
ALTER TABLE table_name
DISABLE CONSTRAINT constraint_name;
Example
ALTER TABLE supplier
DISABLE CONSTRAINT supplier_pk;
Enable Primary Key
Syntax
ALTER TABLE table_name
ENABLE CONSTRAINT constraint_name;
Example
ALTER TABLE supplier
ENABLE CONSTRAINT supplier_pk;
FOREIGN KEYS
• A foreign key is a way to enforce referential integrity within your Oracle
database. A foreign key means that values in one table must also appear in
another table.
• The referenced table is called the parent table while the table with the foreign
key is called the child table. The foreign key in the child table will generally
reference a primary key in the parent table.
Using a CREATE TABLE statement
Syntax
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
);
Example
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
);
 In case of multiple column key:
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name)
);
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
CONSTRAINT fk_supplier_comp
FOREIGN KEY (supplier_id, supplier_name)
REFERENCES supplier(supplier_id, supplier_name)
);
Using an ALTER TABLE statement
Syntax
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n);
Example:
ALTER TABLE products
ADD CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id, supplier_name)
REFERENCES supplier(supplier_id, supplier_name);
Foreign Keys with Cascade Delete
Using a CREATE TABLE statement
Syntax
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
ON DELETE CASCADE
);
For example:
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) );
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE );
Using an ALTER TABLE statement
Syntax
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
ON DELETE CASCADE;
For example:
ALTER TABLE products
ADD CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE;
Foreign Keys with Set Null on Delete
A foreign key with "set null on delete" means that if a record in the parent table is deleted, then
the corresponding records in the child table will have the foreign key fields set to null. The
records in the child table will not be deleted.
Using a CREATE TABLE statement
Syntax
CREATE TABLE table_name
( column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
ON DELETE SET NULL );
Example
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10),
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE SET NULL
);
Using an ALTER TABLE statement
Syntax
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
ON DELETE SET NULL;
Example
ALTER TABLE products
ADD CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE SET NULL;
• Drop a Foreign Key
Syntax
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
ALTER TABLE products
DROP CONSTRAINT fk_supplier;
• Disable a foreign key
Syntax
ALTER TABLE table_name
DISABLE CONSTRAINT constraint_name;
For Example:
ALTER TABLE products
DISABLE CONSTRAINT fk_supplier;
• Enable a foreign key
Syntax
ALTER TABLE table_name
ENABLE CONSTRAINT constraint_name;
For Example:
ALTER TABLE products
ENABLE CONSTRAINT fk_supplier;
UNIQUE CONSTRAINTS
• A unique constraint is a single field or combination of fields that uniquely defines a record.
Some of the fields can contain null values as long as the combination of values is unique.
 Using a CREATE TABLE statement
CREATE TABLE table_name
(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
...
CONSTRAINT constraint_name UNIQUE (uc_col1, uc_col2, ... uc_col_n)
);
For example:
CREATE TABLE supplier
( supplier_id numeric(10) NOT NULL,
supplier_name varchar2(50) NOT NULL,
contact_name varchar2(50),
CONSTRAINT supplier_unique UNIQUE (supplier_id)
);
Using an ALTER TABLE statement
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n);
Example:
ALTER TABLE supplier
ADD CONSTRAINT supplier_unique UNIQUE (supplier_id);
Drop Unique Constraint
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
Example
ALTER TABLE supplier
DROP CONSTRAINT supplier_unique;
Disable Unique Constraint
ALTER TABLE table_name
DISABLE CONSTRAINT constraint_name;
Example:
ALTER TABLE supplier
DISABLE CONSTRAINT supplier_unique;
Enable Unique Constraint
ALTER TABLE table_name
ENABLE CONSTRAINT constraint_name;
Example:
ALTER TABLE supplier
ENABLE CONSTRAINT supplier_unique;
CHECK CONSTRAINTS
• A check constraint allows you to specify a condition on each row in a table.
Note
• A check constraint can NOT be defined on a SQL View.
• The check constraint defined on a table must refer to only columns in that table.
It can not refer to columns in other tables.
• A check constraint can NOT include a SQL Subquery.
• A check constraint can be defined in either a SQL CREATE TABLE
statement or a SQL ALTER TABLE statement.
 Using a CREATE TABLE statement
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE]
);
Example
CREATE TABLE suppliers
(
supplier_id numeric(4),
supplier_name varchar2(50),
CONSTRAINT check_supplier_id
CHECK (supplier_id BETWEEN 100 and 9999)
);
Using an ALTER TABLE statement
ALTER TABLE table_name
ADD CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE];
Example
ALTER TABLE suppliers
ADD CONSTRAINT check_supplier_name
CHECK (supplier_name IN ('IBM', 'Microsoft', 'NVIDIA'));
Drop a Check Constraint
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
Example
ALTER TABLE suppliers
DROP CONSTRAINT check_supplier_id;
Enable a Check Constraint
ALTER TABLE table_name
ENABLE CONSTRAINT constraint_name;
Example
ALTER TABLE suppliers
ENABLE CONSTRAINT check_supplier_id;
Disable a Check Constraint
ALTER TABLE table_name
DISABLE CONSTRAINT constraint_name;
Example
ALTER TABLE suppliers
DISABLE CONSTRAINT check_supplier_id;
THANK YOU

More Related Content

What's hot (20)

DATABASE CONSTRAINTS
DATABASE CONSTRAINTSDATABASE CONSTRAINTS
DATABASE CONSTRAINTS
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
Sql joins inner join self join outer joins
Sql joins inner join self join outer joinsSql joins inner join self join outer joins
Sql joins inner join self join outer joins
 
Integrity constraints in dbms
Integrity constraints in dbmsIntegrity constraints in dbms
Integrity constraints in dbms
 
Database Relationships
Database RelationshipsDatabase Relationships
Database Relationships
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 
Database Chapter 3
Database Chapter 3Database Chapter 3
Database Chapter 3
 
Packages - PL/SQL
Packages - PL/SQLPackages - PL/SQL
Packages - PL/SQL
 
RELATIONSHIP IN DBMS.pptx
RELATIONSHIP IN DBMS.pptxRELATIONSHIP IN DBMS.pptx
RELATIONSHIP IN DBMS.pptx
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
 
Triggers
TriggersTriggers
Triggers
 
Mysql
MysqlMysql
Mysql
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Databases: Normalisation
Databases: NormalisationDatabases: Normalisation
Databases: Normalisation
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
Sql views
Sql viewsSql views
Sql views
 
Application of Data structure
Application of Data structureApplication of Data structure
Application of Data structure
 
SQL Views
SQL ViewsSQL Views
SQL Views
 

Similar to SQL Keys & Constraints Lecture

Similar to SQL Keys & Constraints Lecture (20)

CONSTRAINTS PPT.pptx
CONSTRAINTS PPT.pptxCONSTRAINTS PPT.pptx
CONSTRAINTS PPT.pptx
 
MY SQL
MY SQLMY SQL
MY SQL
 
Sql integrity constraints
Sql integrity constraintsSql integrity constraints
Sql integrity constraints
 
Lecture 3 sql {basics ddl commands}
Lecture 3 sql {basics  ddl commands}Lecture 3 sql {basics  ddl commands}
Lecture 3 sql {basics ddl commands}
 
Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Les02
Les02Les02
Les02
 
3. DDL.pdf
3. DDL.pdf3. DDL.pdf
3. DDL.pdf
 
Les10
Les10Les10
Les10
 
Difference Between Sql - MySql and Oracle
Difference Between Sql - MySql and OracleDifference Between Sql - MySql and Oracle
Difference Between Sql - MySql and Oracle
 
Les10
Les10Les10
Les10
 
Les10 Creating And Managing Tables
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
 
Entigrity constraint
Entigrity constraintEntigrity constraint
Entigrity constraint
 
Learn plsql
Learn plsqlLearn plsql
Learn plsql
 
Sql ch 12 - creating database
Sql ch 12 - creating databaseSql ch 12 - creating database
Sql ch 12 - creating database
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
dbms.pdf
dbms.pdfdbms.pdf
dbms.pdf
 
SQL : Structured Query Language
SQL : Structured Query LanguageSQL : Structured Query Language
SQL : Structured Query Language
 
Create table
Create tableCreate table
Create table
 
SQL
SQLSQL
SQL
 

Recently uploaded

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 

Recently uploaded (20)

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 

SQL Keys & Constraints Lecture

  • 1. LECTURE -4 S T R U C T U R E D Q U E R Y L A N G U A G E ( K E Y S & C O N S T R A I N T S ) D e l i v e r e d B y : M r . S h u b h a m S h u k l a
  • 2. PRIMARY KEYS Note • In Oracle, a primary key can not contain more than 32 columns. • A primary key can be defined in either a CREATE TABLE statement or an ALTER TABLE statement. Create Primary Key - Using CREATE TABLE statement Syntax CREATE TABLE table_name ( column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n) );
  • 3. Example: CREATE TABLE supplier ( supplier_id numeric(10) not null, supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name) );
  • 4. Create Primary Key - Using ALTER TABLE statement Syntax ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n); Example ALTER TABLE supplier ADD CONSTRAINT supplier_pk PRIMARY KEY (supplier_id);
  • 5. • Drop Primary Key Syntax • ALTER TABLE table_name DROP CONSTRAINT constraint_name; Example: ALTER TABLE supplier DROP CONSTRAINT supplier_pk;
  • 6. Disable Primary Key Syntax ALTER TABLE table_name DISABLE CONSTRAINT constraint_name; Example ALTER TABLE supplier DISABLE CONSTRAINT supplier_pk; Enable Primary Key Syntax ALTER TABLE table_name ENABLE CONSTRAINT constraint_name; Example ALTER TABLE supplier ENABLE CONSTRAINT supplier_pk;
  • 7. FOREIGN KEYS • A foreign key is a way to enforce referential integrity within your Oracle database. A foreign key means that values in one table must also appear in another table. • The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table.
  • 8. Using a CREATE TABLE statement Syntax CREATE TABLE table_name ( column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT fk_column FOREIGN KEY (column1, column2, ... column_n) REFERENCES parent_table (column1, column2, ... column_n) );
  • 9. Example CREATE TABLE supplier ( supplier_id numeric(10) not null, supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) ); CREATE TABLE products ( product_id numeric(10) not null, supplier_id numeric(10) not null, CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES supplier(supplier_id) );
  • 10.  In case of multiple column key: CREATE TABLE supplier ( supplier_id numeric(10) not null, supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name) ); CREATE TABLE products ( product_id numeric(10) not null, supplier_id numeric(10) not null, supplier_name varchar2(50) not null, CONSTRAINT fk_supplier_comp FOREIGN KEY (supplier_id, supplier_name) REFERENCES supplier(supplier_id, supplier_name) );
  • 11. Using an ALTER TABLE statement Syntax ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (column1, column2, ... column_n) REFERENCES parent_table (column1, column2, ... column_n); Example: ALTER TABLE products ADD CONSTRAINT fk_supplier FOREIGN KEY (supplier_id, supplier_name) REFERENCES supplier(supplier_id, supplier_name);
  • 12. Foreign Keys with Cascade Delete Using a CREATE TABLE statement Syntax CREATE TABLE table_name ( column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT fk_column FOREIGN KEY (column1, column2, ... column_n) REFERENCES parent_table (column1, column2, ... column_n) ON DELETE CASCADE );
  • 13. For example: CREATE TABLE supplier ( supplier_id numeric(10) not null, supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) ); CREATE TABLE products ( product_id numeric(10) not null, supplier_id numeric(10) not null, CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES supplier(supplier_id) ON DELETE CASCADE );
  • 14. Using an ALTER TABLE statement Syntax ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (column1, column2, ... column_n) REFERENCES parent_table (column1, column2, ... column_n) ON DELETE CASCADE; For example: ALTER TABLE products ADD CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES supplier(supplier_id) ON DELETE CASCADE;
  • 15. Foreign Keys with Set Null on Delete A foreign key with "set null on delete" means that if a record in the parent table is deleted, then the corresponding records in the child table will have the foreign key fields set to null. The records in the child table will not be deleted. Using a CREATE TABLE statement Syntax CREATE TABLE table_name ( column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT fk_column FOREIGN KEY (column1, column2, ... column_n) REFERENCES parent_table (column1, column2, ... column_n) ON DELETE SET NULL );
  • 16. Example CREATE TABLE supplier ( supplier_id numeric(10) not null, supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) ); CREATE TABLE products ( product_id numeric(10) not null, supplier_id numeric(10), CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES supplier(supplier_id) ON DELETE SET NULL );
  • 17. Using an ALTER TABLE statement Syntax ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (column1, column2, ... column_n) REFERENCES parent_table (column1, column2, ... column_n) ON DELETE SET NULL; Example ALTER TABLE products ADD CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES supplier(supplier_id) ON DELETE SET NULL;
  • 18. • Drop a Foreign Key Syntax ALTER TABLE table_name DROP CONSTRAINT constraint_name; ALTER TABLE products DROP CONSTRAINT fk_supplier;
  • 19. • Disable a foreign key Syntax ALTER TABLE table_name DISABLE CONSTRAINT constraint_name; For Example: ALTER TABLE products DISABLE CONSTRAINT fk_supplier; • Enable a foreign key Syntax ALTER TABLE table_name ENABLE CONSTRAINT constraint_name; For Example: ALTER TABLE products ENABLE CONSTRAINT fk_supplier;
  • 20. UNIQUE CONSTRAINTS • A unique constraint is a single field or combination of fields that uniquely defines a record. Some of the fields can contain null values as long as the combination of values is unique.  Using a CREATE TABLE statement CREATE TABLE table_name ( column1 datatype [ NULL | NOT NULL ], column2 datatype [ NULL | NOT NULL ], ... CONSTRAINT constraint_name UNIQUE (uc_col1, uc_col2, ... uc_col_n) );
  • 21. For example: CREATE TABLE supplier ( supplier_id numeric(10) NOT NULL, supplier_name varchar2(50) NOT NULL, contact_name varchar2(50), CONSTRAINT supplier_unique UNIQUE (supplier_id) );
  • 22. Using an ALTER TABLE statement ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); Example: ALTER TABLE supplier ADD CONSTRAINT supplier_unique UNIQUE (supplier_id); Drop Unique Constraint ALTER TABLE table_name DROP CONSTRAINT constraint_name; Example ALTER TABLE supplier DROP CONSTRAINT supplier_unique;
  • 23. Disable Unique Constraint ALTER TABLE table_name DISABLE CONSTRAINT constraint_name; Example: ALTER TABLE supplier DISABLE CONSTRAINT supplier_unique; Enable Unique Constraint ALTER TABLE table_name ENABLE CONSTRAINT constraint_name; Example: ALTER TABLE supplier ENABLE CONSTRAINT supplier_unique;
  • 24. CHECK CONSTRAINTS • A check constraint allows you to specify a condition on each row in a table. Note • A check constraint can NOT be defined on a SQL View. • The check constraint defined on a table must refer to only columns in that table. It can not refer to columns in other tables. • A check constraint can NOT include a SQL Subquery. • A check constraint can be defined in either a SQL CREATE TABLE statement or a SQL ALTER TABLE statement.
  • 25.  Using a CREATE TABLE statement CREATE TABLE table_name ( column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE] ); Example CREATE TABLE suppliers ( supplier_id numeric(4), supplier_name varchar2(50), CONSTRAINT check_supplier_id CHECK (supplier_id BETWEEN 100 and 9999) );
  • 26. Using an ALTER TABLE statement ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE]; Example ALTER TABLE suppliers ADD CONSTRAINT check_supplier_name CHECK (supplier_name IN ('IBM', 'Microsoft', 'NVIDIA')); Drop a Check Constraint ALTER TABLE table_name DROP CONSTRAINT constraint_name; Example ALTER TABLE suppliers DROP CONSTRAINT check_supplier_id;
  • 27. Enable a Check Constraint ALTER TABLE table_name ENABLE CONSTRAINT constraint_name; Example ALTER TABLE suppliers ENABLE CONSTRAINT check_supplier_id; Disable a Check Constraint ALTER TABLE table_name DISABLE CONSTRAINT constraint_name; Example ALTER TABLE suppliers DISABLE CONSTRAINT check_supplier_id;