0% found this document useful (0 votes)
104 views58 pages

LM 6 - SQL Fundamentals Advanced SQL Features

The document discusses SQL fundamentals including data types, schema definition, commonly used SQL commands like SELECT, INSERT, UPDATE, DELETE and logical operators. It provides syntax and examples for each command.

Uploaded by

Bala Krish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views58 pages

LM 6 - SQL Fundamentals Advanced SQL Features

The document discusses SQL fundamentals including data types, schema definition, commonly used SQL commands like SELECT, INSERT, UPDATE, DELETE and logical operators. It provides syntax and examples for each command.

Uploaded by

Bala Krish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

KGiSL Institute of Technology

(Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai)


Recognized by UGC, Accredited by NBA (IT)
365, KGiSL Campus, Thudiyalur Road, Saravanampatti, Coimbatore – 641035.

Department of Computer Science and Engineering

Name of the Faculty : Ms. Aruna T N

Subject Name & Code : CS3492/ Database Management Systems

Branch & Department : Computer Science and Engineering

Year & Semester : II / IV

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Course Outcome

CO 1 Demonstrate fundamentals of Data models and Relational


databases - K3 LEVEL

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Syllabus
UNIT I - RELATIONAL DATABASES

Purpose of Database System – Views of data – Data Models –


Database System Architecture – Introduction to relational databases
– Relational Model – Keys – Relational Algebra – SQL
fundamentals – Advanced SQL features – Embedded SQL–
Dynamic SQL

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
TOPIC

SQL Fundamentals

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Introduction
• SQL: Structured Query Language is a simple and powerful language used to
create, access, and manipulate data and structure in the database. SQL is like
plain English: easy to understand and to write.
• Various parts of SQL are:
– Data Definition Language (DDL) – defining relation schemas
– Data Manipulation Language (DML) – manipulating relation schemas
– Transaction Control Language(TCL) – beginning & ending of the transactions
– Data Control Language(DCL)- to grant and take back authority from any database user.
– Data Query Language(DQL)- fetch data from tables based on conditions that we can easily
apply.
– Integrity – specifying integrity constraints
– View Definition – defining views for database
– Embedded SQL and Dynamic SQL – SQL commands in C, C++, COBOL or Java
– Authorization – access rights
CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Data Abstraction
Basic data types used in SQL are:
1. char(n)🡪 representing fixed length character string. Eg: to represent name, designation,
course_name
2. varchar(n)🡪 character varying. Denoting variable length character strings
3. int🡪 representing numeric values without precision
4. numeric🡪 representing a fixed point number with user specified precision. Eg:
numeric(3,2) allows 333.11 but it does not allow 3333.11
5. smallint🡪 used to store small integer value
6. real🡪 allows floating point, double precision number
7. float(n)🡪 representing floating point number with precision of atleast n digits

CS8791/CC/IVCSE/VIISEM/KG-KiTE
Basic Schema Definition
• Classification of SQL Commands
• Data Definition Language (DDL)
• Data Manipulation Language (DML)
• Data Control Language (DCL)
DDL
• SQL commands that can be used to define the database schema.
• It deals with descriptions of the database schema and is used to create and modify the
structure of database objects in database.
Examples of DDL commands are:
CREATE: used to create the database or its object
DROP: used to delete objects from the database
ALTER: used to alter the structure of the database
TRUNCATE: used to remove all records from table including all spaces allocated for
records
COMMENT: used to add comments to the data dictionary
RENAME: used to rename an object existing in the database
DML

• Commands deal with manipulation of data present in the database

Examples of DML commands are:


INSERT: used to insert data into the table
UPDATE: used to update existing data within a table
DELETE: used to delete records from a database table
LOCK: Table control concurrency.
DCL

• It deals with the rights, permissions and other controls of the database
system
Examples of DCL commands are:
GRANT: gives user’s access privileges to database
REVOKE: withdraw user’s access privileges given by using the GRANT
command
TCL
• To keep a check on other commands and their affect on the
database. These commands can annul changes made by other
commands by rolling the data back to its original state. It can also
make any temporary change permanent.

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
DQL

• It is used to fetch data from tables based on conditions that we can


easily apply.
Examples of DQL commands are:
SELECT: used to retrieve data from the database

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Commonly used SQL Commands
1. Create Table
Syntax: create table table_name;
Eg: create table Student(RollNo int, Name varchar(10), Marks numeric(3,2), Primary key(RollNo));

