0% found this document useful (0 votes)
7 views61 pages

Module 3

Module 3 covers SQL Data Manipulation Language (DML) including queries, nested queries, and SQL set operations like UNION, INTERSECT, and JOIN types. It also discusses physical data organization concepts and SQL aggregate functions such as COUNT, SUM, AVG, MIN, and MAX. The document provides syntax examples for SQL queries and operations to manipulate and retrieve data from databases.

Uploaded by

Aann Mariya Sabu
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)
7 views61 pages

Module 3

Module 3 covers SQL Data Manipulation Language (DML) including queries, nested queries, and SQL set operations like UNION, INTERSECT, and JOIN types. It also discusses physical data organization concepts and SQL aggregate functions such as COUNT, SUM, AVG, MIN, and MAX. The document provides syntax examples for SQL queries and operations to manipulate and retrieve data from databases.

Uploaded by

Aann Mariya Sabu
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
You are on page 1/ 61

Module 3

• SQL DML (Data Manipulation Language) - SQL queries on single and


multiple tables, Nested queries (correlated and non-correlated), Aggregation
and grouping, Views, assertions, Triggers, SQL data types.

• Physical Data Organization - Review of terms: physical and logical records,


blocking factor, pinned and unpinned organization. Heap files, Indexing,
Singe level indices, numerical examples, Multi-level-indices, numerical
examples, B-Trees & B+-Trees (structure only, algorithms not required),
Extendible Hashing, Indexing on multiple keys – grid files.
Basic Query Structure
• A typical SQL query has the form:

select A1, A2, ..., An


from r1, r2, ..., rm
where P

– Ai represents an attribute
– Ri represents a relation
– P is a predicate.
• The result of an SQL query is a relation.
• The basic structure of SQL expression consist of three clauses
– Select clause
– From clause
– Where clause
The select Clause
• The select clause lists the attributes desired in the result of a
query
– corresponds to the projection operation of the relational
algebra
• Example: find the names of all instructors:
select name
from instructor
• NOTE: SQL names are case insensitive (i.e., you may use
upper- or lower-case letters.)
– E.g., Name = NAME = name
The select Clause

SELECT name
from`instructor`
The select Clause
• SQL allows duplicates in relations as well as in query results.
• To force the elimination of duplicates, insert the keyword distinct
after select.
• Find the department names of all instructors, and remove
duplicates
select distinct dept_name
from instructor
• The keyword all specifies that duplicates should not be removed.

select all dept_name


from instructor
The select Clause

SELECT DISTINCT `dept_name`


FROM `instructor`
The select Clause

• An asterisk in the select clause denotes “all attributes”


select *
from instructor
The select Clause
• The select clause can contain arithmetic expressions involving the
operation, +, –, , and /, and operating on constants or attributes of tuples.
– The query:
select ID, name, salary/12
from instructor
would return a relation that is the same as the instructor relation,
except that the value of the attribute salary is divided by 12.
– Can rename “salary/12” using the as clause:
select ID, name, salary/12 as monthly_salary
The select Clause

SELECT `ID`,`name`,`salary`/12
FROM `instructor` WHERE 1
The where Clause
• The where clause specifies conditions that the result must satisfy
– Corresponds to the selection predicate of the relational algebra.
• To find all instructors in Comp. Sci. dept
select name
from instructor
where dept_name = ‘Comp. Sci.'
• Comparison results can be combined using the logical connectives and, or, and
not
– To find all instructors in Comp. Sci. dept with salary > 80000
select name
from instructor
where dept_name = ‘Comp. Sci.' and salary > 80000
• Comparisons can be applied to results of arithmetic expressions.
The where Clause

SELECT `name` FROM `instructor`


