0% found this document useful (0 votes)
22 views

Constraints by Using SQL

The document discusses various SQL constraints that can be used when defining tables in a database including primary keys, composite keys, null/not null constraints, and foreign keys. It provides examples of creating tables and adding primary key and foreign key constraints through ALTER statements as well as through single CREATE statements. It also shows how to define a composite primary key across two columns and describes dropping a constraint.

Uploaded by

cavad565
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Constraints by Using SQL

The document discusses various SQL constraints that can be used when defining tables in a database including primary keys, composite keys, null/not null constraints, and foreign keys. It provides examples of creating tables and adding primary key and foreign key constraints through ALTER statements as well as through single CREATE statements. It also shows how to define a composite primary key across two columns and describes dropping a constraint.

Uploaded by

cavad565
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

CONSTRAINTS

BY USING SQL
PRIMARY KEY
COMPOSITE KEY
NULL & NOT NULL
FOREIGN KEY

CREATE TABLE STUDENTS


(ROLL_NO NUMBER(10),
FULL_NAME NUMBER(20));

ALTER TABLE STUDENTS


ADD (CONSTRAINT STUDENTS_BRW_P2
PRIMARY KEY(ROLL_NO))

STUDENTS_BRW_P2

CREATE TABLE COURSES


(ROLL_NO_FK NUMBER(10),
SUBJECT_ID VARCHAR2(10),
MARKS NUMBER(10));

ALTER TABLE COURSES


ADD (CONSTRAINT COURSES_BRW_F1
FOREIGN KEY(ROLL_NO_FK)
REFERENCES STUDENTS(ROLL_NO))

SQL> select
CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAME,
LAST_CHANGE
From user_constraints
where LAST_CHANGE > '15-feb-2003' ;

CONSTRAINT_NAME
-----------------------------COURSES_BRW_F1

C
-----------R

TABLE_NAME
----------------COURSES

LAST_CHAN
--------25-FEB-03

DROP CONSTRAINT

ALTER TABLE COURSES


DROP CONSTRAINT COURSES_BRW_F1;

CREATE TABLE Table1


(a NUMBER(10),
b NUMBER(10))

ALTER TABLE TABLE1


ADD (CONSTRAINT b_BRW_F1
Primary KEY(a,b))

Defining Composite Key


create table aaab(a number, b number);
alter table aaab add(constraint abc_pk
PRIMARY KEY(a,b));
desc aaab;
Name

Null?

Type

NOT NULL

NUMBER

NOT NULL

NUMBER

CREATE TABLE AB_XYZ(A NUMBER, B NUMBER,


CONSTRAINT P_ABC PRIMARY KEY(A,B));

Creating table and defining Primary


key using single statement
create table xyz
(a number PRIMARY KEY, b number);

Creating table and defining


Foreign key using single statement
create table a_xyz(a number, b number,
constraint f_abc FOREIGN KEY(a)
REFERENCES abc(id));

Lab Practice
Do it now.

ISSUE
Member_id
Book_id
Date

Books
Book_id_pk
Book_name

Member
member_id_pk
Book_name

Thanks

You might also like