2. Insert
Syntax:
i) Insert into table_name(column1, column2,column3…..) values(value1, value2, value3,….);
ii) Insert into table_name values(value1, value2, value3,……);
Eg:
i) Insert into Student(RollNo, Name, Marks) values(1, ‘Sharan’, 95.50);
ii) Insert into Student values(1, ‘Sharan’, 95.50);
Commonly used SQL Commands
3. Delete
Syntax: delete from table_name where condition;
Eg: delete from Student where RollNo = 10;

4. Alter
Syntax:
i) alter table table_name add column_name datatype;
ii) alter table table_name drop column column_name;
Eg:
iii) alter table Student add address varchar(20);
iv) alter table Student drop column address;
SELECT , FROM, WHERE

• SELECT: similar to projection which selects the attributes based on the condition described
by WHERE clause
• SELECT col1,col2,…,coln FROM table_name;
• FROM: takes an relation name as an argument from which attributes are to be
selected/projected
• SELECT * FROM table_name;
• WHERE: defines condition which must match in order to qualify the attributes to be
projected
• SELECT col1,col2,…,coln FROM table_name WHERE condition;

Eg:
SELECT SName FROM Student WHERE Age > 18;
Update
• Modifying the existing record of a table
• Syntax:
UPDATE table_name SET col1 = value1, col2 = value2,… WHERE
condition;
RollNo Name City
Eg: UPDATE Student SET city =
111 AAA Mumbai
‘chennai’ WHERE RollNo = 111
222 BBB Bangalore
RollNo Name City
Student
111 AAA Chennai
222 BBB Bangalore
Delete
• Delete one or more records based on some condition
• Syntax:
DELETE FROM table_name WHERE condition; (or)
DELETE FROM table_name ;
Eg: DELETE FROM student ‘chennai’
RollNo Name City WHERE RollNo = 111
111 AAA Mumbai
222 BBB Bangalore RollNo Name City
222 BBB Bangalore
Student
Logical Operators
• Using WHERE clause we can use the operators such as AND,OR and NOT
• Syntax:
i) SELECT col1,col2,… FROM table_name WHERE condition1 AND
condition2 AND Condition3…;
ii) SELECT col1,col2,… FROM table_name WHERE condition1 OR
condition2 OR Condition3…;
iii) SELECT col1,col2,… FROM table_name WHERE NOT
condition;
Example
1. SELECT col1,col2,… FROM table_name WHERE condition1
AND condition2 AND Condition3…;

Eg: SELECT Rollno, Name, City FROM Student WHERE Rollno =


111 AND City=‘Mumbai’;
RollNo Name City
111 AAA Mumbai RollNo Name City
222 BBB Bangalore 111 AAA Mumbai
Student
Example
2. SELECT col1,col2,… FROM table_name WHERE condition1 OR
condition2 OR Condition3…;

Eg: SELECT Rollno, Name, City FROM Student WHERE City =


‘Mumbai’ or City=‘Bangalore’;
RollNo Name City
111 AAA Mumbai
222 BBB Bangalore RollNo Name City
111 AAA Mumbai
Student
222 BBB Bangalore
Example
3. SELECT col1,col2,… FROM table_name WHERE NOT condition;

Eg: SELECT Rollno, Name, City FROM Student WHERE City = NOT
City=‘Bangalore’;

RollNo Name City


111 AAA Mumbai
222 BBB Bangalore RollNo Name City
111 AAA Mumbai
Student
ORDER BY
• For getting the Sorted records in the table we use ORDER BY command.
• The ORDER BY keyword sorts the records in ascending order by default.
Syntax: SELECT col1,col2,…,coln FROM table_name ORDER BY
col1,col2,.. ASC|DESC
Eg: SELECT * FROM Student ORDER BY Rollno DESC;
RollNo Name City
111 AAA Mumbai RollNo Name City
222 BBB Bangalore 222 BBB Bangalore
Student 111 AAA Mumbai
Alteration
• We can add new column or delete some column from the table using these
alteration commands.
Syntax: ALTER TABLE table_name ADD column_name datatype;
ALTER TABLE table_name DROP column_name datatype;
Eg: ALTER TABLE Student ADD Email varchar(30);
RollNo Name City Email
RollNo Name City
222 BBB Bangalore NULL
111 AAA Mumbai
111 AAA Mumbai NULL
222 BBB Bangalore
Student RollNo Name Email
222 BBB NULL
Eg: ALTER TABLE Student DROP COLUMN City; 111 AAA NULL
Constraints
• Specify rules for data in a table
• Various Types of Constraints
• Primary Key
• Foreign Key
• Unique
• NOT NULL
• CHECK
• IN Operator
Constraints – Primary Key