WHERE `dept_name`="Comp. Sci."
The from Clause
• The from clause lists the relations involved in the query
– Corresponds to the Cartesian product operation of the relational
algebra. of 2 relations
• Find the Cartesian product instructor X teaches
select *
from instructor, teaches
– generates every possible instructor – teaches pair, with all attributes
from both relations.
– For common attributes (e.g., ID), the attributes in the resulting table
are renamed using the relation name (e.g., instructor.ID)
• Cartesian product not very useful directly, but useful combined with where-
clause condition (selection operation in relational algebra).
The from Clause

SELECT * FROM instructor,teaches


SQL Set Operations

• These operations are performed on multiple tables


• Types of Set Operations

– UNION

– UNION ALL

– INTERSECT

– MINUS
Union

• The SQL Union operation is used to combine the result of two or more
SQL SELECT queries.
• In the union operation, all the number of datatype and columns must be
same in both the tables on which UNION operation is being applied.
• The union operation eliminates the duplicate rows from its resultset.
• Syntax
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;
ID NAME ID NAME

1 JACK 3 JACKSON

2 HARRY 4 STEPHAN

3 JACKSON 5 DAVID

Fig 1:Table 1 Fig 2: Table 2

SELECT * FROM First


ID NAME
UNION
SELECT * FROM Second; 1 JACK

2 HARRY

3 JACKSON

4 STEPHAN

5 DAVID
Union All

• Union All operation is equal to the Union operation.


• It returns the set without removing duplication and sorting the data.
• Syntax:
SELECT column_name FROM table1
UNION ALL
SELECT column_name FROM table2;

Example: Using the above First and Second table.

Union All query will be like:

SELECT * FROM First


UNION ALL
SELECT * FROM Second;
• The resultset table will look like:

ID NAME

1 JACK

2 HARRY

3 JACKSON

3 JACKSON

4 STEPHAN

5 DAVID
Intersect

• It is used to combine two SELECT statements.


• The Intersect operation returns the common rows from both the SELECT
statements.
• In the Intersect operation, the number of datatype and columns must be the
same.
• It has no duplicates and it arranges the data in ascending order by default.
• Syntax
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2;
Example:
Using the above First and Second table.Intersect query will be:
SELECT * FROM First
INTERSECT
SELECT * FROM Second;

ID NAME

3 JACKSON
Minus

• It combines the result of two SELECT statements.


• Minus operator is used to display the rows which are present in the first
query but absent in the second query.
• It has no duplicates and data arranged in ascending order by default .
• Syntax:
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2;
• Example: Using the above First and Second table.Minus query will be:
SELECT * FROM First
MINUS
SELECT * FROM Second;

ID NAME

1 JACK

2 HARRY
SQL JOIN
► How do I get data from multiple tables?
► A SQL JOIN combines records from two tables.

► A JOIN locates related column values in the two tables.


► A query can contain zero, one, or multiple JOIN operations.

► INNER JOIN is the same as JOIN; the keyword INNER is optional.


SQL JOIN
► Four different types of JOINs
► (INNER) JOIN: Select records that
have matching values in both
tables.
► FULL (OUTER) JOIN: Selects all
records that match either left or
right table records.
► LEFT (OUTER) JOIN: Select
records from the first (left-most)
table with matching right table
records.
► RIGHT (OUTER) JOIN: Select
records from the second (right-
most) table with matching left table
records
select name,student from tsble1 inner join table2 on
col1=col2 where

The SQL JOIN syntax


► The general syntax is
SELECT column-names
FROM table-name1 INNER JOIN table-name2
ON column-name1 = column-name2
WHERE condition

► The INNER keyword is optional: it is the default as well as the most


commonly used JOIN operation.
The SQL JOIN Example
► Problem: List all orders with customer information
SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country
FROM Order JOIN Customer
ON Order.CustomerId = Customer.Id
SQL LEFT JOIN
► What is a LEFT JOIN in SQL?
► A LEFT JOIN performs a join starting with the first (left-most) table.

► Then, any matched records from the second table (right-most) will be
included.
► LEFT JOIN and LEFT OUTER JOIN are the same.
The SQL LEFT JOIN syntax
► The general LEFT OUTER JOIN syntax is

