DBS Unit II
DBS Unit II
Unit – II
SQL
Dr. S. Manikandan
HOD-IT
1
SQL
• 1970 – Sequel
• 1986 – SQL (Structured Query Language)
• It is not case sensitive
• It is a programming language for relational databases
like MySQL, Oracle, Sybase
• Non relational databases like MongoDB, DynamoDB do
not use SQL
2
Parts of SQL
• DDL
• Interactive DML
• Integrity Constraints – Commands
• View definition
• Transaction control – commands for
specifying beginning and ending of
transaction
• Embedded SQL and Dynamic SQL –
how SQL statements can be
embedded with C, C++,Java
3
Data Definition
• char(n)
• varchar(n)
• int
• numeric(p,d)
numeric (3,1) allows 78.2
• Float(n)
5
Basic Schema Definition in SQL
What is Relational Database?
Relational database means the data is stored as well as retrieved in the form of
relations (tables).
Table 1 shows the relational database with only one relation
called STUDENT which
stores ROLL_NO, NAME, ADDRESS, PHONE and AGE of students.
STUDENT
6
Terminologies
These are some important terminologies that are used in terms of relation.
Attribute: Attributes are the properties that define a relation.
e.g.; ROLL_NO, NAME etc.
Tuple: Each row in the relation is known as tuple. The above relation
contains 4 tuples, one of which is shown as:
Degree: The number of attributes in the relation is known as degree of the
relation. The STUDENT relation defined above has degree 5.
Cardinality: The number of tuples in a relation is known as cardinality.
The STUDENT relation defined above has cardinality 4.
Column: Column represents the set of values for a particular attribute.
The column ROLL_NO is extracted from relation STUDENT.
7
SQL Commands
8
DDL
9
• CREATE It is used to create a new table in
the database.
• Syntax:
• CREATE TABLE TABLE_NAME (COLUM
N_NAME DATATYPES[,....]);
• Example:
• CREATE TABLE EMPLOYEE(Name VAR
CHAR2(20), Email VARCHAR2(100), DOB
DATE);
10
• DROP: It is used to delete both the
structure and record stored in the table.
• Syntax
• DROP TABLE table_name;
• Example
• DROP TABLE EMPLOYEE;
11
• ALTER: It is used to alter the structure of the
database. This change could be either to modify the
characteristics of an existing attribute or probably to
add a new attribute.
• Syntax:
• To add a new column in the table
• ALTER TABLE table_name ADD column_name COLU
MN-definition;
• To modify existing column in the table:
• ALTER TABLE table_name MODIFY(column_definitio
ns....);
• EXAMPLE
• ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
• ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20)); 12
• TRUNCATE: It is used to delete all the
rows from the table and free the space
containing the table.
• Syntax:
• TRUNCATE TABLE table_name;
• Example:
• TRUNCATE TABLE EMPLOYEE;
13
DML Commands
14
• INSERT: The INSERT statement is a SQL query. It is
used to insert data into the row of a table.
Syntax:
• INSERT INTO TABLE_NAME
(col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN); Or
• INSERT INTO TABLE_NAME
VALUES (value1, value2, value3, .... valueN);
Example
• INSERT INTO book (Author, Subject) VALU
ES (“Abraham", "DBMS"); 15
• UPDATE: This command is used to update or
modify the value of a column in the table.
Syntax:
• UPDATE table_name SET [column_name1= v
alue1,...column_nameN = valueN] [WHERE C
ONDITION]
For example:
UPDATE students
SET User_Name = 'Sonoo'
WHERE Student_Id = '3'
16
DELETE: It is used to remove one or more
row from a table.
Syntax:
• DELETE FROM table_name [WHERE co
ndition];
For example:
DELETE FROM book
WHERE Author=“Abraham";
17
Banking Database
Relational Schema
• branch(branch_name, branch_city,assets)
• customer(cus_name,cus_street,cus_city)
• loan(loan_num,branch_name,amount)
• borrower(cus_name,loan_num)
• account(account_num,branch_name,balance)
• depositor(cus_name,account_num)
18
Basic Structure of SQL Queries
19
select branch_name
from loan
20
Book Table
21
Author table
Author_name Country
Arora U.S.
Kapoor Canada
Basu India
Sinha India
22
Select clause
23
SQL uses logical connectives and,or,not
24
Rename Operation
• Old-name as new-name
Select title, Unit_price*1.15 as New_price from book;
Tuple variables
Tuple variables are defined in the from clause by the
way of as clause
Find the titles of books with author name and author
country
select title, B.author_name, country
From book as B, author as A
Where B.author_name = A.author_name
25
String operations
27
Aggregate Functions
Aggregate functions are functions that take a
collection of values as input and return a single
value. SQL offers five built-in aggregate
functions.
SQL offers five built in aggregate function:
• Average: avg
• Minimum: min
• Maximum: max
• Total: sum
• Count: count
28
Aggregate Functions
29
Aggregate Functions
31
Ex: On every book author receives 10 %
royalty. Display total royalty amount
received by each author till date.
32
• Select Author_name, sum(Unit_price * .10)
“Royalty Amount” from book
group by Author_name;
33
Having
34
• Display publisher wise total price of books
published, except for publisher “PHI”.
select Publisher_name, sum(Unit_price) “Total
Book Amount” from book group by
Publisher_name
having Publisher_name < > ‘PHI’;
Publisher_name Total book amount
Nirali 250
SciTech 300
Technical 850
35
• Display royalty amount received by
those authors whose second
character of name contains ‘a’.
36
• Select Author_name, sum(Unit_price *
0.10) “Royalty Amount” from book
group by Author_name
having Author_name like ‘_a%’;
Author_name Royalty amount
Basu 85
Kapoor 30
Sinha 25
37
Set Operations
38
Example – Set Operations
Depositor Table
Customer_Name Account_no
John 1001
Sita 1002
Vishal 1003
Ram 1004
Borrower Table
Customer_Name Loan_no
John 2001
Tonny 2002
Rohit 2003
Vishal 2004
39
Union
40
Customer_Name Customer_Name
John John
Sita Sita
Vishal Vishal
Ram Ram
Tonny John
Rohit Tonny
Rohit
Vishal
41
Intersect
• Intersect operation returns common records from the
output of both queries.
Find all customers who have a loan and account at the
bank
select Customer_Name from Depositor
intersect
select Customer_Name from Borrower;
The intersect operation automatically terminates
duplicates. If we want to retain all duplicates, we must
write intersect all in place of intersect
select Customer_Name from Borrower
Intersect all
select Customer_Name from Depositor;
42
Cusomer_name
John
Vishal
43
Except
Customer_name
Ram
Sita
44
Null Values
45
Nested Subquries
46
Set Memberships
47
in
from book
Author_name Country
where Pub_year = ‘2004’);
Arora U.S.
Basu India
48
Not in
49
Not in
Oracle
Unix
50
Set Comparison
51
JOIN
52
Student
Student
Course
53
INNER JOIN
54
• SELECT StudentCourse.COURSE_ID, Student.NAME,
Student.AGE FROM Student INNER JOIN
StudentCourse ON Student.ROLL_NO =
StudentCourse.ROLL_NO;
Output:
55
LEFT JOIN
• This join returns all the rows of the table on the left
side of the join and matching rows for the table on
the right side of join. The rows for which there is no
matching row on right side, the result-set will
contain null. LEFT JOIN is also known as LEFT
OUTER JOIN.
56
SELECT student.NAME, StudentCourse.COURSE_ID
FROM Student LEFT JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;
57
RIGHT JOIN
58
SELECT Student.NAME, StudentCourse.COURSE_ID
FROM Student RIGHT JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;
59
FULL JOIN
60
• SELECT Student.NAME, StudentCourse.COURSE_ID
FROM Student FULL JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;
61
VIEW
62
StudentDetails
StudentMarks
63
CREATING VIEWS
64
Creating View from a single table
65
• In this example, we will create a view named
StudentNames from the table StudentDetails.
CREATE VIEW StudentNames AS SELECT S_ID,
NAME FROM StudentDetails ORDER BY NAME;
If we now query the view as,
• SELECT * FROM StudentNames;
66
Creating View from multiple tables
67
DELETING VIEWS
68
UPDATING VIEWS
There are certain conditions needed to be satisfied to update a
view. If any one of these conditions is not met, then we will
not be allowed to update the view.
• The SELECT statement which is used to create the view
should not include GROUP BY clause or ORDER BY clause.
• The SELECT statement should not have the DISTINCT
keyword.
• The View should have all NOT NULL values.
• The view should not be created using nested queries or
complex queries.
• The view should be created from a single table. If the view is
created using multiple tables then we will not be allowed to
update the view.
69
• We can use the CREATE OR REPLACE
VIEW statement to add or remove fields
from a view.
• CREATE OR REPLACE VIEW
view_name AS SELECT
column1,coulmn2,.. FROM table_name
WHERE condition;
70
For example, if we want to update the view MarksView and
add the field AGE to this View from StudentMarks Table,
we can do this as:
• CREATE OR REPLACE VIEW MarksView AS SELECT
StudentDetails.NAME, StudentDetails.ADDRESS,
StudentMarks.MARKS, StudentMarks.AGE FROM
StudentDetails, StudentMarks WHERE
StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:
• SELECT * FROM MarksView;
71
Inserting a row in a view
We can insert a row in a View in a same way as we do in
a table. We can use the INSERT INTO statement of
SQL to insert a row in a View
INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
72
Deleting a row from a View
73
Transactions
• A transaction is a unit of work that is performed against a
database. Transactions are units or sequences of work
accomplished in a logical order, whether in a manual
fashion by a user or automatically by some sort of a
database program.
• A transaction is the propagation of one or more changes to
the database. For example, if you are creating a record or
updating a record or deleting a record from the table, then
you are performing a transaction on that table. It is
important to control these transactions to ensure the data
integrity and to handle database errors.
• Practically, you will club many SQL queries into a group
and you will execute all of them together as a part of a
transaction.
74
• The following commands are used to
control transactions.
• COMMIT − to save the changes.
• ROLLBACK − to roll back the changes.
• SAVEPOINT − creates points within the
groups of transactions in which to
ROLLBACK.
• SET TRANSACTION − Places a name
on a transaction.
75
COMMIT
• Transactional control commands are only used with
the DML Commands such as - INSERT, UPDATE
and DELETE only. They cannot be used while creating
tables or dropping them because these operations are
automatically committed in the database.
• The COMMIT Command
• The COMMIT command is the transactional command
used to save changes invoked by a transaction to the
database.
• The COMMIT command is the transactional command
used to save changes invoked by a transaction to the
database. The COMMIT command saves all the
transactions to the database since the last COMMIT or
ROLLBACK command.
76
The syntax for the COMMIT command is as follows.
COMMIT;
Example
SQL> DELETE FROM CUSTOMERS WHERE AGE = 25;
SQL> COMMIT;
Thus, two rows from the table would be deleted and the
SELECT statement would produce the following result.
77
ROLLBACK Command
79
SAVEPOINT Command
80
• SQL> SAVEPOINT SP1;
Savepoint created.
• SQL> DELETE FROM CUSTOMERS WHERE ID=1;
1 row deleted.
• SQL> SAVEPOINT SP2;
Savepoint created.
• SQL> DELETE FROM CUSTOMERS WHERE ID=2;
1 row deleted.
• SQL> SAVEPOINT SP3;
Savepoint created.
• SQL> DELETE FROM CUSTOMERS WHERE ID=3;
1 row deleted.
81
• Now that the three deletions have taken place, let us
assume that you have changed your mind and
decided to ROLLBACK to the SAVEPOINT that you
identified as SP2. Because SP2 was created after
the first deletion, the last two deletions are undone −
• SQL> ROLLBACK TO SP2;
• Rollback complete.
• Notice that only the first deletion took place since
you rolled back to SP2.
82
RELEASE SAVEPOINT Command
83
SET TRANSACTION Command
84
SQL Data Types and Schemas
Date and Time Data Type
Datatype Description
85
SQL Character and String Data Types
Datatype Description
86
Procedure
• A procedure is a subprogram that performs
a specific action.
create or replace procedure <proc_name> [parameter
list] is
<local declaration>
begin
(executable statements)
[exception] (exception handlers)
end;
A Procedure has two parts:
• Specification
• Body
87
• Specification begins with the key word
procedure and ends with the procedure
name or parameter list.
• Procedure body begins with the keyword
is and ends with the keyword end.
• Syntax to execute a procedure is
exec <proc_name> (parameters);
88
Types of parameters passed to subprogram
89
create or replace procedure "INSERTUSER"
(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user values(id,name);
end;
BEGIN
insertuser(101,'Rahul');
dbms_output.put_line('record inserted successfully');
END;
90
Function
91
Example
92
Integrity Constraints
93
94
Domain constraints
95
Entity integrity constraints
96
Referential Integrity Constraints
97
Example
98
Key constraints
99
Trigger
100
Explanation of syntax
• create trigger [trigger_name]: Creates or replaces an
existing trigger with the trigger_name.
• [before | after]: This specifies when the trigger will be
executed.
• {insert | update | delete}: This specifies the DML
operation.
• on [table_name]: This specifies the name of the
table associated with the trigger.
• [for each row]: This specifies a row-level trigger, i.e.,
the trigger will be executed for each row being
affected.
• [trigger_body]: This provides the operation to be
performed as trigger is fired
101
Example:
102
Example
103
insert into Student values(1,"ABCDE", 20, 20, 20, 0, 0);
104
End
105