• Is defined to uniquely identify the records from the table

• It must contain Unique Values

• Eg: CREATE TABLE Student (AdharNo int, Name Varchar(20),


Address Varchar(30), City Varchar(10), PRIMARY KEY(AdharNo));
Constraints – Foreign Key

• It is used to link two tables.

• Foreign Key for one table is actually a primary key of another table.

• Eg: CREATE TABLE Department( DeptID int, DeptName


Varchar(20), EmpID int, PRIMARY KEY(DeptID), FOREIGN
KEY(EmpID) REFERENCES Employee(EmpID));
Constraints – UNIQUE & NOT NULL

• Unique: To prevent same values in a column

• NULL: It means unknown values

• Eg: CREATE TABLE Employee(EmpID INT NOT NULL, Name


varchar(20), Mobileno INT NOT NULL UNIQUE);
Constraints – CHECK

• It is used to limit the value range that can be placed in a column.

• Eg: CREATE TABLE Employee(Sno int PRIMARY KEY, Name


varchar(20), Age > 0);
Constraints – IN

• IN operator is just similar to OR operator

• Eg: SELECT * FROM Employee WHERE empID IN (1,3);


empID Name Salary
1 AAA 10000 empID Name Salary
2 BBB 20000 1 AAA 10000
3 CCC 30000 2 BBB 20000
4 DDD 40000 3 CCC 30000
5 EEE 50000
Build-in Datatypes
• Date: date containing four digit year-month-date
– Eg: date ‘2018-12-22’
• Time: time of day in hours, minutes, hours
– Eg: time ’09:00:30’
• Timestamp: date + time of day
– Eg: timestamp ‘2018-12-22 09:00:30’
• Interval: period of time
– Eg: interval ‘1’ day
• Extract: extract the values of individual fields from date/time/timestamp
– Eg: extract (year from r.starttime)
• Cast: cast string types to date/time/timestamp
– Eg: cast < string-valued-expression> as date
CS8791/CC/IVCSE/VIISEM/KG-KiTE
User Defined Datatypes

• Create type construct in SQL creates user-defined type

create type Dollars as numeric(12,2) final


• Create domain construct in SQL creates user-defined domain types

create domain person_name char(20) not null

• Types and domains are similar

• Domains can have constraints, such as not null, specified on them

CS8791/CC/IVCSE/VIISEM/KG-KiTE
Large Object Types

• Large objects (photo, video, CAD files, etc…) are stored as large object
• When a query returns a large object, a pointer is returned rather than the large
object itself
• 2 large object are:
– Blob (Binary Large Object): object is a collection of uninterrupted binary data
(whose interpretation is left to an application outside of the database system)
– Clob (Character Large Object): object is a collection of character data
Domain and Key Constraints

• Domain constraints are the most elementary form of integrity constraint

• Test values inserted in the database, and test queries to ensure that the comparisons
make sense
• New domains can be created from existing datatypes
– Eg: create domain Dollars numeric(12,2)

create domain Pounds numeric(12,2)


• We cannot assign or compare a value of type Dollars to a value of type Pounds

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Integrity Constraints
• Integrity constraints guard against accidental damage to the database, by
ensuring that authorized changes to the database do not result in a loss of data
consistency
• Eg: A customer must have a (non-null) phone number
Constraints on a Single Relation
• Null
• Primary key
• Unique
• Check(p)
– Where ‘p’ is a predicate

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Contd..
1. Not null constraint
Eg: Declare branch_name for branch is not null
branch_name char(15)not null

2. Unique constraint: attributes form a candidate key


Syntax: unique(A1,A2,A3,……Am)

3. Check clause
Eg: Declare branch_name as the primary key for branch and ensure that the values of
assets are non-negative
create table branch(branch_name char(15), branch_city char(30), assets
integer, primary key (branch_name), check(assets >= 0))
String Operations
• String Comparisons: = , < , > ,<=, >=, <>, ||,etc.,
• Pattern Matching can be performed on strings using two types of
special characters:
• Percent (%) : It matches zero, one or multiple characters.
• Underscore ( _ ) : The _ Character matches any single character.
• Patterns are Case Sensitive
• Eg: ‘Data%’ matches any string beginning with data.
• ‘_ _ _’ matches any string of exactly three characters
• ‘_ _ _%’ matches any string of atleast length 3 characters
CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Example : Employee Database