SELECT column-names
FROM table-name1 LEFT OUTER JOIN table-name2
ON column-name1 = column-name2
WHERE condition

► The OUTER keyword is optional


SQL LEFT JOIN Example
► Problem: List all customers and the total amount they spent irrespective
whether they placed any orders or not.
SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country
FROM Customer C LEFT JOIN Order O
ON O.CustomerId = C.Id
ORDER BY TotalAmount
SQL RIGHT JOIN
► What is a RIGHT JOIN in SQL?
► A RIGHT JOIN performs a join starting with the second (right-most)
table and then any matching first (left-most) table records.
► RIGHT JOIN and RIGHT OUTER JOIN are the same.
The SQL RIGHT JOIN syntax
► The general RIGHT OUTER JOIN syntax is:

SELECT column-names
FROM table-name1 RIGHT OUTER JOIN table-name2
ON column-name1 = column-name2
WHERE condition

► The OUTER keyword is optional


SQL RIGHT JOIN Examples
► Problem: List customers that have not placed orders

SELECT TotalAmount, FirstName, LastName, City, Country


FROM [Order] O RIGHT JOIN Customer C
ON O.CustomerId = C.Id
WHERE TotalAmount IS NULL
SQL FULL JOIN
► What does a SQL FULL JOIN return?
► FULL JOIN returns all matching records from both tables whether the
other table matches or not.
► Be aware that a FULL JOIN can potentially return very large datasets.

► These two: FULL JOIN and FULL OUTER JOIN are the same.
The SQL FULL JOIN syntax
► The general FULL OUTER JOIN syntax is:

SELECT column-names
FROM table-name1 FULL OUTER JOIN table-name2
ON column-name1 = column-name2
WHERE condition

► The OUTER keyword is optional


SQL FULL JOIN Examples
► Problem: Match all customers and suppliers by country

SELECT C.FirstName, C.LastName, C.Country AS CustomerCountry,


S.Country AS SupplierCountry, S.CompanyName
FROM Customer C FULL JOIN Supplier S
ON C.Country = S.Country
ORDER BY C.Country, S.Country
This returns suppliers that have no customers in their country,
and customers that have no suppliers in their country,
and customers and suppliers that are from the same country.
Aggregate Function
► Aggregate functions are a very powerful tool to analyze the data and gain
useful business insights.
► Aggregate functions are functions that take a collection of values as input
and return a single value
► Behavior of Aggregate Functions
► Operates - on a single column

► Return - a single value

► The most commonly used SQL aggregate functions include SUM, MAX,
MIN, COUNT and AVERAGE.
► Aggregators are very often used in conjunction with Grouping functions in
order to summarize the data.
SQL COUNT()
► The COUNT() function returns the number of rows that matches a specified
criteria.
► SQL COUNT(column_name)

► The COUNT(column_name) function returns the number of values


(NULL values will not be counted) of the specified column:
► SELECT COUNT(column_name) FROM table_name;
► SQL COUNT(*)

► The COUNT(*) function returns the number of records in a table:

► SELECT COUNT(*) FROM table_name;

► SQL COUNT(DISTINCT column_name)

► The COUNT(DISTINCT column_name) function returns the number


of distinct values of the specified column:
► SELECT COUNT(DISTINCT column_name) FROM table_name;
SQL COUNT() Example
OrderID CustomerID EmployeeID OrderDate ShipperID
10265 7 2 1996-07-25 1
10266 87 3 1996-07-26 3
10267 25 4 1996-07-29 1

counts the number of orders from "CustomerID"=7 from the "Orders" table:
SELECT COUNT(CustomerID) AS
OrdersFromCustomerID7 FROM Orders
WHERE CustomerID=7;

OrdersFromCustomerID7
1
SQL COUNT(*) Example
OrderID CustomerID EmployeeID OrderDate ShipperID
10265 7 2 1996-07-25 1
10266 87 3 1996-07-26 3
10267 25 4 1996-07-29 1

