Database Systems: Concepts & SQL Guide
Database Systems: Concepts & SQL Guide
DSE 2221
3 Credits
Reference:
Database System Concepts , 6th Edition
Authors:
Abraham Silberschatz
Henry F. Korth
S. Sudarshan
1
Main Concepts Discussed
2
Database System Applications
1/14/2025 ADBMS 3
Database Management System (DBMS)
➢Database A collection of related data (and a description of this
data), designed to meet the information needs of an organization.
➢DBMS is a collection of interrelated data and set of programs to
access those data.
➢DBMS is a general purpose software system that facilitates the
process of defining, constructing, manipulating and sharing
databases among users and applications.
1/14/2025 ADBMS 4
1/14/2025 ADBMS 5
Unit 4
Structured Query Language
Overview of SQL Query Language
• IBM developed the original version of SQL, originally SEQUEL in 1970s
• The sequel language has evolved since then and the name changed as SQL and
has established itself as the standard relational database language
• In 1986, the ANSI and ISO published an SQL standard called SQL-86
• Recently SQL:2008
• SQL (Structured Query Language) is a special – purpose programming language
designed for managing data held in a relational database management
system(RDBMS)
• Each SQL command should be terminated by ;
1/14/2025 7
Different Types of SQL Commands
SQL 11
Oracle- SQL Data Types…
1. Character
• Char – fixed length character string that can varies between 1-2000 bytes
• Varchar / Varchar2 – variable length character string, size ranges from 1-4000
bytes.
• Long - variable length character string, maximum size is 2 GB
Example: Name Char(10)
SQL 12
SQL 13
SQL Data Types
3. Date : used to store date and time in the table. DB uses its own format of storing in fixed
length of 7 bytes for century, date, month, year, hour, minutes, seconds. The default data type is
“dd-mon-yy” Example: Birth_date Date
4. Interval Year To Month : Stores a period of time using the YEAR and MONTH date
time fields Example: year_of_experience INTERVAL YEAR TO MONTH
CREATE TABLE Emp ( empno NUMBER, ename VARCHAR2(50), job VARCHAR2(255) , year_of_experience INTERVAL
YEAR TO MONTH );
SQL 15
Create Table Construct
An SQL relation is defined using the create table command:
create table r (A1 D1, A2 D2, ..., An Dn); both are equivalent syntax
Therefore designer has to ensure that data entered by user has to be checked against
these rules and allowed to store if valid otherwise need to be rejected.
SQL 18
TYPE of CONSTRAINTS
Rule/Constraints can be imposed on single column or combination of columns.
Table Level Constraint.- Defined at the end after defining all the columns.
Multi-level Column.
– Assume that are two columns in the table say- Date_of_Birth and Date_of_Join.
not null -
primary key (A1, ..., An )
foreign key (Am, ..., An ) references r
Unique
Check
Default
SQL 20
NOT NULL
NULL is special kind of value applicable to any domain(datatype).
Note: NULL is not equivalent to '' or ' '
In some cases, value to some column is mandatory to enter.
In other words we want to force the user to enter some value to the column.
Example: Assume that for the table Instructor we want to make user to enter some values for
name
SQL 23
Note: NO component of primary key can be NULL
FOREIGN KEY…
foreign key (Ak1 , Ak2, . . . , Akn ) references s:
The foreign key in a relation r specification says that the values of attributes (Ak1 , Ak2, . . . , Akn )
for any tuple in the relation r must correspond to values of the primary key attributes of some tuple
in relation s. [Link]
[Link]
Enrollment can be done to only to those who are student, therefore SID column in Enrollment can have only
values which are present in SID in Student table.
This condition is imposed by defining SID in Enrollment as Foreign key referencing Students
Child
Parent
Note: In relation R, attribute A can’t contain a value which is not existing in attribute A of relation S.
In the example above , at this instance A in R can’t have a value a6 or a7 etc.
SQL 25
..FOREIGN KEY
Properties:
A Foreign key can contain-
Only values present in the corresponding Parent Column/s.
NULL values accepted, if Foreign key is not defined with additional NOT NULL
constraints.
Foreign key column can reference to any column (parent column) whose data
type, width is same and Parent column has to be defined with Primary key or
Unique constraint.
A Parent Column has to exist before creation of Child Column with Foreign
key Constraint.
SQL 27
..FOREIGN KEY table-level
Example:
Parent(Master) Table:
CREATE TABLE Items( Item_name varchar2(10), Comp_name varchar2(10),
Price Number(3),
PRIMARY KEY ( Item_name,Comp_name ) );
Child(Detail) Table
CREATE TABLE Transactions( It_name varchar2(10), Comp_name varchar2(10),
Tr_Date date, Qty Number(3),
FOREIGN KEY(It_name, Comp_name) REFERENCES Items);
SQL 28
Does the following table get created with Foreign key constraint?
SQL 29
Does the following table get created with Foreign key constraint?
No: referenced table has a unique key so it has to be refered during foreign key definition
SQL 30
Write the SQL commands to create following tables with
mentioned constraints
*Assume that one student stays in one particular room of one particular Hostel only.
Student Hostel
Column DataType Constraint Column DataType Constraint
RegNo Number Primary key Hostel_NoVarchar Primary Key
Name Varchar Room_No Number Primary Key
Phone Number Unique RegNum Foreign Key
SQL 32
MAINTAINING REFERENTIAL INTEGRITY
Any delete made to the department table that would
On Delete Restrict delete or change a primary key value will be rejected
unless no foreign key references that value in the
employee table. This is the default constraint in
Oracle.
33
..FOREIGN KEY- ON DELETE CASCADE/ON DELETE SET NULL
A foreign key with cascade delete means that if a record in the parent table is deleted, then the
corresponding records in the child table will automatically be deleted. This is called a cascade delete
in Oracle.
Example: Create tables give in slide 29 with ON DELETE CASCADE clause along with FOREIGN
KEY.
Parent(Master) Table:
Child(Detail) Table
CREATE TABLE Emp ( Empno number(3) PRIMARY KEY, Name varchar(10), Deptno
varchar(2) REFERENCES Department ON DELETE CASCADE ) ;
Any Delete operation on the table Department(Parent) first deletes dependent records
in the EMP(child) table automatically. Thus Delete operation restriction on Foreign
SQL 34
key constraint is get resolved automatically.
..FOREIGN KEY- ON DELETE CASCADE/ON DELETE SET NULL
A foreign key with “ON DELETE SET NULL " 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.
Example: Create tables give in slide 18 with ON DELETE SET NULL clause along with FOREIGN KEY.
Parent(Master) Table:
Child(Detail) Table
CREATE TABLE Emp( Empno number(3) PRIMARY KEY, Name varchar(10), Deptno
varchar(2) REFERENCES Department ON DELETE SET NULL );
SQL 35
..FOREIGN KEY- ON DELETE CASCADE/ON DELETE SET NULL
SQL 36
..INSERT
Syntax-
INSERT INTO table_name(column1,column2,..) VALUES (value1,value2,….)
Example: Insert a record into Course table having values to Course_id, Dept_Name columns
only. Course(Course_id,title,Dept_Name,Credits)
SQL 37
UPDATE
SQL 38
DELETE
Syntax:
DELETE FROM table_name WHERE condition;
Example:
• Delete all instructors
delete from instructor
SQL 39
..FOREIGN KEY – INSERT Restrictions
Note-Parent record is added to DEPARTMENT and now we can add Employee with D4 department
SQL 40
..FOREIGN KEY- UPDATE/DELETE Restrictions
Similarly,
UPDATE EMP SET DEPTNO=‘D5’ WHERE EMPNO=100;
is Rejected.
UPDATE EMP SET DEPTNO=‘D3’ WHERE EMPNO=100;
is Accepted.
SQL 43
Note: [Link] ;
Exercise (Hostel_No,Room_No)- [Link]
RegNum- [Link]
Student Hostel
RegNo Name Phone RegNum Hostel_no Room_No What is the result of
111Ravi 122334 123H-16 376 execution of following SQL
123Raj 324555 111H-18 799 statements?
112Rakesh 563255 115H-18 376
115Ajay 567899
SQL 44
..FOREIGN KEY - Recursive Relationship
Example:
CREATE TABLE EMP ( Empno number(3) PRIMARY KEY, Ename
Varchar2(10), MGRNO number(3) );
SQL 45
Exercise
SQL 46
Inserting Data into Student table having Recursive relationship
SQL 48
Exercise UNIQUE…
Answer the validity of following statements with respect UNIQUE constraint on ID column-
SQL 49
..UNIQUE
In the following table combination of Area_code & Phone_Num is Unique
for a landline phone.
SQL 50
Exercise
SQL 51
The CHECK clause – Using IN
check (P)
where P is a predicate(condition)
Example: Ensure that Type of Courses offered by a department is any one of MCA, MTech,
BTech, MS.
SQL 52
..The CHECK clause –Using BETWEEN
Create table Instructor and ensure that Salary column accepts only values in the range 50000 to
200000 ( both upper and lower bound values are valid).
Create a table CANDIDATES(CandtID, Name, Branch) appearing for entrance exam at MIT.
Candidate numbers must be Unique & every candidate number must start with MIT.
CREATE TABLE CANDIDATES( CandtId varchar2(7) PRIMARY KEY CHECK (CandtId LIKE
'MIT%'), Name varchar2(10),Branch varchar2(10));
Wild characters-
% any number of characters
_ (underscore) Single character
SQL 54
..The check clause - using function UPPER()
Example:
Create a table CANDIDATES(CandtID, Name, Branch) appearing for entrance exam at MIT.
Candidate numbers must be Unique & every candidate number must start with MIT. User must enter
Branch in Capital letters only.
CREATE TABLE CANDIDATE( CandtId varchar2(7) PRIMARY KEY CHECK (CandtId LIKE 'MIT%'),
Name varchar(10),Branch varchar(10) CHECK(Branch=UPPER(Branch)));
Example:
SQL 59
Naming the Constraints
• If user do not specifies Constraint Name while defining Constraints, System itself gives a name.
System uses auto generate method to give unique constraints names such as – SYS_C0003461
etc. As constraint names have to be unique. In case of constraint violation, it is easy to user to track
the constraint if user defined constraint name is given.
SQL 61
Exercise
SQL 63
CREATE TABLE … AS SELECT…
The CREATE TABLE … AS SELECT… statement is used to create a new table having
same/partial structure of an existing table given with SELECT statement.
EMP_SPOUSE
Attribute DataType Size
EMPNO NUMBER 3 We can create EMP_SPOUSE table by copying
ENAME VARCHAR2 10 structure for EMPNO and ENAME from EMP
SPOUSE_NAME VARCHAR2 10 table.
EMP
Attribute Data Type Size Constraints Constraint Name
EMPNO NUMBER 3 PRIMARY KEY PK_Empno
ENAME VARCHAR2 10
MGRNO NUMBER 3 References EMP(EMPNO) FK_MgrNo_EMP
DEPTNO VARCHAR2 2 References DEPT(DNO) FK_Deptno_DEPT
DOB DATE
DOJ DATE DOJ>DOB DOJ_Grtr_DOB
SAL NUMBER 7,2 SAL>30000 SAL_Grtr_30K
SQL 64
CREATE TABLE … AS SELECT…
CREATE TABLE EMP_SPOUSE(ENO,NAME) AS SELECT EMPNO,ENAME FROM EMP;
The DROP TABLE statement allows you to remove or delete a table from the database.
Syntax:
SQL 66
Alter Table Constructs…
The ALTER TABLE statement is used to add, modify, or drop/delete columns/constraints in
a table.
Adding Column
Syntax:
Modifying Column
Syntax:
ALTER TABLE table_name
MODIFY (column_1 column_type, column_2 column_type, ... column_n
column_type);
Example: Increase the size of Salary column & modify Name column definition by adding NOT NULL rule
SQL 68
..Alter Table Constructs
DROP a Column
Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;
SQL 69
..Alter Table Constructs
SQL 70
..Alter Table Constructs
RENAME a Table
Syntax:
ALTER TABLE table_name RENAME TO New_table_name;
Example:
SQL 71
..Alter Table Constructs
Adding CHECK Constraint to a column
Syntax:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name CHECK( p ) );
Where p - predicate
Example: Add constraint to Students table to check mark2 column takes values
only in the range 0 to 100.
SQL 72
..Alter Table Constructs
Adding UNIQUE Constraint to a column
Syntax:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE( column1,column2,..columnn ) );
SQL 73
..Alter Table Constructs
Adding PRIMARY KEY Constraint to a column
Syntax:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
PRIMARY KEY (column1, column2, ... column_n) ;
Example: Assume that Person(Fname, Lname, Address) table is already created. Add
constraint to Person table to make (FName,LName) column as Primary Key.
ALTER TABLE Person ADD CONSTRAINT F_L_Name_FK
PRIMARY KEY (FName,LName);
SQL 74
..Alter Table Constructs
Adding FOREIGN KEY Constraint to a column
Syntax:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n);
Example: Assume that Person(Fname, Lname, Address) table is already created with (Fname,LName) as
Primary Key. Also a table Customer(Cust_Id, Cust_FName,Cust_Lname,Credits) is also created already.
Now we want to make (Cust_FName,Cust_Lname) as foreign key referencing Person
SQL 75
..Alter Table Constructs
Removing Constraints
Syntax:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name ;
Example: Assume that Person(Fname, Lname, Address) table is already created with
(Fname,LName) as Primary Key Also a table Customer(Cust_Id,
Cust_FName,Cust_Lname,Credits) is also created already. Now we want to remove foreign
key constraint from (Cust_FName,Cust_Lname).
SQL 76
INSERT
insert into course values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);
There will be 1 to 1 mapping between values given and order in which columns are
created in relation Course.
1st value ‘CS-437’ is mapped to column Course_id,
2nd value ‘Database Systems’ is mapped to column title and so on.
SQL 77
..INSERT
Syntax-
INSERT INTO table_name(column1,column2,..) VALUES (value1,value2,….)
Example: Course(Course_id,title,Dept_Name,Credits)
➢Insert a record into Course table by changing the order of the columns:
➢Insert a record into Course table having values to Course_id, Dept_Name columns only.
DBMS LAB 79
Insert into… Select .. From…
• Some time instead of giving data for every tuple in the INSERT INTO command,
we can insert tuples on the basis of the result of a query.
• Using SELECT statement as sub query in the INSERT INTO, we can select
(copy) some set of records from a relation(source) and insert into another
relation(Destination).
• Note that we need to take care of datatype and size compatibility.
STUD Rollno Name Course Dept MARKS Rno Course Marks Attendance
101 Ajit Algorithms CS
Example: Insert Rollno and course information of students enrolled to MCA department into
MARKS relation.
INSERT INTO MARKS(RNo, Course) SELECT Rollno, Course FROM STUD WHERE Dept=‘MCA’;
SQL 80
..INSERT
Syntax-
INSERT INTO table1(column1,column2,..) SELECT column1,column2,.. FROM table2;
Example: Consider the tables Student(Id, Name, D_name, tot_cred) and Instructor(Id,
Name, Dept_name, Salary). Add all instructors to the student relation with tot_creds set to 0
insert into student
select Id, Name, Dept_name, 0
from instructor;
OR
insert into student(ID, name, D_name)
select ID, name, dept_name
from instructor;
The select from where statement is evaluated fully before any of its results are inserted into the
relation
SQL 81
..INSERT (date value)
Example: Assume a table Stud (Rno, Name, Birth_Date)
▪ Insert a record into STUD table.
▪ TO_DATE () is a oracle inbuilt function, which converts given date value (in the form
character value) into date type.
▪ Date has a default format set. Example: Default format is say : DD-MON-YY , then
you can enter data as below without TO_DATE()
SQL 82
UPDATE
SQL 83
..UPDATE
• Example: Consider the table Instructor(Id, Name, Dept_name, Salary).
Increase salaries of instructors whose salary is over $100,000 by 3%, and all
others receive a 5% raise
• Write two update statements:
UPDATE instructor
set salary = salary * 1.03
where salary > 100000;
UPDATE instructor
set salary = salary * 1.05
where salary <= 100000;
• The order is important
SQL 84
..UPDATE –using CASE
• Same query(previous slide) as before but with case statement
update instructor
set salary = case
when salary <= 100000 then salary * 1.05
else salary * 1.03
end;
Syntax:
DELETE FROM table_name WHERE condition;
Example:
• Delete all instructors
delete from instructor
SQL 86
..DELETE
Syntax:
DELETE FROM table_name WHERE condition;
Note- Condition is involving some sub-query
Example:
• Delete all tuples in the instructor relation for those instructors associated
with a department located in the ‘Watson’ building.
delete from instructor
where dept_name in (select dept_name
from department
where building = ’Watson’);
SQL 87
..DELETE
Example:
Delete all instructors whose salary is less than the average salary of instructors
SQL 88
Tutorial 1 25-01-2025
Write the SQL-DDL commands to do the following:
1) Create the following tables
SALESMAN (Salesman_id, Name, City, Commission)
CUSTOMER (Customer_id, Cust_Name, City, Grade, Salesman_id)
ORDERS (Ord_No, Purchase_Amt, Ord_Date, Customer_id, Salesman_id)
▪ Underlined attributes are primary keys and other column with same names are foreign
keys.
▪ Assume appropriate datatype and size. Give your own proper constraint names to the
constraints
▪ Also impose following constraints-
▪ Commission – minimum 1000 and maximum 20000
▪ Grade – Silver or Gold or Diamond or Platinum
▪ Minimum Purchase_amount 500/-
2) Create a new column- Points number type into table Customer and put constraint
minimum points 10;
END
SQL 90