EmpID EmpName Department Date_of_Join


1 AAA Marketing 1 – Jan
2 ABC Manager 2 – Jan
3 CCC Manager 3 – Jan
4 DDD Accounts 4 - Jan
5 FEEEE Sales 5 – Jan
6 FFFFF Purchase 6 - Jan

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
SQL Statement
• SELECT * FROM Employee WHERE EmpName LIKE ‘A%’;
EmpID EmpName Department Date_of_Join
1 AAA Marketing 1 – Jan
2 ABC Manager 2 – Jan

• SELECT EmpName FROM Employee WHERE EmpName LIKE


‘A%C’;
EmpName
ABC

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
SQL Statement
• SELECT EmpName FROM Employee WHERE EmpName LIKE
‘F_ _ _ _’;

EmpID EmpName
5 FEEEE
6 FFFFF

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
SET Operations : UNION
• To use this UNION clause, each SELECT statement must have
• Same Number of columns selected
• Same Number of column expressions
• Same Data Type
• Have them in the same order
• Syntax:

SELECT column1 [,column 2] FROM table1 [,table2] [WHERE


condition] UNION SELECT column1 [,column 2] FROM table1
[,table2] [WHERE condition]
CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Example
sid sname age sid isbn day
1 AAA 20 1 005 25-03-24
2 BBB 21 2 006 26-03-24
3 CCC 22
3 007 27-03-24
4 DDD 23
Reserve
Student
isbn bname Author
005 DBMS XYZ
006 OS PQR Book
007 DAA ABC

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Example : UNION

SELECT S.sname FROM Student S, Reserve R, Book B WHERE S.sid =


R.sid AND R.isbn = B.isbn AND B.bname = ‘DBMS’ UNION SELECT
S.sname FROM Student S, Reserve R, Book B WHERE S.sid = R.sid
AND R.isbn = B.isbn AND B.bname = ‘OS’;

Finds the names of the students who have reserved the “DBMS” book or
“OS” Book
CS3492/DBMS/IICSE/IVSEM/KG-KiTE
SET Operations : INTERSECT

• Common entries between two tables can be represented with the help of
INTERSECT operator

• Syntax:

SELECT column1 [,column 2] FROM table1 [,table2] [WHERE


condition] INTERSECT SELECT column1 [,column 2] FROM table1
[,table2] [WHERE condition]

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Example : INTERSECT

SELECT S.sid , S.sname FROM Student S, Reserve R, Book B WHERE


S.sid = R.sid AND R.isbn = B.isbn AND B.bname = ‘DBMS’
INTERSECT SELECT S.sname FROM Student S, Reserve R, Book B
WHERE S.sid = R.sid AND R.isbn = B.isbn AND B.bname = ‘OS’;

Finds the names of the students who have reserved both the “DBMS”
book and“OS” Book
CS3492/DBMS/IICSE/IVSEM/KG-KiTE
SET Operations : EXCEPT

• It is used to represent the set difference in the query. It is used to


represent the entries that are present in one table and not in other.

• Syntax:

SELECT column1 [,column 2] FROM table1 [,table2] [WHERE


condition] EXCEPT SELECT column1 [,column 2] FROM table1
[,table2] [WHERE condition]

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Example : EXCEPT

SELECT S.sid , S.sname FROM Student S, Reserve R, Book B WHERE


S.sid = R.sid AND R.isbn = B.isbn AND B.bname = ‘DBMS’ EXCEPT
SELECT S.sname FROM Student S, Reserve R, Book B WHERE S.sid =
R.sid AND R.isbn = B.isbn AND B.bname = ‘OS’;