To get number of rows in the 'orders' table, the following SQL statement can be
used:
SELECT COUNT(*)
FROM orders;

COUNT(*)
3
SQL COUNT(DISTINCT column_name) Example
OrderID CustomerID EmployeeID OrderDate ShipperID
10265 7 2 1996-07-25 1
10266 87 3 1996-07-26 3
10267 25 4 1996-07-29 1

SELECT COUNT(DISTINCT ShipperID)


FROM orders;

COUNT(DISTINCT ShipperID)
2
SQL SUM, AVG
► SELECT SUM returns the sum of the data values.
► And SELECT AVG returns the average of the data values.
► The general SUM syntax is:
SELECT SUM(column-name)
FROM table-name;
► The general AVG syntax is:
SELECT AVG(column-name)
FROM table-name;
SQL SUM, AVG Examples
► Problem: Compute the total amount sold in 2013.
SELECT SUM(TotalAmount) Sum

FROM [Order] 658388.75

WHERE YEAR(OrderDate) = 2013

►Problem: Compute the average size of all orders. Average


1631.877819
SELECT AVG(TotalAmount)
FROM [Order]
SQL MAX and MIN
► SELECT MIN returns the minimum value for a column.
► And SELECT MAX returns the maximum value for a column.
► The general MIN syntax is:
SELECT MIN(column-name)
FROM table-name;
► The general MAX syntax is:
SELECT MAX(column-name)
FROM table-name;
SQL MAX and MIN Example
Problem: Find the cheapest product
SELECT MIN(UnitPrice)
UnitPrice
FROM Product
2.50

Problem: Find the largest order placed in 2014


SELECT MAX(TotalAmount)
TotalAmount
FROM [Order] 17250.00
WHERE YEAR(OrderDate) = 2014
OrderDate
2013-12-31 00:00:00.000
Problem: Find the last order date in 2013
SELECT MAX(OrderDate)
FROM [Order]
WHERE YEAR(OrderDate) = 2013
The SQL ORDER BY

• The ORDER BY Keyword is used to sort the record in ascending


order.
• It sort the records in ascending order by default
• To sort the records in descending order, use the DESC keyword
• Syntax
SELECT column1, column2,....
FROM table_name
ORDER BY column1, column2,...
ASC/DESC;
Name City Country
Alfred berlin germany
Anna Mcity mexico
Antonio mcity mexico
James london uk
Christina beiging china

Eg select all customers from the customers table, sorted by the country column
Query: select * from customer order by country; auto ascending

Name City Country


Christtina beiging china
Alfred berlin germany
Anna Mcity mexico
Antonio mcity mexico
James london uk
• Eg select all customers from the customers table, sorted by the country
column in descending
• Query: select * from customer order by country desc;

Name City Country


James london uk
Antonio mcity mexico
Anna Mcity mexico
Alfred berlin germany
Christtina beiging china
The SQL GROUP BY

• It is used to arrange identical data into groups


• It is often used with aggregate functions to group the result-set by one or
more columns.
• The SQL GROUP BY syntax
SELECT column-names
FROM table-name
WHERE condition
GROUP BY column-names;
• Eg 1 : list the number of customers in each country
• Query: select Count(name), country from customer group by (country);

COUNT (NAME) COUNTRY


1 UK
1 GERMANY
2 MEXICO
1 CHINA
SN0 FNAME LNAME SALAR POSITION
Y
100 JOHN VARGHESE 30000 MANAGER
101 SUSAN ABRAHAM 24000 MANAGER
102 DAVID GEORGE 12000 PROJECT MANAGER
103 ANN MARY 12000 PROJECT MANAGER
104 MARY MATHEW 9000 PROJECT MANAGER

Eg 2: List the minimum salary held by each positions


Query : select position, min(salary) from staff
group by (position);

