0% found this document useful (0 votes)
10 views51 pages

SQL Module 1

The document provides an overview of SQL, including data definition, data types, and commands for managing databases. It outlines the mapping of entity types, relationships, and SQL commands such as CREATE, ALTER, and DROP, along with constraints like PRIMARY KEY and FOREIGN KEY. Additionally, it details SQL data types, operators, and coding conventions for writing SQL queries.

Uploaded by

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

SQL Module 1

The document provides an overview of SQL, including data definition, data types, and commands for managing databases. It outlines the mapping of entity types, relationships, and SQL commands such as CREATE, ALTER, and DROP, along with constraints like PRIMARY KEY and FOREIGN KEY. Additionally, it details SQL data types, operators, and coding conventions for writing SQL queries.

Uploaded by

1ds24ai028
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dayananda Sagar College of Engineering

Kumara Swamy Layout,Bangalore-560078


Department of Artificial Intelligence & Machine Learning

MODULE - 1

SQL: SQL Data Definition and Data Types specifying basic constraints in SQL, Basic
retrieval queries in SQL, Insert, Delete and Update statements in SQL, Additional
features of SQL, More complex SQL Queries, Specifying Constraints as Assertions and
Triggers, Views (Virtual Tables) in SQL, Schema Change Statement in SQL.

Dept of AI&ML,DSCE,Bangalore pg. 1


Step 1: Mapping of Regular Entity Types
Step 2: Mapping of Weak Entity Types
Step 3: Mapping of Binary 1:1 Relation Types
Step 4: Mapping of Binary 1:N Relationship Types.
Step 5: Mapping of Binary M:N Relationship Types.
Step 6: Mapping of Multivalued attributes.
Step 7: Mapping of N-ary Relationship Types.

Step 1: Convert all strong Entity sets to Relations


• Only simple attributes will be mapped in case of composite attributes.
• Exclude multivalued attributes from mapping to Relations.

Dept of AI&ML,DSCE,Bangalore pg. 2


Step 2: Mapping of Weak Entity Types
• Create a separate relation and include all simple attributes.
• Add the primary key of the owner entity set into weak entity set.

Step 3: Mapping 1:1 Relationship types


Method 1 : Foreign Key approach
Let R and S be two Entity Sets.
1. Identify the Entity Set with total participation, say S
2. Add primary key of R into S as foreign key.

Step 4: Mapping 1:N Relationship types