Finds the students who have reserved both the “DBMS” book but not
reserved “OS” Book
CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Aggregate Functions
• It is used to perform a calculation on a set of values to return a single
scalar value.
• Built-in Aggregate Functions:
• Average (avg)
• Minimum (min)
• Maximum (max)
• Total (sum)
• Count

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
SQL Statement : Aggregate Functions
• Eg: SELECT AVG(marks) FROM Students; Test
(To Compute average marks of the students) Id Value
• Eg: SELECT COUNT(*) FROM Test; 11 100
4 22 200
• Eg: SELECT COUNT(ALL id) FROM Test; 33 300
3 NULL 400
• Eg: SELECT Min (Value) FROM Test;
Eg: SELECT Sum (Value)
100
FROM Test;
• Eg: SELECT Max (Value) FROM Test; 1000
400
CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Group By

• It is used to group rows that have the same values.

• Syntax:

SELECT column_name FROM table_name WHERE condition


GROUP BY column_name;

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Example : Student Table
Sid Sname Marks city Student
1 AAA 60 Pune
2 BBB 70 Mumbai
3 CCC 90 Pune
4 DDD 55 Mumbai

Eg: SELECT SUM(Marks), city FROM Student GROUP BY city;


SUM (Marks) city
150 Pune
125 Mumbai

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Having

• Only the groups that meet the HAVING criteria will be returned.

• Syntax:

SELECT column_name FROM table_name WHERE condition


GROUP BY column_name HAVING condition;

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Example : Student Table
Sid Sname Marks city Student
1 AAA 60 Pune
2 BBB 70 Mumbai
3 CCC 90 Pune
4 DDD 55 Mumbai
5 EEE 84 Chennai

Eg: SELECT SUM(Marks), city FROM Student GROUP BY city


SUM (Marks) city
HAVING city IN(‘Pune’, ‘Mumbai’);
150 Pune
125 Mumbai
CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Nested Queries

• A query is written inside a query. The result of inner query is used in


execution of outer query.

• The execution of inner query is independent of outer query.

• There are 2 types of Nested Queries


• Independent Query
• Co-related Query

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Example : Nested Queries
Sid Sname Phone
1 AAA 1111
2 BBB 2222
3 CCC 3333
Student_City
4 DDD 4444 Sid cid
1 101
Student
1 103
cid cname
2 101
101 Pune
3 102
102 Mumbai
4 102
103 Chennai
4 103
City
CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Example: Independent Query
1. Find the cid for cname = ‘Pune’ or ‘Chennai’
• Eg: SELECT cid FROM city WHERE cname = ‘Pune’ or ‘Chennai’;

2. Using cid , find the sid.


• Eg: SELECT sid FROM Student_city WHERE cid IN ( SELECT cid FROM city
WHERE cname = ‘Pune’ or cname = ‘Chennai’);

3. To find the sname who live in city ‘Pune’ or ‘Chennai’


Eg: SELECT sname FROM Student WHERE sid IN (SELECT sid FROM
Student_city WHERE cid IN ( SELECT cid FROM city WHERE cname = ‘Pune’ or
cname = ‘Chennai’);
CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Example: Co-related Query
• In co-related nested query, the output of inner query depends on the row which
is being currently executed in outer query.

• Eg: If we want to find out sname of Student who live in city with cid as 101,

SELECT sname FROM Student S WHERE EXISTS (SELECT * FROM


Student_City SC WHERE S.sid = SC.sid and SC.cid = 101 )

CS3492/DBMS/IICSE/IVSEM/KG-KiTE
Modification of Databases
• To make changes in the existing databases
• Insertion
• Insert INTO table_name (col1,col2,..,) values (val1,val2,..,)
• Eg: Insert INTO Student (Rollno,Name,Marks) values (111,’AAA’,90);
• Deletion
• DELETE FROM table_name WHERE condition;
• Eg: DELETE FROM Student WHERE Rollno = 10;
• Updation
• Update table_name set col1 = val1, col2 = val2,.., where condition;
• Eg: Delete Student Set Name = ‘www’ where Rollno = 101;
CS3492/DBMS/IICSE/IVSEM/KG-KiTE
DCL Commands
• It is used to control privileges in database.
• GRANT
• It is used to provide access or privilege on the database.
• Syntax: GRANT privilege_name ON object_name TO { user_name | PUBLIC |
role_name} [WITH GRANT OPTION];
• Eg: GRANT SELECT ON student_details TO user1;
• REVOKE
• It removes user access rights or privileges to the database.
• Syntax: REVOKE privilege_name ON object_name FROM {user_name | PUBLIC |
role_name}
• Eg: REVOKE SELECT ON student_details FROM user1;
CS3492/DBMS/IICSE/IVSEM/KG-KiTE

You might also like