POSITION MIN(SALARY)
MANAGER 24000
PROJECT 9000
MANAGER
HAVING Clause

• It is used to state a condition that applies to groups


• It can be used in conjunction with group by clause
• The general syntax is
SELECT column-names not where condition
FROM table-name
GROUP BY column-names
HAVING condition
SQL HAVING Clause
► What does the HAVING clause do in a query?
► The HAVING clause is like WHERE but operates on grouped records
returned by a GROUP BY.
► HAVING applies to summarized group records, whereas WHERE applies
to individual records.
► Only the groups that meet the HAVING criteria will be returned.
► HAVING requires that a GROUP BY clause is present.

► Both WHERE and HAVING can be used in the same query at the same
time.
• Eg: select the name of the employee held in various positions whose salary
is above 10,000
• Query: Select position, fname from staff group by(position) having
salary>10000

POSITION FNAME
MANAGER JOHN
PROJECT MANAGER DAVID
► Problem: List the number of customers in each country. Only include countries with
more than 10 customers.
SELECT COUNT(Id), Country
FROM Customer
GROUP BY Country
HAVING COUNT(Id) > 10
Problem: List the number of customers in each country, except the USA, sorted
high to low. Only include countries with 9 or more customers.
SELECT
COUNT(Id), Country
FROM Customer
WHERE Country <> 'USA'
GROUP BY Country where count(id) is not possible

HAVING COUNT(Id) >= 9


ORDER BY COUNT(Id) DESC
Question 1

Consider the following relations:


FACULTY(FNO, NAME, GENDER, AGE, SALARY, DNUM)
C.SELECT DNAME,COUNT(CNO) AS NUMOFCOURSE FROM
DEPARTMENT(DNO, DNAME, DPHONE) DEPARMENT JOIN COURSE ON D.DNO=C.CODNO
GROUP BY DNAME HAVING COUNT(CNO)>0

COURSE(CNO, CNAME, CREDITS, ODNO) ORDER BY NUMOFCOURSE


TEACHING(FNO, CNO, SEMESTER)
DNUM is a foreign key that identifies the department to which a faculty
belongs. ODNO is a foreign key identifying the department that offers a
course. select CNO,CNAME FROM COURSE JOIN DEPARTMENT ON
COURSE.DNO=DEPARTMENT.DNO WHERE DEPARTMENT.NAME='CS' AND C.CRED=3;
Write SQL expressions for the following queries:
• a) Course numbers and names of 3-credit courses offered by ‘CS’
department.SELECT NAME FROM FACULTY JOIN TEACHING ON F.FNO=T.TNO GROUP BY FNAME HAVING COUNT(T.CNO)
<=3;
• b) Names of faculty members teaching maximum3 courses.
• c) Names of departments along with number of courses offered by each of
them, in the increasing order of number of courses; exclude departments
which do not offer any course.
Question 2
• For the relation schema below, give an expression in SQL for each of the
queries that follows:
employee(employee-name, street, city)
works(employee-name, company-name, salary)
company(company-name, city)
manages(employee-name, manager-name)
• a) Find the names, street address, and cities of residence for all employees
who work for the Company ‘RIL Inc.' and earn more than $10,000.
• b) Find the names of all employees who live in the same cities as
thecompanies for which they work.
• c) Find the names of all employees who do not work for ‘KYS Inc.’.
Assume that all people work for exactly one company.
• d) Find the names of all employees who earn more than every employeeof
‘SB Corporation'. Assume that all people work for at most one company.
Question 3

• In the following tables ADVISOR and TAUGHTBY are foreign keys