• Let R and S be Entity sets (with 1:N) where S is having total participation in
Relationship.
• Add Primary key of R into S as Foreign key. (Primary key from “1” side to “N”
side as Foreign key.

Dept of AI&ML,DSCE,Bangalore pg. 3


Step 5: Mapping M:N Relationship types
Create a third relation containing the primary keys of both the Entity sets and add descriptive
attributes if any.

Step 6: Mapping Multivalued attributes


• For each multivalued attribute, create a separate Relation.
• Add Primary Key of Entity set in new Relation as a Foreign Key.
• The Foreign Key attribute and Multivalued attribute will become Composite Key.

Dept of AI&ML,DSCE,Bangalore pg. 4


Step 7: Mapping N-ary relationships
• For each N-ary relationships, create a separate relation.
• New relation will contain the Primary Keys of all Entity Sets forming N-ary
Relationship.

Structured Query Language

• SQL is used to interact with a database to manage and retrieve the data.
• DBMS processes SQL request retrieves the requested data from the database and returns it.
• This process of requesting data from the database and receiving back the result is called a
database query and hence the name SQL (Structured query language)
• SQL is mainly used for creating tables, inserting, updating and deleting records.

Categories of SQL commands

1. Data Definition Language (DDL)


2. Data Manipulation Language (DML)
3. Data Control Language (DCL)

Dept of AI&ML,DSCE,Bangalore pg. 5


Data types in SQL

[Link] Data Type Description


Syntax
1 Char(size) Fixed length strings.
It can store upto 2000 bytes.
The parameter size is the no. of characters to store.
The space is padded.
Example : if char(10) is the datatype and the string is „DBMS‟, it
is stored as „DBMS „
2 Varchar2(size) Variable length strings.
It can store upto 4000 bytes.
The parameter size is the no. of characters to store.
Example : if char(10) is the datatype and the string is „DBMS‟, it
is stored as „DBMS‟„
3 Number(s) It stores integer value with maximum no. of digits specified as s.
Example : Number(2) stores a 2 digit integer number.
4 Number(p, s) Max. Precision is 38 digits
Where : p is the precision & s is the scale
Example : Number(7,2)
This stores a number that has 5 digits before the decimal and 2
digits as fractional part like 56734.56
st st
5 Date
It stores an date between 1 Jan 4712 BC and 31 Dec 9999 AD
Format : YYYY-MM-DD
DD-MON-YYYY
DD-MON-YY
6 Time Format : HH:MM:DD

7 Timestamp It includes both date and time fields.


Format : YYYY-MM-DD HH:MI:SS

Operators in SQL

Operator Description Example

= Equal to Author = 'Alcott'

<> or != Not equal to Dept <> 'Sales'


(many DBMSs accept != in addition to <>)
> Greater than Hire_Date > '2012-01-31'

< Less than Bonus < 50000.00

>= Greater than or equal Dependents >= 2

<= Less than or equal Rate <= 0.05

Dept of AI&ML,DSCE,Bangalore pg. 6


BETWEEN Between an inclusive range Cost BETWEEN 100.00 AND
500.00

LIKE Match a character pattern First_Name LIKE 'Will%'

IN Equal to one of multiple possible values DeptCode IN (101, 103, 209)

IS or IS Compare to null (missing data) Address IS NOT NULL


NOT NULL

Note
Case sensitivity in SQL
SQL is NOT case sensitive
SQL keywords are NOT case sensitive
SQL data types are NOT case sensitive
TABLE Name is NOT case sensitive
Column Names are NOT case sensitive
Row values for VARCHAR, CHAR, DATE, TIME, TIMESTAMP data type are case sensitive

Coding convention
All the keywords must be written in UPPER CASE.
All the table names, column names must be written in lower case.

The values of the columns whose data type is CHAR, VARCHAR or DATE must be mentioned in
single quotes. Example : „S1001‟, ‟15-AUG-2010‟, „1GA14CS101‟

The values that are mentioned after the VALUES keyword must follow the same order as the
columns mentioned after the table name.

SQL Commands
DDL

1. Create Command
2. Alter Command
3. Drop Command
4. Rename Command
5. Truncate Command

1. Create Command
• DDL command.
• Works with columns of a table.
• Used to create the columns/attributes of the table.
• CREATE is used along with the keyword TABLE.

Dept of AI&ML,DSCE,Bangalore pg. 7


Syntax :
CREATE TABLE tablename
(
fieldname1 datatype [constraint],
fieldname2 datatype [constraint], ......
filednamen datatype [constraint]
);

Constraints in SQL

1. PRIMARY KEY constraint


2. Foreign key constraint
3. NOT NULL
4. UNIQUE
5. CHECK
6. DEFAULT

1. PRIMARY KEY constraint


• Uniquely identifies each row of the table.
• Primary key is UNIQUE and NOT NULL
Example :
Table : Department

DEPTNO DNAME LOCATION


10 Account New York
20 Operations Dallas
30 Sales Chicago
40 Research Boston

CREATE TABLE department (


deptno int primary key, dname
varchar(15), location varchar(20)
);

2. Foreign Key constraint


• A foreign key in one table points to a primary key in another table.
• Foreign key constraint is used to prevent actions that would destroy links between tables.
• It also prevents invalid data from being inserted into the foreign key column because it has
one of the values contained in the table it points to.
• Foreign key can have duplicate values but it must contain the same values as primary key.

Dept of AI&ML,DSCE,Bangalore pg. 8


Table : Employee

EMPID EMPNAME JOB HIREDATE SALARY COMM DEPTNO


7356 Smith Clerk 17-Nov-16 2000 20
7499 Scott Salesman 08-Dec-18 1700 300 30
7521 Adams Clerk 15-Mar-17 1900 20
7654 Allen Manager 01-Jan-10 3400 10
7934 Jones Manager 16-Dec-11 3300 10
7688 Martin Salesman 10-Nov-19 1500 300 30

CREATE TABLE employee (


empid number(4) primary key, empname
varchar(20) not null, job varchar(15),
hiredate date, salary
number(6), comm int,
deptno int references department(deptno)
);

3. NOT NULL
• It implies that value has to be provided for the column(s) compulsorily.
• It prevents null values to be entered.
Example :
CREATE TABLE persons (
p_id number(3) primary key, name
varchar(10) not null, address
varchar(10),
city varchar(10)
);

4. Unique
• It implies that the values in the column(s) should be distinct.
• A column with unique constraint can have null value.

CREATE TABLE customer (


cust_id varchar(10) constraint pk_custid primary key, cust_name varchar(20)
not null,
DOJ date,
userid varchar(15) unique, password
varchar(15) not null
);

Dept of AI&ML,DSCE,Bangalore pg. 9


5. CHECK
It is used to check a condition at column level.

CREATE TABLE
emp (
emp_id varchar(20) primary key, empname
varchar(10) not null, deptno number(5),
salary number(7) check (salary>1000)
);

6. DEFAULT
• It is used to provide default value at column level.
• The DEFAULT constraint can also be used to insert system values, by using functions like
sysdate

CREATE TABLE Student (


usn varchar(10) primary key, name
varchar(20),
marks float,
grade varchar(3) default 'A', DOJ date
default sysdate
);

INSERT INTO student VALUES ('1GA15CS045', 'Amit', 78.5, default,


default);
INSERT INTO student VALUES ('1GA16CS123', 'Yuva', 68.5, 'B', '12- JUL-16');

USN NAME MARKS GRADE DOJ


1GA15CS045 Amit 78.5 A 21-OCT-20
1GA16CS123 Yuva 68.5 B 12-JUL-16

FOREIGN KEY (foreign_key_columns)


REFERENCES parent_table(parent_key_columns)
ON UPDATE action
ON DELETE action;

Note : The ON UPDATE and ON DELETE specify which action will execute
when a row in the parent table is updated and deleted.

The following are permitted actions :

[Link] ACTION, 2. CASCADE, [Link] NULL, and 4. SET DEFAULT


Delete actions of rows in the parent table

If you delete one or more rows in the parent table, you can set one of the following actions:
Dept of AI&ML,DSCE,Bangalore pg. 10
 ON DELETE NO ACTION: SQL Server raises an error and rolls back the delete action on the row in
the parent table.
 ON DELETE CASCADE: SQL Server deletes the rows in the child table that is corresponding to the
row deleted from the parent table.
 ON DELETE SET NULL: SQL Server sets the rows in the child table to NULL if the corresponding
rows in the parent table are deleted. To execute this action, the foreign key columns must be nullable.
 ON DELETE SET DEFAULT SQL Server sets the rows in the child table to their default values if the
corresponding rows in the parent table are deleted. To execute this action, the foreign key columns
must have default definitions. Note that a nullable column has a default value of NULL if no default
value specified.

By default, SQL Server appliesON DELETE NO ACTION if you don‟t explicitly specify any action.

Update action of rows in the parent table

If you update one or more rows in the parent table, you can set one of the following actions:

 ON UPDATE NO ACTION: SQL Server raises an error and rolls back the update action on the row in
the parent table.
 ON UPDATE CASCADE: SQL Server updates the corresponding rows in the child table when the
rows in the parent table are updated.
 ON UPDATE SET NULL: SQL Server sets the rows in the child table to NULL when the
corresponding row in the parent table is updated. Note that the foreign key columns must be null able
for this action to execute.
 ON UPDATE SET DEFAULT: SQL Server sets the default values for the rows in the child table that
have the corresponding rows in the parent table updated.

DELETE CASCADE:
ON DELETE CASCADE clause in MySQL/SQL is create at foreign key. By using this option,
it automatically remove the matching records from the child table when we delete the rows from
the parent table. It is a kind of referential action related to the foreign key.

UPDATE CASCADE:
ON UPDATE CASCADE clause in MySQL/SQL is create at foreign key. By using UPDATE
CASCADE in the referencing table it used to update the matching records from the child table
automatically when we update the rows in the parent table.
* These two CANNOT be used with alter command

Dept of AI&ML,DSCE,Bangalore pg. 11


Foreign Keys with cascade delete
CREATE TABLE DEPT_LOC
(
Dnumber Integer, Location
Varchar(15),
Primary Key (Dnumber, Location),
Foreign Key (Dnumber) References Department(Dnumber)
ON DELETE CASCADE
);

CREATE TABLE ParentTable


(
ParentID INT PRIMARY KEY,
Column1 VARCHAR(50),
Column2 INT
)

CREATE TABLE ChildTable


(
ChildID INT PRIMARY KEY,
ParentID INT FOREIGN KEY REFERENCES ParentTable(ParentID) ON DELETE CASCADE
ON UPDATE CASCADE,
Column1 VARCHAR(50),
Column2 INT
)

2. Alter Command

• DDL command.
• Works with columns of a table.
• Used to add, delete, or modify columns in an existing table.
• Used to add and drop various constraints on an existing table.
• Works with the keywords ADD / MODIFY / DROP
Syntax :
ALTER TABLE tablename ADD/MODIFY/DROP (fieldname datatype [constraint]);

Examples :
• ALTER TABLE persons ADD(phone varchar(10));
• ALTER TABLE persons MODIFY(name varchar(15));
• ALTER TABLE persons MODIFY(phone varchar(12) constraint ph not null);
• ALTER TABLE persons DROP(constraint ph);
• ALTER TABLE cust_details ADD constraint pk_cust_accno primary key(account_no);
• ALTER TABLE cust_transaction ADD constraint fk_custaccno foreign key (account_no)
references cust_details (account_no);

Dept of AI&ML,DSCE,Bangalore pg. 12


• To rename a column : ALTER TABLE persons RENAME COLUMN name TO p_name;
ALTER TABLE old_table_name RENAME TO new_table_name;
or
RENAME old_table _name To new_table_name ;

RENAME Employee To Coding_Employees ;

ALTER TABLE table_name


RENAME COLUMN old_name TO new_name;

Note :
• We can change data type and length of the column.
• If the table has only one column, ALTER cannot be used to drop the column.
• Column to be modified should be empty to decrease the column length.

3. Drop Command
• It is used to delete both columns and rows of a table.
• There is no way to recover the data. (ROLLBACK command does not work)

Syntax :
DROP TABLE tablename;
Example : DROP TABLE persons;

TRUNCATE TABLE

TRUNCATE TABLE table_name;

TRUNCATE TABLE Employee;

DESCRIBE TABLE
{DESCRIBE | DESC} table_name;

SQL Commands
DML

1. Insert Command
• DML command.
• Works with records of a table.
• Used to insert records of the table.
• INSERT is used along with the keywords INTO and VALUES.

[Link] values without specifying column:


INSERT INTO table_name VALUES (value1, value2, value3....);

Dept of AI&ML,DSCE,Bangalore pg. 13


INSERT INTO items_tbl VALUES(1, "Soap", 5, 200, "2021-07-08");

[Link] values with specifying column:


Syntax : INSERT INTO table (column1, column2, ... ,column n ) VALUES
(value1, value 2, ... ,value n );

INSERT INTO items_tbl(ID, Item_Name, Item_Quantity, Item_Price, Purchase_Date) VALUES


(1, "Soap", 5, 200, "2021-07-08");

3. Insert multiple values with specifying column:


INSERT INTO items_tbl(ID, Item_Name, Item_Quantity, Item_Price, Purchase_Date) VALUES
(1, "Soap", 5, 200, "2021-07-08"), (2, "Toothpaste", 2, 80, "2021-07-
10"), (3, "Pen", 10, 50, "2021-07-12"), (4, "Bottle", 1, 250, "2021-07-
13"), (5, "Brush", 3, 90, "2021-07-15"), ( 6, "Notebooks", 10, 1000, "2021-07-26"));

[Link] Multiple values using single statement:


Syntax : INSERT INTO table (column1, column2, ... ,column n ) VALUES
(&column1, &column2, ... ,&column n )
[Link] multiple Records from existing table
INSERT INTO Table1 (column1, Column 2)

SELECT col 1, col 2 FROM Table2;

INSERT INTO T1 (A, B) SELECT C1, C2 FROM T2;

Dept of AI&ML,DSCE,Bangalore pg. 14


Example 1 : Structure of the Table : Student
Field Name Data type Constraint
USN Varchar(10) Primary key
Name Varchar(10) Not null
Stream Varchar(10)
DOJ Date
Marks Number(5,2)

INSERT INTO student VALUES(„1GA14CS067‟, „Lakshmi‟, „CSE‟,‟12- JUL-14‟,83.3);

Example 2 : Structure of the Table : Customer


Field Name Data type Constraint
Cust_ID Varchar(10) Primary key
Cust_Name Varchar(10) Not null
Dateof Registration Date
UserID Varchar(10) Not null
Password Varchar(10) Not null

INSERT INTO customer VALUES(„C5‟, „Simon‟, NULL,


„simon1005‟,‟Symon@123‟);
Cust_ID Cust_Name Dateof Registration UserID Password
C5 Simon simon1005 Symon@123

INSERT INTO customer (cust_ID, cust_name, user_ID, password)


VALUES („C5‟, „Simon‟, „simon1005‟,‟Symon@123‟);
Cust_ID Cust_Name Dateof Registration UserID Password
C5 Simon simon1005 Symon@123

2. Update Command
• DML command.
• Works with records.
• Used to update the values of the records.
• UPDATE is used with the keyword SET.
Syntax :
1. It used to update the specified column value
UPDATE tablename SET(columnname=value );
or
2. It used to update the specified column value for given condition
UPDATE tablename SET(columnname=value ) [WHERE condition]);

Dept of AI&ML,DSCE,Bangalore pg. 15


UPDATE table_name SET [column_name1= value1,... colu
mn_nameN = valueN] [WHERE condition]
or
UPDATE table_name
SET column_name = expression
WHERE conditions ;
or
UPDATE tableDestination
SET [Link] = value
WHERE EXISTS (
SELECT [Link]
FROM tblSource
WHERE tblSource.join_col = tblDestination. Join_col
AND [Link] = value)
Increase the stipend of all the students by 20%
UPDATE student SET stipend=stipend+0.2*stipend;

Add an amount of 500 to all CSE and Mech students


UPDATE student SET stipend=stipend+500 WHERE stream='CSE' OR stream='MECH';

Increase the scholarship of all EC students by 30% who have got „A grade
UPDATE student SET scholarship=scholarship+0.3*scholarship WHERE stream='EC' AND
grade='A';

Change the grades of all the students to „A‟ who have got greater than or equal to 75 marks
UPDATE student SET grade='A' WHERE marks>=75;

Dept of AI&ML,DSCE,Bangalore pg. 16


3. Delete Command

• DML command.
• Works with records.
• Used to delete all / specified records of a table.
• DELETE is used with the keyword FROM.
Syntax : it delete all values of table
DELETE FROM tablename;

Syntax : it delete specified values of table for given condition.

DELETE FROM tablename [WHERE condition];

Delete the records of all the EC students


DELETE FROM student WHERE stream='EC';

Delete the student details who have got the stipend in 3000s
DELETE FROM student WHERE stipend BETWEEN 3000 AND 3999;

Delete the details who have not got scholarship


DELETE FROM student WHERE scholarship IS NULL;

Summary

Column CREAT CREATE TABLE student


s (DDL) E (usn varchar(10));
CREATION
TABLE
Rows INSERT INTO student VALUES
INSERT INTO
(DML) („1GA14CS009‟);
Column
DESC DESC student;
s (DDL)
DESCRIPTION
Rows
SELECT SELECT * FROM student;
(DML)
Column ALTER TABLE ALTER TABLE student
s (DDL) -- MODIFY MODIFY (usn varchar(15));
MODIFICATION UPDDATE student SET
Rows UPDATE -
usn=‟1GA14CS020‟
(DML - SET
WHERE
)
usn=‟1GA14CS009‟;
Columns
DROP TABLE DROP TABLE student;
(DDL)
DELETION
Rows
DELETE DELETE FROM student;
(DML)

Dept of AI&ML,DSCE,Bangalore pg. 17


ALTER TABLE student
ALTER TABLE
Column RENAME COLUMN usn
-- RENAME
RENAME TO
regno;

Table RENAME RENAME student TO class;

4. Select Command
• DML command.
• Works with records of a table.
• Used to display all or specified records of the table.
• SELECT is used along with the keywords FROM.
• Also used with the keyword WHERE on giving conditions on rows.

Syntax : To retrieve all column of specified table

SELECT *
FROM < Table List>;

Syntax : To retrieve the column details of specified table

SELECT < Column List>


FROM < Table List>;

Syntax : To retrieve the column details of specified table for given condition.

SELECT < Column List>


FROM < Table List>
WHERE < Condition >;

SELECT */column name1, column name2,. ... FROM tablename [WHERE CONDITION];

1. Retrieve the name of employee .


SELECT EMP_NAME
FROM EMPLOYEE;
Dept of AI&ML,DSCE,Bangalore pg. 18
EMP_NAME
GOVIND
ADARSH
BHARATH
2. Retrieve the name of employee whose salary
is 20000 .
SELECT EMP_NAME
FROM EMPLOYEE
Where emp_salary=20000;
EMP_NAME
GOVIND
BHARATH

3. To retrieve EMP_ID, EMP_NAME and


DEPT_NAME whose salary is greater than 6000.
SELECT EMP_ID, EMP_NAME, DEPT_NAME
FROM EMPLOYEE, DEPARTMENT
WHEREEMPLOYEE.EDEPT_NO=DEPARTMENT.
DEPT_NO;

Example : Table : student


Dept of AI&ML,DSCE,Bangalore pg. 19
ATTRIBUTE DATA TYPE CONSTRAINT
USN Varchar(10) Primary Key
NAME Varchar(10)
SEM Varchar(3)
STREAM Varchar(5)
DOJ Date
MARKS Number(4,1)
GRADE Varchar(1)
STIPEND Number(4)
SCHOLARSHIP Number(4)

Create table student (


USN varchar(10) constraint pk_usn primary key, NAME
varchar(10),
SEM varchar(3),
STREAM varchar(5),
DOJ date,
MARKS number(4,1),
GRADE varchar(1),
STIPEND number(4),
SCHOLARSHIP
number(4)
);

USN NAME SE STREA DOJ MARK GRA STIPE SCHO


M M S DE ND LARS
HIP
1GA14CS034 Manjunath 5B CSE 12-JUN-14 78.5 B 4000

1GA13EC090 Sujay 7B EC 22-JUL-13 89.2 A 4500 4000

1GA15ME109 Vikas Gupta 3C MECH 08-MAY-15 68.6 C 3000

1GA13CS004 Akash Malhotra 7A CSE 12-MAY-13 73.1 B 3500

1GA15EC012 Karan 3A EC 30-AUG-15 90.6 A 5000 4500

1GA14ME015 Divakar Patil 5A MECH 09-JUN-14 75.4 B 4000

1GA14CS003 Amit Tripathi 5A CSE 13-JUN-14 64.4 C 2500

1GA13CS122 Seema 7B CSE 13-JUL-13 88.5 A 4500 4000

1GA15EC022 Mohan Kumar 3B EC 01-AUG-15 92.0 A 5000 4500

1GA14EC004 Suhas Chandra 5A EC 15-JUN-14 67.5 C 3000

Display all the records of the table student.


Dept of AI&ML,DSCE,Bangalore pg. 20
SELECT * FROM student;

Display all the records of “CSE” stream.


SELECT * FROM student WHERE stream='CSE';

Display name, semester and stream of students whose stipend is 5000.


SELECT name, sem, stream FROM student WHERE stipend=5000;

Display all the details who are not in “EC” stream.


SELECT * FROM student WHERE stream!='EC‟;
OR
SELECT * FROM student WHERE stream<>'EC';

Display all the records who are either in „MECH‟ or who have got C grade.
SELECT * FROM student WHERE stream='MECH‟ OR grade='C';

Display all the details of CS students who are in “5A”


SELECT * FROM student WHERE stream=‟CSE‟ AND sem=‟5A‟;

Dept of AI&ML,DSCE,Bangalore pg. 21


Operator LIKE, NOT LIKE, BETWEEN, NOT BETWEEN, IN, NOT
IN, IS NULL, IS NOT NULL
Syntax :
<Column Name> LIKE ‘PATTERN’

<Column Name> BETWEEN value1 AND value2


 value1 is the beginning value of the range.
 value2 is the ending value of the range (inclusive).

SELECT column1, column2, column3,....columnN


FROM table_name
WHERE column BETWEEN value1 AND value2;

Display all the details who are getting a stipend between 3500 and 4000.
SELECT * FROM student WHERE stipend>=3500 AND stipend<=4000;
OR
SELECT * FROM student WHERE stipend BETWEEN 3500 AND 4000;

Display usn, name, stream and marks of all the students whose marks are in the range 65 to
75.
SELECT usn, name, stream, marks FROM student WHERE marks BETWEEN
65 AND 75;

Display all the details whose marks are not in 60s.


SELECT * FROM student WHERE marks NOT BETWEEN 60 AND 69.9;

Display all the details whose names begin with A.


SELECT * FROM student WHERE name LIKE 'A%';
Note :
„%‟ matches with zero or any number of characters.
„_‟ (underscore) matches with a single character.

Dept of AI&ML,DSCE,Bangalore pg. 22


Display all the details whose names end with n.
SELECT * FROM student WHERE name LIKE '%n';

Display the details whose have exactly 5 characters.


SELECT * FROM student WHERE name LIKE ' ';
Display the details whose names have „u‟ as 2nd letter.
SELECT * FROM student WHERE name LIKE '_u%';

Display the details who are in 7th semester.


SELECT * FROM student WHERE sem LIKE '7_';

Display the details who are not in 3rd semester.


SELECT * FROM student WHERE sem NOT LIKE '3_';

Display the details of all Mechanical students who are in 5th semester.
SELECT * FROM student WHERE stream='MECH' AND sem like '5_';

Display the details of 7th semester students who have got „A‟ grade.
SELECT * FROM student WHERE sem LIKE '7_' AND grade='A';

IN / NOT IN

Display the details of studies in 3,5,7 semester students.


SELECT * FROM student WHERE sem IN(3,5,7);

Display the details of student are not studying 3,5,7 semester.


SELECT * FROM student WHERE sem IN(3,5,7);

ALL
The ANY and ALL operators allow you to perform a comparison between a single column value and a
range of other values.

Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <,
or <=).

SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name
Dept of AI&ML,DSCE,Bangalore pg. 23
FROM table_name
WHERE condition);

ANY
SQL ANY compares a value of the first table with all values of the second
table and returns the row if there is a match with any value.
SELECT column
FROM table1
WHERE column OPERATOR ANY (
SELECT column
FROM table2
);

ORDER by CLAUSE

Dept of AI&ML,DSCE,Bangalore pg. 24


[Link] column 1, column 2, … , column n
FROM table_name
ORDER BY <column name 1 order, column name 2 order
>;
or
[Link] column 1, column 2, … , column n
FROM table_name
WHERE <condition>
ORDER BY <column name 1 order, column name 2 order
>;
Or

3. SELECT column 1, column 2, … , column n


FROM table_name
WHERE <condition>
GROUP BY column name 1, column name 2
HAVING < condition>
ORDER BY <column name 1 order, column name 2 order
>;
Display the records in ascending order of USN.
SELECT * FROM student ORDER BY usn;

Note : default order is Ascending/ASC


Display the details in descending order of names.
SELECT * FROM student ORDER BY name DESC;

Display the records whose marks are in 80s in ascending order.


SELECT * FROM student WHERE marks BETWEEN 80 AND 89.9 ORDER BY
marks;
Note : order by must come at the end.

