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

Lab 06 - Database Systems

The document describes various SQL constraints that can be implemented in a lab experiment on database management systems. The objectives are to implement NOT NULL, UNIQUE, FOREIGN KEY, CHECK, and DEFAULT constraints. The document provides detailed explanations and examples of creating each constraint type using SQL on both CREATE TABLE and ALTER TABLE statements. Cascade options for FOREIGN KEY constraints are also demonstrated.

Uploaded by

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

Lab 06 - Database Systems

The document describes various SQL constraints that can be implemented in a lab experiment on database management systems. The objectives are to implement NOT NULL, UNIQUE, FOREIGN KEY, CHECK, and DEFAULT constraints. The document provides detailed explanations and examples of creating each constraint type using SQL on both CREATE TABLE and ALTER TABLE statements. Cascade options for FOREIGN KEY constraints are also demonstrated.

Uploaded by

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

NATIONAL UNIVERSITY OF MODERN LANGUAGES

DEPARTMENT OF COMPUTER SCIENCES

DATABASE MANAGEMENT SYSTEMS


LAB 06

LAB TITLE
SQL Constraints

Lab Objectives SQL Constraints.


Implementation of following constraints:
 NOT NULL 

 UNIQUE
Lab Task/Experiment  FOREIGN KEY 
 CHECK 
 DEFAULT 

Equipment Oracle SQL

SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy
and reliability of the data in the table. If there is any violation between the constraint and the data
action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and
table level constraints apply to the whole table.
The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified

SQL NOT NULL Constraint


By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
NATIONAL UNIVERSITY OF MODERN LANGUAGES
DEPARTMENT OF COMPUTER SCIENCES

This enforces a field to always contain a value, which means that you cannot insert a new record,
or update a record without adding a value to this field.
SQL NOT NULL on CREATE TABLE
The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT
accept NULL values when the "Persons" table is created:
Example
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255) NOT NULL,
    Age int
);

SQL NOT NULL on ALTER TABLE


To create a NOT NULL constraint on the "Age" column when the "Persons" table is already
created, use the following SQL:
ALTER TABLE Persons
MODIFY Age int NOT NULL;

SQL UNIQUE Constraint


The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a
column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.

SQL UNIQUE Constraint on CREATE TABLE


The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is
created:
CREATE TABLE Persons (
    ID int NOT NULL UNIQUE,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
);
NATIONAL UNIVERSITY OF MODERN LANGUAGES
DEPARTMENT OF COMPUTER SCIENCES

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CONSTRAINT UC_Person UNIQUE (ID,LastName)
);

SQL UNIQUE Constraint on ALTER TABLE

To create a UNIQUE constraint on the "ID" column when the table is already created, use the
following SQL:
ALTER TABLE Persons
ADD UNIQUE (ID);

To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the


following SQL syntax:
ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

DROP a UNIQUE Constraint

To drop a UNIQUE constraint, use the following SQL:


ALTER TABLE Persons
DROP CONSTRAINT UC_Person;
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of single
or multiple columns (fields).

SQL PRIMARY KEY on CREATE TABLE

The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is
created:
CREATE TABLE Persons (
    ID int NOT NULL PRIMARY KEY,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
NATIONAL UNIVERSITY OF MODERN LANGUAGES
DEPARTMENT OF COMPUTER SCIENCES

    Age int


);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint


on multiple columns, use the following SQL syntax:
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);

Note: In the example above there is only ONE PRIMARY KEY (PK_Person). However, the
VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).

SQL PRIMARY KEY on ALTER TABLE

To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use
the following SQL:
ALTER TABLE Persons
ADD PRIMARY KEY (ID);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint


on multiple columns, use the following SQL syntax:
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

Note: If you use ALTER TABLE to add a primary key, the primary key column(s) must have
been declared to not contain NULL values (when the table was first created).

DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL:


ALTER TABLE Persons
DROP CONSTRAINT PK_Person;

SQL FOREIGN KEY Constraint


NATIONAL UNIVERSITY OF MODERN LANGUAGES
DEPARTMENT OF COMPUTER SCIENCES

The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY
KEY in another table.
The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.
Look at the following two tables:
Persons Table
PersonID LastName FirstName Age

1 Hansen Ola 30

2 Svendson Tove 23

3 Pettersen Kari 20
Orders Table
OrderID OrderNumber PersonID

1 77895 3

2 44678 3

3 22456 2

4 24562 1

Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the parent table.

SQL FOREIGN KEY on CREATE TABLE

The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table
is created:

CREATE TABLE Orders (
    OrderID int NOT NULL PRIMARY KEY,
    OrderNumber int NOT NULL,
NATIONAL UNIVERSITY OF MODERN LANGUAGES
DEPARTMENT OF COMPUTER SCIENCES

    PersonID int FOREIGN KEY REFERENCES Persons(PersonID)


);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint


on multiple columns, use the following SQL syntax:

CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
    REFERENCES Persons(PersonID)
);
Syntax for creating Foreign keys with cascade delete
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
);

Syntax for creating Foreign keys with cascade update


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 UPDATE CASCADE
);
NATIONAL UNIVERSITY OF MODERN LANGUAGES
DEPARTMENT OF COMPUTER SCIENCES

SQL FOREIGN KEY on ALTER TABLE


To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is
already created, use the following SQL:
ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint
on multiple columns, use the following SQL syntax:
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

DROP a FOREIGN KEY Constraint

To drop a FOREIGN KEY constraint, use the following SQL:


ALTER TABLE Orders
DROP CONSTRAINT FK_PersonOrder;