referring to the table PROFESSOR. ROLLNO and COURSEID in
ENROLLMENT refer to tables with primary keys of the same name.
STUDENT(ROLLNO, NAME, AGE, GENDER, ADDRESS, ADVISOR)
COURSE(COURSEID, CNAME, TAUGHTBY, CREDITS)
PROFESSOR(PROFID,PNAME, PHONE)
ENROLLMENT(ROLLNO, COURSEID, GRADE)
• Write SQL expressions for the following queries:
• (i) Names of courses taught by ‘Prof. Raju’.
• (ii) Names of students who have not enrolled for any course taught by
‘Prof. Ganapathy’.
• (iii) For each course, name of the course and number of students enrolled
for the course.
STUDENT(ROLLNO, NAME, AGE, GENDER, ADDRESS, ADVISOR)
COURSE(COURSEID, CNAME, TAUGHTBY, CREDITS)
PROFESSOR(PROFID,PNAME, PHONE)
ENROLLMENT(ROLLNO, COURSEID, GRADE
SELECT S.NAME FROM STUDENT S JOIN ENROLLMENT E ON S.ROLLNO = E.ROLLNO JOIN COURSE ON E.COURSEID
= C.COURSEID JOIN PROFESSOR P ON C.TAUGHTBY = P.PROFID
WHERE P.PNAME -'PROF.GANAPATHY; AND E.COURSE IS NULL;

1.SELECT C.CNAME FROM COURSE C


INNER JOIN PROFESSOR P ON C.TAUGHTBY =P.PROFID
WHERE P.PNAME = 'Prof. Raju';
2. SELECT S.NAME Names of students who have not enrolled for any course taught by
‘Prof. Ganapathy
FROM STUDENT S
LEFT JOIN ENROLLMENT E ON S.ROLLNO = E.ROLLNO
LEFT JOIN COURSE C ON E.COURSEID = C.COURSEID
LEFT JOIN PROFESSOR P ON C.TAUGHTBY = P.PROFID
WHERE P.PNAME IS NULL;
3.SELECT C.CNAME, COUNT(E.ROLLNO) AS "Number of Students Enrolled"
FROM COURSE C
LEFT JOIN ENROLLMENT E ON C.COURSEID = E.COURSEID
GROUP BY C.COURSEID, C.CNAME;
Question 4
• Write the SQL statement for the following
ALBUMS(ALBUM-ID, ALBUM-NAME, PRODUCEDBY, YEAR)
SONGS(SONG-ID, SONG-START, DURATION, ALBUM-ID)
a. Update the year of the album with name ‘suhana’to 2018
b. Delete the album ‘YADON KI BAARISH’ along with all the songs in it
A SELECT employee.employee-name, employee.street, employee.city
FROM employee
JOIN works ON employee.employee-name = works.employee-name
WHERE works.company-name = 'RIL Inc.' AND works.salary > 10000;
B SELECT DISTINCT employee.employee-name
FROM employee
JOIN works ON employee.employee-name = works.employee-name
JOIN company ON works.company-name = company.company-name
WHERE employee.city = company.city;
C SELECT employee.employee-name
FROM employee
LEFT JOIN works ON employee.employee-name = works.employee-name
WHERE works.company-name IS NULLOR works.company-name != 'KYS Inc.';
D SELECT e1.employee-name
FROM employee e1
JOIN works w1 ON e1.employee-name = w1.employee-name
WHERE w1.salary > ALL (SELECT w2.salary
FROM works w2
WHERE w2.company-name = 'SB Corporation')
ALBUMS(ALBUM-ID, ALBUM-NAME, PRODUCEDBY, YEAR)
SONGS(SONG-ID, SONG-START, DURATION, ALBUM-ID)
a. Update the year of the album with name ‘suhana’to 2018
b. Delete the album‘YADON KI BAARISH’ along with all the songs in i

a.UPDATE ALBUMS
SET YEAR = 2018
WHERE ALBUM-NAME = 'suhana';
b. DELETE FROM ALBUMS
WHERE ALBUM-NAME = 'YADON KI BAARISH';

DELETE FROM SONGS


WHERE ALBUM-ID = (SELECT ALBUM-ID FROM ALBUMS WHERE
ALBUM-NAME = 'YADON KI BAARISH');

You might also like