IS / IS NOT NULL
Display the details who have not got scholarship.
Dept of AI&ML,DSCE,Bangalore pg. 25
SELECT * FROM student WHERE scholarship IS NULL;

Display the details of students who have got scholarship.


SELECT * FROM student WHERE scholarship IS NOT NULL;

Differences between = and LIKE


= LIKE
Can be used with column of any data Must be used with column with the data types
type CHAR, VARCHAR, DATE, TIME only. (strings)
It is used to check the condition for an It is used to check the condition for a similar value
exact value
No special symbols used % for matching any no. of characters
_ for matching exactly one character

DISTINCT
• By default, the select statement retrieves all the rows that are filtered by select statement.
This may contain duplicate roes.
• Distinct helps to avoid duplicate values.

Display the different streams.


SELECT DISTINCT(stream) FROM student;
DISTINCT (STREAM)
CSE
EC
MECH

Arithmetic Operators
 The standard arithmetic operators '+', '-'. '*', and '/' (for addition, subtraction, multiplication, and
division, respectively) can be applied to numeric values in an SQL query result

Aggregate Functions
Dept of AI&ML,DSCE,Bangalore pg. 26
The aggregate function takes a complete column of data as its argument and produces a single
resultant data value that summarizes the column.
• Sum() It computes the total of a given column.
• Avg() It computes the average of a given column.
• Min() It finds the smallest value in a given column.
• Max() It finds the largest value in a given column.
• Count() It counts the number of non-null values in a given column.
• Count(*) It counts rows of query results including rows which have NULL values. If
there are no rows, it returns a value 0.
Find the sum of the marks.
SELECT SUM(marks) FROM student;

Find the sum of all the marks who have „C‟ grade.
SELECT SUM(marks) FROM student WHERE grade='C';

Find the average of stipend who are not in „EC‟ stream.


SELECT AVG(stipend) FROM student WHERE stream!='EC';

Find the annual stipend.


SELECT stipend*12 FROM student;

Count the number of all the records.


SELECT COUNT(*) FROM student;

 Find the maximum salary, the minimum salary, and the average salary among all employees.

SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY)


FROM EMPLOYEE

 Find the maximum salary, the minimum salary, and the average salary among employees who work for the
'Research' department.

Q16: SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY)


FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME='Research'

Group By Command
It is used in select statement to collect data across multiple records and group the results by one or
more columns.

Display different streams and their count.


SELECT stream, COUNT(stream) FROM student GROUP BY stream;
STREAM COUNT(STREAM)
CSE 4
EC 4
MECH 2
Display different streams, find the sum of marks of each stream.
SELECT stream, SUM(marks) FROM student GROUP BY stream;
Dept of AI&ML,DSCE,Bangalore pg. 27
Display different streams, minimum and maximum marks stream wise.
SELECT stream, MIN(marks),MAX(marks) FROM student GROUP BY stream;

Having clause
• It is used along with group by clause.
• It is used to specify search condition for groups.

Display different streams and their count which are appearing more than twice.
SELECT stream, COUNT(stream) FROM student GROUP BY stream HAVING count(stream)>2;

Differences between order by and group by

ORDER BY GROUP BY

Works for individual fields Works for a group of values

WHERE is used with order by to give HAVING is used with group by to give condition
condition
Aggregate functions cannot be used Aggregate functions can be used with group by
with order by

Differences between WHERE and HAVING

WHERE HAVING

WHERE is used with order by to give HAVING is used with group by to give condition
condition
Uses relational operators like =,<, > etc Uses aggregate functions like sum(), min() etc

Give Example Give Example

Ambiguous Attribute Names, Aliasing, Renaming, and Tuple Variables

• In SQL, the same name can be used for two (or more) attributes as long as the attributes are in
different tables.
• If this is the case, and a multiple table query refers to two or more attributes with the same
name, we must qualify the attribute name with the relation name to prevent ambiguity.
• This is done by prefixing the relation name to the attribute name and separating the two by a
period.

Example :
SELECT Fname, Address, [Link] FROM EMPLOYEE, DEPARTMENT
WHERE DName = 'Accounts' AND [Link] = [Link];
Dept of AI&ML,DSCE,Bangalore pg. 28
We can also rename the table names to shorter names by creating an alias for each table name to
avoid repeated typing of long table names.
SELECT Fname, Address, [Link] FROM EMPLOYEE E, DEPARTMENT D
WHERE [Link] = [Link];

Aliases are the temporary names given to table or column for the purpose of a particular SQL query. It
is used when name of column or table is used other than their original names, but the modified name
is only temporary.
• Aliases are created to make table or column names more readable.
• The renaming is just a temporary change and table name does not change in the original
database.
• Aliases are useful when table or column names are big or not very readable.
• These are preferred when there are more than one table involved in a query.

Set operators
• UNION
• MINUS
• INTERSECT
must satisfy Union Compatibility

To retrieve all names from both STUDENT and FACULTY.


SELECT SNAME FROM STUDENT
UNION
SELECT FNAME FROM FACULTY;

To retrieve all the names present in both STUDENT and FACULTY.

SELECT SNAME FROM STUDENT


INTERSECTION
SELECT FNAME FROM FACULTY;
SNAME
------------
VISHNU
To retrieve the names at only present in STUDENT.

SELECT SNAME FROM STUDENT


MINUS
SELECT FNAME FROM FACULTY;
Dept of AI&ML,DSCE,Bangalore pg. 29
SNAME
------------
RAJ

To retrieve the faculty names at not present in STUDENT.


SELECT FNAME FROM FACULTY
MINUS
SELECT SNAME FROM STUDENT;

SNAME
------------
Ganesh
Types of JOIN
• Inner joins
• Equi join (=)
• Natural join ( Joining attribute name should be same in both table if not rename
attribute then apply join condition)
• Theta join(>,<,<>,>=,=<)
• Cross Join(X)
• Self-Join

SELECT <column list>


FROM TABLE_R JOIN TABLE_S ON <Join condition> ;

• Inner joins

Select *
From T1 JOIN T2 T1.P=T2.A;

Or
• Equi join

Select *
From T1,T2
WhereT1.P=T2.A;

Dept of AI&ML,DSCE,Bangalore pg. 30


Outer join
• LEFT OUTER JOIN
• RIGHT OUTER JOIN
• FULL OUTER JOIN

SELECT <column list>


FROM TABLE_R LEFT OUTER JOINTABLE_S ON <Join condition> ;

SELECT *
FROM T1 LEFT OUTER JOIN T2 ON T1.P=T2A ;

Select *
From T1,T2
WhereT1.P=+T2.A;

SELECT *
FROM T1 RIGHT OUTER JOIN T2 ON T1.P=T2A;

Dept of AI&ML,DSCE,Bangalore pg. 31


Select *
From T1,T2
WhereT1.P += T2.A;
P Q R A B C
10 a 5 10 b 5
10 a 5 10 b 5
25 a 6 25 c 3
15 b 8 NULL NULL NULL

SELECT *
FROM T1 FULL OUTER JOIN T2 ON T1.P=T2A;

P Q R A B C
10 a 5 10 b 5
10 a 5 10 b 5
25 a 6 25 c 3
15 b 8 NULL NULL NULL

Cross Join
Each row of n table mapping to all row of m table then output will n*m rows

Select *
From T1 cross join T1 B

Self Join
Joining a table with itself.
Select *
From T1 A,T1 B
WhereA.P=T1.R;

 Examples:

Q1: SELECT [Link], [Link], [Link], [Link]


FROM EMPLOYEE E S
WHERE [Link]=[Link]

can be written as:

Q1: SELECT [Link], [Link], [Link], [Link]


FROM (EMPLOYEE E LEFT OUTER JOIN EMPLOYEES
ON [Link]=[Link])

Q2: SELECT FNAME, LNAME, ADDRESS


FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND DNUMBER=DNO
 could be written as:

Dept of AI&ML,DSCE,Bangalore pg. 32


Q2: SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE JOIN DEPARTMENT ON DNUMBER=DNO)
WHERE DNAME='Research‟

or as:
Q2: SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE NATURAL JOIN DEPARTMENT
AS DEPT(DNAME, DNO, MSSN, MSDATE)
WHERE DNAME='Research‟

 TH Another Example;
– Q3 could be written as follows; this illustrates multiple joins in the joined tables

Q3: SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS


FROM (PROJECT JOIN DEPARTMENT ON DNUM=DNUMBER)
JOIN EMPLOYEE ONMGRSSN=SSN) )
WHERE PLOCATION='Stafford’

Nested Queries

• Some queries require that existing values in the database be fetched and then used in a
comparison condition.
• Such queries can be conveniently formulated by using nested queries, which are complete
select-from-where blocks within another SQL query. That other query is called the outer
query.
• These nested queries can also appear in the WHERE clause or the FROM clause or the
SELECT clause or other SQL clauses as needed.
• A Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause.
• A subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.
• Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.

Rules :
1. Subqueries must be enclosed within parentheses.
2. A subquery can have only one column in the SELECT clause, unless multiple columns are
in the main query for the subquery to compare its selected columns.
3. An ORDER BY command cannot be used in a subquery, although the main query can use
an ORDER BY. The GROUP BY command can be used to perform the same function as
the ORDER BY in a subquery.
4. Subqueries that return more than one row can only be used with multiple value operators
such as the IN operator.
5. The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
6. A subquery can return a single value, a single row, a single column, or a whole table. They are
called scalar subqueries.

Dept of AI&ML,DSCE,Bangalore pg. 33


SELECT column FROM table
WHERE column OPERATOR (
SELECT column FROM table
);

or

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name
OPERATOR (SELECT column_name [,column_name ] FROM table1 [, table2 ]
[WHERE]);
Or
SELECT Column_Name1, Column_Name2, ...., Column_NameN
FROM Table_Name WHERE Column_Name Comparison_Operator
( SELECT Column_Name1, Column_Name2, ...., Column_NameN
FROM Table_Name WHERE condition);