SQL CHECK Constraint

The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a column it will allow only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.

SQL CHECK on CREATE TABLE

The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table
is created. The CHECK constraint ensures that the age of a person must be 18, or older:
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int CHECK (Age>=18)
);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple


columns, use the following SQL syntax:
CREATE TABLE Persons (
    ID int NOT NULL,
NATIONAL UNIVERSITY OF MODERN LANGUAGES
DEPARTMENT OF COMPUTER SCIENCES

    LastName varchar(255) NOT NULL,


    FirstName varchar(255),
    Age int,
    City varchar(255),
    CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);

SQL CHECK on ALTER TABLE

To create a CHECK constraint on the "Age" column when the table is already created, use the
following SQL:
ALTER TABLE Persons
ADD CHECK (Age>=18);
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');

DROP a CHECK Constraint

To drop a CHECK constraint, use the following SQL:


ALTER TABLE Persons
DROP CONSTRAINT CHK_PersonAge;

SQL DEFAULT Constraint

The DEFAULT constraint is used to set a default value for a column.


The default value will be added to all new records, if no other value is specified.

SQL DEFAULT on CREATE TABLE

The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is
created:
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
NATIONAL UNIVERSITY OF MODERN LANGUAGES
DEPARTMENT OF COMPUTER SCIENCES

    City varchar(255) DEFAULT 'Sandnes'


);

SQL DEFAULT on ALTER TABLE

To create a DEFAULT constraint on the "City" column when the table is already created, use the
following SQL:
ALTER TABLE Persons
MODIFY City DEFAULT 'Sandnes';
DROP a DEFAULT Constraint
To drop a DEFAULT constraint, use the following SQL:
ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT;
AUTO INCREMENT Field
Auto-increment allows a unique number to be generated automatically when a new record is
inserted into a table.
Often this is the primary key field that we would like to be created automatically every time a
new record is inserted.

Syntax for Oracle

In Oracle the code is a little bit more tricky.


You will have to create an auto-increment field with the sequence object (this object generates a
number sequence).
Use the following CREATE SEQUENCE syntax:
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;
The code above creates a sequence object called seq_person, that starts with 1 and will increment
by 1. It will also cache up to 10 values for performance. The cache option specifies how many
sequence values will be stored in memory for faster access.
To insert a new record into the "Persons" table, we will have to use the nextval function (this
function retrieves the next value from seq_person sequence):
INSERT INTO Persons (Personid,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen');
The SQL statement above would insert a new record into the "Persons" table. The "Personid"
column would be assigned the next number from the seq_person sequence. The "FirstName"
column would be set to "Lars" and the "LastName" column would be set to "Monsen".
NATIONAL UNIVERSITY OF MODERN LANGUAGES
DEPARTMENT OF COMPUTER SCIENCES

CREATE TABLE product (


category INT NOT NULL, id INT NOT NULL,
price DECIMAL,
PRIMARY KEY(category, id)
)

CREATE TABLE customer (


id INT NOT NULL,
PRIMARY KEY (id)
)

CREATE TABLE product_order (


no INT NOT NULL AUTO_INCREMENT,
product_category INT NOT NULL,
product_id INT NOT NULL,
customer_id INT NOT NULL,

PRIMARY KEY(no),
INDEX (product_category, product_id),
INDEX (customer_id),

FOREIGN KEY (product_category, product_id)


REFERENCES product(category, id)
ON UPDATE CASCADE ON DELETE RESTRICT,

FOREIGN KEY (customer_id)


REFERENCES customer(id)
)
NATIONAL UNIVERSITY OF MODERN LANGUAGES
DEPARTMENT OF COMPUTER SCIENCES

DATABASE MANAGEMENT SYSTEMS


LAB 06

Lab Task 1:

Create the database for the following scenario. You may first draw EDR or define schema before
writing the SQL queries in order to avoid mistakes.

Odeon Cinema and other international cinemas have decided to install a centralized database.
This database should keep information regarding cinemas including its name, address and phone
number. Each CINEMA must have one or more THEATERs and each THEATER must have
many number of SHOW_TIME. During these SHOW_TIMEs in a particular THEATER; A
particular MOVIE must be shown to the general public.

LAB TASK 2:

Part 1: Insert the sample data in the Database you created for the following Logical Schema in
your previous lab.

• Student(sid: integer, name: string, login: string, age: integer, gpa:float )


• Course(cid: string, cname:string, credits:integer)
• Enrolled(sid:integer, cid:string, grade:string, session:string)

Then perform the following queries.

a. SELECT sname, matricmarks, fscmarks, decision


FROM student, apply
WHERE student.sid=apply.sid and major=‘BSCS’
and dname='cs’;
b. SELECT DISTINCT student.sid, sname, ….
FROM major, apply, student
WHERE student.sid=apply.sid and major.mname=apply.dname and
NATIONAL UNIVERSITY OF MODERN LANGUAGES
DEPARTMENT OF COMPUTER SCIENCES

major.name=“BSCS”
Order by entrytest desc;

Part 2: Write the SQL queries for the following :

 All students with entrytest marks >50.

 All engineering departments with students enrollment>500.

 Insert a new department in department’s table. Name of the department is Mechatronics.


Total strength is 0 and location is ghazali block.

 Update location of computer science department from ghazali block to ibn-e-khaldun.

 Update name of major “BSCS” to “BCS” (check for cascade).

 Accept applications of students in BSCS major who have entry test marks between 80 and
100.
hint: you may have to update “decision” attribute in Apply.

 Delete students whose entrytest marks are less than 50.

You might also like