Types of SubQueries
1. Single row subqueries
2. Multiple value/column subqueries
3. Correlated subqueries
1. Single row subqueries
 They return only one row.
 Use single-row comparison operators (<, >, ≤, ≥, =, <>)
 The inner query must return only one value, otherwise error will result.
 The subquery result is then compared to the value of the column(s) in the parent
query.

2. Multiple value/Column subqueries


• Multiple-row subqueries are nested queries that can return more than one row of results to
the parent query.
• Multiple-row subqueries are used most commonly in WHERE and HAVING clauses.
• Since it returns multiple rows, it must be handled by set comparison operators (IN, ALL,
ANY).
• While IN operator works similar to OR operator, ANY operator compares a specified value
to each value returned by the sub query while ALL compares a value to every value returned
by a sub query.

3. Correlated Subquery
• A correlated subquery is one where the inner query depends on values provided by the outer
query.
• Correlated subqueries are used for row-by-row processing
• This means that in a correlated subquery, the inner query is executed repeatedly, once for
each row that might be selected by the outer query.
Dept of AI&ML,DSCE,Bangalore pg. 34
• A correlated subquery is used when result of the subquery depends on value in each
candidate row of main query.
• The inner query will be referencing the outer query.
• The outer query record is passed to the inner query, the inner query evaluates that record
and passes the data again back to the outer query.
• A correlated subquery is evaluated once for each row processed by the parent statement. The
parent statement can be a SELECT, UPDATE, or DELETE statement

. Examples :

1. Single row subqueries

Example 1:
Retrieve the employees who are earning a salary less than the average salary.

Steps :
1. Find average salary first.
SELECT avg(salary) FROM Emp;
Output of inner query :
Avg(salary) = (4400+13000+12000+8300+4400)/5 = 8420
2. Select employees where salary<the average salary calculated.
Dept of AI&ML,DSCE,Bangalore pg. 35
SELECT name, salary FROM Emp WHERE salary < 8420;
Query Statement :
SELECT name, salary FROM Emp WHERE salary < (SELECT avg(salary) FROM Emp);
Example 2:

Retrieve the details of employees who are earning a salary equal to minimum salary.
SELECT * FROM Emp WHERE salary = (SELECT MIN(salary) FROM Emp);
Example 3:
Write SQL Query to display employee name who has obtained maximum salary.
SELECT name from Emp where salary= (SELECT Max(salary) from Emp);

Example 4:
Write SQL Query to display the second highest salary.
SELECT max(salary) from Emp where salary != (SELECT Max(salary) from Emp);

Example 5:
Write SQL Query to display the second lowest salary.
SELECT min(salary) from Emp where salary != (SELECT min(salary) from Emp);

2. Multiple value/Column subqueries


Example 1:
Retrieve the employees who earn maximum salary in each job.
Steps :
1. Inner Query :
SELECT max(salary), job_id FROM Emp GROUP BY job_id ;
Output of the inner query :

2. Outer Query :
SELECT * FROM Emp WHERE (salary, job_id) IN {(8300, ACC), (4400,ASST), (13000,MGR)}

SELECT * FROM Emp WHERE (salary, job_id) IN (SELECT max(salary), job_id FROM
Emp GROUP BY job_id );

Dept of AI&ML,DSCE,Bangalore pg. 36


3. Correlated Subquery

Example 1:
Find out employees who earn a salary less than the average salary for their jobs.
SELECT name, job_id, salary FROM Emp E1 WHERE salary < (SELECT avg(salary) FROM
Emp E2 WHERE E1.job_id=E2.job_id);
NAME JOB_ID SALARY
Kavya MGR 12000

Example 2:
Find out employees who earn a salary equal to the sum of salary jobwise.

SELECT name, job_id, salary FROM Emp E1 WHERE salary = (SELECT sum(salary) FROM
Emp E2 WHERE E1.job_id=E2.job_id);
NAME JOB_ID SALARY
Saritha ACC 8300

Example 3:
Find all employee details who work in a department.

SELECT * FROM Emp WHERE EXISTS (Select * from Dept where


Dept.Emp_ID=Emp.Emp_ID);

Output :

Dept of AI&ML,DSCE,Bangalore pg. 37


 Retrieve the name of each employee who has a dependent with the same first name as the employee.

SELECT [Link], [Link]


FROM EMPLOYEE AS E
WHERE [Link] IN (SELECT ESSN
FROM DEPENDENT
WHERE ESSN=[Link] AND
[Link]=DEPENDENT_NAME)

EXISTS and NOT EXISTS Operator


 The EXISTS operator is used to test for the existence of any record in a subquery.

 The EXISTS condition in SQL is used to check whether the result of a correlated nested query is
empty (contains no tuples) or not.

 The result of EXISTS is a boolean value True or False.

 It returns TRUE if the subquery returns one or more records.

 It can be used in a SELECT, UPDATE, INSERT or DELETE statement

SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name(s)
FROM table_name
WHERE condition);

SELECT column_name(s)
FROM table_name
WHERE NOT EXISTS
(SELECT column_name(s)
FROM table_name
WHERE condition);

Differences between subquery and correlated subquery

Dept of AI&ML,DSCE,Bangalore pg. 38


Questions on Nested Queries

Example 1 :
Write the queries in SQL for the following relations.
SAILORS (sid, sname, rating, age)
BOATS (bid, bname, color)
RESERVES (sid, bid, day)

1) Find the names of sailors who have reserved the boat number „103‟.
2) Find the names of sailors who have reserved a „red‟ and a „green‟ boat.
3) Find the names of sailors who have reserved atleast one boat.
4) Find the names of sailors with age over 20 years, who have not reserved a red boat.

Solution :
We will try creating the above tables with records and then execute the query.

1) Find the names of sailors who have reserved the boat number „103‟.
SELECT sname FROM sailors s, boats b, reserves r WHERE [Link]=103 AND [Link]=[Link]
AND [Link]=[Link];

2) Find the names of sailors who have reserved a „red‟ and a „green‟ boat.
SELECT sname FROM sailors s, boats b, reserves r WHERE [Link] IN('red', 'green') AND
[Link]=[Link] AND [Link]=[Link] ;

Dept of AI&ML,DSCE,Bangalore pg. 39


3) Find the names of sailors who have reserved atleast one boat.
SELECT distinct(sname) FROM sailors s, reserves r WHERE [Link]=[Link];

4) Find the names of sailors with age over 20 years, who have not reserved a red boat.
SELECT Sname FROM sailors s, boats b, reserves r WHERE age>20 AND color!='red‟
AND [Link]=[Link] AND [Link]=[Link] ;

Example 2 :
Write queries in SQL for the following. Refer the following relations
Employee (Name, SSN, Salary, Super SSN, DNo)
Department (DNum, DName, Mgr SSN)
Dept-Locations (DNum, Dlocation)
Works ON (ESSN, PNo, Hours)
Dependent (ESSN, Dep Name, Gender)
1) Retrieve the name of the employee who gets second highest salary.
2) For each department that has more than 5 employees, retrieve the department number and
no. of its employees who have salary more than Rs.5000.
3) Retrieve the name of employees whose salary is greater than all the employees working in
either department 5 or 6.
Solution :
1) Retrieve the name of the employee who gets second highest salary.
SELECT name, max(salary) FROM Employee WHERE salary < (SELECT max(salary)
FROM Employee);

2) For each department that has more than 5 employees, retrieve the department
number and no. of its employees who have salary more than Rs.5000.
SELECT dnum, count(SSN)FROM Employee, department WHERE Dno=dnum AND
salary>5000 GROUP BY dnum HAVING count(ssn)>5;

3) Retrieve the name of employees whose salary is greater than all the employees working
in either department 5 or 6.
SELECT name FROM employee WHERE salary >(SELECT max(salary) FROM
employee WHERE dno IN(5,6);

Example 3 :
Consider the following schema and write the SQL queries
STUDENT(USN, name, branch, percentage)
Dept of AI&ML,DSCE,Bangalore pg. 40
FACULTY(FID, fname, dept, designation, salary)
COURSE(CID, cname, FID)
ENROLL(CID, USN, grade)
i) Retrieve the names of all students enrolled for the course „CS-54‟.
ii) List all the departments having an average salary of the faculties above Rs.10,000.
iii) List the names of students enrolled for the course „CS-51‟ and having „B‟ grade.

Solution :
i) Retrieve the names of all students enrolled for the course „CS-54‟.
SELECT [Link] FROM student s, course c, enroll e WHERE [Link]=[Link] AND [Link]=[Link] AND
[Link]=‟CS-54‟;

ii) List all the departments having an average salary of the faculties above Rs.10,000.
SELECT dept FROM faculty WHERE avg(salary)> (SELECT salary FROM faculty WHERE
salary>10000);

iii) List the names of students enrolled for the course „CS-51‟ and having „B‟ grade.
SELECT [Link] FROM student s, enroll e, course c WHERE [Link]=[Link] AND [Link]=[Link] AND
[Link]=‟CS-51‟ AND [Link]=‟B‟;

Example 4 :
Given the schema and write the SQL queries
EMP (Fname, Lname, SSN, Bdate, Address, Gender, Salary, Super SSN, Dno)
DEPT (Dname, Dnumber, Mgr_SSN, Mgrstartdate)
DEPT_LOC (DNumber, Dloc)
PROJECT (Pname, Pnumber, Ploc, Dnum)
WORKS_ON (WSSN, Pno, Hours)
DEPENDENT (ESSN, Dept_name, Gender, Bdate, relation)
i) Retrieve the manager name with atleast 1 dependent
ii) Retrieve the employee names who work on any of the project that „kumar‟ works
iii) Retrieve the pno, pname, no. of man hours work done on each project.
iv) Retrieve the pname which are controlled by Research department.
v) Retrieve the employee name who work for dept number 10 and have a daughter.
vi) Retrieve the list of employees and the projects they are working on, ordered by department and,
within each department, ordered alphabetically by last name, first name.
vii) For each project, retrieve the project number, the project name, and the number of employees
who work on that project.
viii) For each project on which more than two employees work, retrieve the project number, the
project name, and the number of employees who work on the project.
ix) For each project, retrieve the project number, the project name, and the number of employees
from department 4 who work on the project.

Solution :
i) Retrieve the manager name with atleast 1 dependent
SELECT fname, lname FROM emp e1, dept d1, dependent d2 WHERE [Link]=[Link] AND
Dept of AI&ML,DSCE,Bangalore pg. 41
[Link]=[Link];

ii) Retrieve the employee names who work on any of the project that „kumar‟ works
SELECT fname, lname FROM emp e, project p WHERE [Link]=[Link] AND fname=‟Kumar‟;

iii) Retrieve the pno, pname, no. of man hours work done on each project.
SELECT [Link], [Link], [Link] FROM works_on w, project p WHERE [Link]=[Link];

iv) Retrieve the pname which are controlled by Research department.


SELECT [Link] FROM project p, dept d WHERE [Link]=[Link] AND
[Link]=‟Research‟;

v) Retrieve the employee name who work for dept number 10 and have a daughter.
SELECT fname, lname FROM employee e, dependent d WHERE [Link]=[Link] AND [Link]=10
AND [Link]=‟daughter‟;

vi) Retrieve the list of employees and the projects they are working on, ordered by
department and, within each department, ordered alphabetically by last name, first name.
SELECT fname, lname, pname, dname from employee, department, project where dnumber=dno
and ssn=essn and pno=pnumber group by dname order by dname, lname, fname;

vii) For each project, retrieve the project number, the project name, and the number of
employees who work on that project.
SELECT [Link], [Link], count([Link]) FROM project p, dept d, emp e WHERE
[Link]=[Link] AND [Link]=[Link] GROUP BY pnumber;

viii) For each project on which more than two employees work, retrieve the project number,
the project name, and the number of employees who work on the project.
SELECT [Link], [Link], count([Link]) FROM project p, dept d, emp e WHERE
[Link]=[Link] AND [Link]=[Link] GROUP BY pnumber HAVING count([Link])>2;

ix) For each project, retrieve the project number, the project name, and the number of
employees from department 4 who work on the project.
SELECT [Link], [Link], count([Link]) FROM project p, dept d, emp e WHERE
[Link]=[Link] AND [Link]=[Link] GROUP BY pnumber AND dnum=4 GROUP BY
pnumber HAVING count(dnum)>2;

Example 5 :
Consider the following tables :
Works (Pname, Cname, Salary)
Lives (Pname, Street, City)
Located_In (Cname, City)

1. List the names of people who work for the company „Wipro‟ along with the cities they live
in.
2. Find the names of persons who do not work for „Infosys‟
Dept of AI&ML,DSCE,Bangalore pg. 42
3. Find the people whose salaries are more than that of all of the average salary of „Oracle‟
employees.
4. Find the persons who work and live in the same city.

Solution :

1. List the names of people who work for the company „Wipro‟ along with the cities they live
in.
Select [Link], [Link] from works w, lives l where [Link]='Wipro' and [Link]=[Link] ;

2. Find the names of persons who do not work for „Infosys‟


Select pname from works where cname!='Infosys' ;

3. Find the people whose salaries are more than that of all of the average salary of „Oracle‟
employees.
Select pname, salary from works where salary> (select avg(salary) from works where
cname='Oracle') ;

4. Find the persons who work and live in the same city.
Select [Link] from works w, lives l, located_in x where [Link]=[Link] and
[Link]=[Link] and [Link]=[Link];

Dept of AI&ML,DSCE,Bangalore pg. 43


Other SQL Constructs:
WITH and CASE

• The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database.
• The clause is used for defining a temporary relation such that the output of this temporary
relation is available and is used by the query that is associated with the WITH clause.
• Queries that have an associated WITH clause can also be written using nested sub-queries
but doing so add more complexity to read/debug the SQL query.
• WITH clause is not supported by all database system.
• The name assigned to the sub-query is treated as though it was an inline view or table.

Example :

WITH Demo (averageValue) as


(
SELECT avg(Salary) from Employee
)
SELECT EmployeeID, Name, Salary FROM Employee, Demo
WHERE [Link] > [Link];

• The CASE statement goes through conditions and returns a value when the first condition
is met (like an IF-THEN-ELSE statement).
• So, once a condition is true, it will stop reading and return the result.
• If no conditions are true, it returns the value in the ELSE clause.
• If there is no ELSE part and no conditions are true, it returns NULL.

Example 1 :

Dept of AI&ML,DSCE,Bangalore pg. 44


SELECT name, salary,
CASE
When salary <5000 then 'The salary is less than 5000‟
When salary <10000 then 'The salary is less than 10000‟
When salary <15000 then 'The salary is less than 15000'
END
FROM emp;

Dept of AI&ML,DSCE,Bangalore pg. 45


Assertions

 SQL supports the creation of assertions which are constraints not associated with only one
table.
 An assertion statement should ensure that a certain condition will always exist in the
database.
 DBMS always checks the assertion whenever modifications are done in the corresponding
table.
Examples :
• Ensuring the sum of loan amounts for each branch is less than the sum of all account
balances at the branch.
• Ensuring every loan customer keeps a minimum of $1000 in an account.

Example 1 :
Sum of loans taken by a customer does not exceed 10,00,000
CREATE ASSERTION Sumloans CHECK (1000000>= ALL SELECT sum(amount) from
borrower B, loan L where B.loan_no=L.Loan_no GROUP BY customer_name);

Example 2 :
The salary of an employee must not be greater than the salary of the manager of the
department that the employee works for.
CREATE ASSERTION salaryconstraint CHECK (NOT EXISTS (SELECT * FROM employee e,
employee m, department d where [Link]>[Link] AND [Link]=[Link] AND [Link]=[Link]));

• The basic technique for writing assertions is to specify a query that selects any tuples that
violate the desired condition.
• By including this query inside a NOT EXISTS clause, the assertion will specify that the
result of this query must be empty so that the condition will always be TRUE.
• Thus, the assertion is violated if the result of the query is not empty.

Triggers

A procedure that starts automatically if specified changes occur to the DBMS.


Three parts:
• Event (activates the trigger) (e.g., an update operation)
• Condition (tests whether the triggers should run) [Optional]
(Ex : [Link] > [Link])
• Action (what happens if the trigger runs)
Event : BEFORE|AFTER INSERT|UPDATE|DELETE ON <tableName>
Condition : SQL expression or even an SQL query (query with non-empty result means TRUE)
Action can be many different choices : SQL statements, DDL and transaction-oriented statements
like “commit”.

Dept of AI&ML,DSCE,Bangalore pg. 46


The trigger is mostly used for maintaining the integrity of the information on the database.
Example : when a new record (representing a new worker) is added to the employees table,
new records should also be created in the tables of the taxes, vacations and salaries.
Syntax :
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT | UPDATE | DELETE}
ON table_name
[FOR EACH
ROW]
WHEN (condition)
DECLARE
Declaration-
statements BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Example :
Create table words (word varchar(10));

CREATE OR REPLACE TRIGGER trim_word


BEFORE INSERT
ON words
FOR EACH ROW
BEGIN
:[Link] := trim(:[Link]);
END;

insert into words (word) values (' Hello „);


insert into words (word) values (' World „);
select word, length(word) from words;

Example

CREATE OR REPLACE TRIGGER


display_salary_changes BEFORE DELETE OR INSERT
OR UPDATE ON customer FOR EACH ROW

Dept of AI&ML,DSCE,Bangalore pg. 47


WHEN ([Link] >
0) DECLARE
sal_diff
number;
BEGIN
sal_diff := :[Link] - :[Link];
dbms_output.put_line('Old salary: ' || :[Link]);
dbms_output.put_line('New salary: ' || :[Link]);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
1 row(s) updated.
UPDATE customer Old salary: 22000
SET salary = salary + 500 New salary: 22500
WHERE id = 2; Salary difference: 500

Assertions vs Triggers

[Link] ASSERTIONS TRIGGERS


We can use Assertions when we know
We can use Triggers even particular condition
1. that the given particular condition is
may or may not be true.
always true.
When the SQL condition is not met
then there are chances to an entire Triggers can catch errors if the condition of the
2.
table or even Database to get locked query is not true.
up.

It helps in maintaining the integrity constraints


Assertions are not linked to specific
in the database tables, especially when the
3. table or event. It performs task
primary key and foreign key constraint are not
specified or defined by the user.
defined.

Assertions do not maintain any track Triggers maintain track of all changes occurred
4.
of changes made in table. in table.

Assertions vs Triggers vs Check

Triggers - a trigger is a piece of SQL to execute either before or after an update, insert, or
delete in a database. An example of a trigger in plain English might be something like: before
updating a customer record, save a copy of the current record.
Check Constraint - A check is a piece of SQL which makes sure a condition is satisfied
before action can be taken on a record. In plain English this would be something like: All
customers must have an account balance of at least $100 in their account.
Assertions - An assertion is a piece of SQL which makes sure a condition is satisfied or it
stops action being taken on a database object. It could mean locking out the whole table or
Dept of AI&ML,DSCE,Bangalore pg. 48
even the whole database.

Views in SQL

• A view is a “virtual” table that is derived from other tables.


• It allows for limited update operations (since the table may not physically be stored).
• It allows full query operations.

Example 1 :
Create table demo as select * from customer where id between 3 and 10;
CREATE VIEW cust_view AS SELECT * FROM customer WHERE salary>20000;

Example 2 :
Create a view which will display the department name, number of employees working
and total salary for each department.
CREATE VIEW view_info (deptname, no_of_emp,
totalsalary) AS
SELECT deptname, count(*), sum(salary) FROM emp, dept WHERE
[Link]=[Link] GROUP BY deptname;

When no longer needed, a view can be dropped:


DROP VIEW view_info;

View Update
• A view is supposed to be upto date. If we modify the tuples in base table on which the
view is defined, the view must automatically reflect these changes.
• Updating of view is complicated and can be ambiguous.

View Update Rules


1. A view with a single defining table is updatable if the view attributes contain the
primary key of the base relation, as well as all attributes with the NOT NULL constraint
that do not have default values specified.
2. Views defined on multiple tables using joins are generally not updatable.
3. Views defined using grouping and aggregate functions are not updatable.

Example 1 :

Dept of AI&ML,DSCE,Bangalore pg. 49


Example 2 :

Schema Change Statements in SQL

Can be used to alter a schema by adding or dropping tables, attributes, constraints, and other
schema elements.
This can be done while the database is operational and does not require recompilation of the
database schema.

1. The DROP Command


2. The ALTER Command

1. The DROP Command


• The DROP command can be used to drop named schema elements, such as tables,
domains, types, or constraints.
Dept of AI&ML,DSCE,Bangalore pg. 50
• One can also drop a whole schema if it is no longer needed by using the DROP
SCHEMA command.
• There are two drop behaviour options: CASCADE and RESTRICT.
Example : to remove the COMPANY database schema and all its tables, domains,
and other elements, the CASCADE option is used as follows:
DROP SCHEMA COMPANY CASCADE;

• If the RESTRICT option is chosen in place of CASCADE, the schema is dropped only
if it has no elements in it; otherwise, the DROP command will not be executed.
• To use the RESTRICT option, the user must first individually drop each element in
the schema, then drop the schema itself.
• If a base relation within a schema is no longer needed, the relation and its definition can
be deleted by using the DROP TABLE command.
Example : If we no longer wish to keep track of dependents of employees in the
COMPANY database, we can get rid of the DEPENDENT relation by issuing the
following command: DROP TABLE DEPENDENT CASCADE;

2. The ALTER Command


• The definition of a base table or of other named schema elements can be changed by
using the ALTER command.
• For base tables, the possible alter table actions include adding or dropping a
column (attribute), changing a column definition, and adding or dropping table
constraints.
• Example : to add an attribute for keeping track of jobs of employees to the
EMPLOYEE base relation in the COMPANY schema, we can use the command
ALTER TABLE [Link] ADD COLUMN Job VARCHAR(12);
• To drop a column, we must choose either CASCADE or RESTRICT for drop behavior.
• If CASCADE is chosen, all constraints and views that reference the column are
dropped automatically from the schema, along with the column.
• If RESTRICT is chosen, the command is successful only if no views or constraints (or
other schema elements) reference the column.
• Example : The following command removes the attribute Address from the
EMPLOYEE base table:
• ALTER TABLE [Link] DROP COLUMN Address CASCADE;

Reference:

[Link]
[Link]
[Link]
[Link]

Dept of AI&ML,DSCE,Bangalore pg. 51

You might also like