Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 170

Unit-II

Structured Query Language


Introduction to SQL

• SQL stands for Structured Query Language


• It is the language for accessing a relational
database.
• SQL provides a set of statements for storing and
retrieving data to and from a relational database.
• The nonprocedural nature of SQL makes it easier
to access data in application programs.
• IBM developed the original version of SQL
• Originally called sequel as part of the System R
project in the early 1970s.
• Name has changed to SQL (Structured Query
Language).
• SQL-Standard SQL-86, SQL-89, SQL-92,
SQL-99, SQL-2003, SQL-2006, SQL-2008, SQL-
2011, SQL-2016, SQL-2019
• UNION
• Combines the results of two SELECT statements
into one result set, and then eliminates any
duplicate rows from that result set.
• Union is like an “OR” operation
• UNION ALL
• Combines the results of two SELECT statements
into one result set and it retain all duplicates
• Union - Restrictions
• The SELECT statements must contain the same
number of columns

• Data type
• Each column in the first table must be the same as
the data type of the corresponding column in the
second table.
• Data width and column name can differ

• Neither of the two tables can be sorted with the


ORDER BY clause.
• Combined query results can be sorted
• INTERSECT
• Returns only those rows that are returned by each of
two SELECT statements.
• It retrieves those tuples which are present in both
relation
• An intersection is an AND operation
• MINUS
• Takes the result set of one SELECT statement, and
removes those rows that are also returned by a
second SELECT statement
• It retrieves rows which are present in 1 but not in 2
• Find all customers having a loan, an account, or
both at the bank
SELECT customer-name FROM depositor
UNION
SELECT customer-name FROM borrower

• Find all customers who have both a loan and an


account at the bank
SELECT customer-name FROM depositor
INTERSECT
SELECT customer-name FROM borrower
• Find all customers who have an account but no
loan at the bank.
SELECT customer-name FROM depositor
MINUS
SELECT customer-name FROM borrower
Aggregate Functions

• Aggregate functions are functions that take a


collection (a set or multiset) of values as input and
return a single value
• Aggregate functions are used in place of column
names in the SELECT statement

• MIN
• MAX
• AVERAGE
• SUM
• COUNT
Aggregate function - MIN

• Returns the smallest value that occurs in the specified


column.
• Column need not be numeric type.
• MIN ignores any null values.

SELECT MIN( column name/ expression) FROM


Table_name;

•Selecting Minimum account balance;

SELECT Min(balance) as MinimumBalance FROM account;


Aggregate function - MAX

• Returns the largest value that occurs in the specified column.


• Column need not be numeric type.
• MIN ignores any null values.

• SELECT MAX( column name/ expression) FROM


Table_name;

•Selecting Maximum loan amount

SELECT MAX(amount) as MaximumAmount FROM loan;


Aggregate function - average
• Returns the average of all the values in the specified
column. SQL AVG() ignores Null Values.
• Column must be numeric data type

• Syntax of SQL AVG()


• AVG ( [ DISTINCT ] column-name/ expression )

• Example 1 of SQL AVG()


List the average account balance of customers
SELECT AVG(balance) as "Average Bal"
FROM account;
• Example 2 of SQL AVG() ID Numb
1 1
Below is the test_table 2 1
Select AVG(Numb) from test_table 3 1
4 2
Result: 5 2
2 6 2
7 3
Select AVG(distinct Numb) from 8 3
test_table 9 4
10 1
Result:
1
Aggregate function - sum
• SQL SUM() function returns the sum of numeric
column.
• SQL SUM() ignores Null Values
• Syntax of SQL SUM()
• SUM ( [ DISTINCT ] column-name / expression )
• Example 1 of SQL SUM()
Find the sum of loan amount of bank
SELECT SUM(amount) as Totalamount
FROM loan;
• Example 2 of SQL SUM() ID Numb
1 1
Below is the test_table 2 1
Select SUM(all Numb) from test_table 3 1
4 2
Result: 5 2
20 6 2
7 3
Select SUM(distinct Numb) from 8 3
test_table 9 4
10 1
Result:
10
Aggregate function- count
• count returns the number of tuples returned by the
query as a number.
• COUNT( [DISTINCT] column-name/ expression )

List the total number of customers


SELECT COUNT(*)
FROM customer;

• Count(*) = No of rows
• Count(ColumnName) = No. of rows that do not
have NULL Value
Aggregate function- count

List the total number of account holder at SBI


Branch
SELECT COUNT(*)
FROM account
WHERE branch-name=‘SBI’;

List the total number of unique customer city


SELECT COUNT(DISTINCT customer-city)
FROM customer;
SQL- Using GROUP BY
• The aggregate function not only to a single set of
tuples, but also to a group of sets of tuples;
• Specifies how to report the output of the query.
• Allows one to define a subset of the values of a particular
field and to apply an aggregate function to the subsets.
• Related rows can be grouped together by GROUP BY
clause by specifying a column as a grouping column.
• GROUP BY is associated with an aggregate function
SQL Group By
• The attribute or attributes given in the group by
clause are used to form groups
• Tuples with the same value on all attributes in the
group by clause are placed in one group.
• Example 1 of SQL Group BY
Calculate the Find the average account
balance at each branch
accountno branchname balance
A101 SBI $1500
A102 BOI $2500
A103 HDFC $3000
A104 SBI $7000
A105 BOI $5000
• First, we need to make sure we select the branch
name as well as average balance.
SELECT branchname, AVG (balance)
FROM account
Second, we need to make sure that all the balnce
figures are grouped by branchnames.
SELECT branchname, AVG (balance)
FROM account
GROUP BY branchname; branchname AVG(balance)
The Result is:
SBI $4250
BOI $3750
HDFC $3000
• Example 2 of SQL Group BY
SELECT COUNT (*) FROM customer
• The above statement returns the total number
of rows in the table.
• We can use GROUP BY to count the number
of customer in each city.
• With GROUP BY, the table is split into groups by city,
and COUNT (*) is applied to each group in turn.
SELECT customercity, COUNT(*)
FROM customer
GROUP BY customercity
• we have a table name Orders.
Orders (O_Id, OrderDate, OrderPrice, Customer)

• we want to find the total sum (total order) of each


customer.
SELECT Customer,SUM(OrderPrice)
FROM Orders
GROUP BY Customer
• Returns a list of Department IDs along with the sum of
their sales for the date of January 1, 2000.

SELECT DeptID, SUM(SaleAmount)


FROM Sales
WHERE SaleDate = '01-Jan-2000'
GROUP BY DeptID

• Calculate the total sales for each store


SELECT store_name, SUM (Sales)
FROM Store_Information
GROUP BY store_name
• Find those branches where the average loan amount is
more than Rs. 120000.
SELECT branch_name, avg(amount)
FROM loan
GROUP BY branch_name
HAVING avg(amount) > 120000
• Find the average salary for each department that has
either more than 1 employee or starts with a “To”:
SELECT Dept, AVG(Salary) as avgsal
FROM Employee
GROUP BY Dept
HAVING COUNT( name ) > 1 OR Dept LIKE ‘To’;
• Find average account balance at each branch with
average account balance more than 5000.

SELECT branch_name, avg(balance)


FROM account
GROUP BY branch_name
HAVING avg(balance) > 5000;
SQL Outer Join
• Inner join retrieve the records having same value for
similar attributes in both tables.
• Outer join retrieve records from one of the table and
display records from another table if matches the
value of similar attribute.
• Display NULL if similar attribute has no
matching value.
– Left Join / Left Outer Join
– Right Join / Right Outer Join
– Full Join / Full Outer Join
Left Join / Left Outer Join
• Retrieve all the rows from left table specified in
Join statement.
• And matching row from right table if common
attribute value matches.
• When a row in the left table has no matching rows in
the right table the associated result set rowcontains null
values for all selected list columns coming from the
right table.
• SELECT <list_of_attributes> FROM <Table1>
LEFT JOIN <Table2>
ON table1.attribute=table2.attribute

• SELECT * FROM FACULTY LEFT


JOIN STUDENT
ON PERSON.PID=STUDENT.PID
• SELECT <list_of_attributes> FROM
<Table1> LEFT OUTER JOIN <Table2>
ON table1.attribute=table2.attribute

• SELECT * FROM FACULTY LEFT


OUTER JOIN STUDENT
ON PERSON.PID=STUDENT.PID
• SELECT <list_of_attributes> FROM
<Table1> LEFT JOIN <Table2>
USING (<attribute>)

• SELECT * FROM FACULTY LEFT


JOIN STUDENT USING (PID)
• SELECT <list_of_attributes> FROM
<Table1> LEFT OUTER JOIN <Table2>
USING (<attribute>)

• SELECT * FROM FACULTY LEFT


OUTER JOIN STUDENT USING (PID)
Right Join / Right Outer Join
• Retrieve all the rows from right table
specified in Join statement.
• And matching row from left table
if common attribute value
matches.
• When a row in the right table has no matching
rows in the left table the associated result set
row contains null values for all selected list
columns coming from the left table.
• SELECT <list_of_attributes> FROM <Table1>
RIGHT JOIN <Table2>
ON table1.attribute=table2.attribute

• SELECT * FROM FACULTY RIGHT


JOIN STUDENT
ON PERSON.PID=STUDENT.PID
• SELECT <list_of_attributes> FROM
<Table1> RIGHT OUTER JOIN <Table2>
ON table1.attribute=table2.attribute

• SELECT * FROM FACULTY RIGHT


OUTER JOIN STUDENT
ON PERSON.PID=STUDENT.PID
• SELECT <list_of_attributes>
FROM
<Table1> RIGHT JOIN <Table2>
USING (<attribute>)

• SELECT * FROM FACULTY RIGHT


JOIN STUDENT USING (PID)
• SELECT <list_of_attributes> FROM
<Table1> RIGHT OUTER JOIN <Table2>
USING (<attribute>)

• SELECT * FROM FACULTY RIGHT


OUTER JOIN STUDENT USING (PID)
Full Join / Full Outer Join
• Retrieve all the rows from left table and
right table specified in Join statement.
• When a row in the left table has no matching
rows in the right table the associated result
set row containsnull values for all selected list
columns coming from the right table.
• When a row in the right table has no matching
rows in the left table the associated result set
row contains null values for all selected list
columns coming from the left table.
• SELECT <list_of_attributes> FROM <Table1>
FULL JOIN <Table2>
ON table1.attribute=table2.attribute

• SELECT * FROM FACULTY FULL


JOIN STUDENT
ON PERSON.PID=STUDENT.PID
• SELECT <list_of_attributes> FROM
<Table1> FULL OUTER JOIN <Table2>
ON table1.attribute=table2.attribute

• SELECT * FROM FACULTY FULL


OUTER JOIN STUDENT
ON PERSON.PID=STUDENT.PID
• SELECT <list_of_attributes> FROM
<Table1> FULL JOIN <Table2>
USING (<attribute>)

• SELECT * FROM FACULTY FULL


JOIN STUDENT USING (PID)
• SELECT <list_of_attributes> FROM
<Table1> FULL OUTER JOIN <Table2>
USING (<attribute>)

• SELECT * FROM FACULTY FULL


OUTER JOIN STUDENT USING (PID)
Natural Join
• Similar to Inner Join
• Retrieve the records having same value for
similar attributes in two tables.
Difference between Inner Join and Natural Join
• In Inner join takes conditions explicitly.
• Natural join takes condition implicitly.
• Colum names in both tables must be same
for natural join.
• In inner join column names can be different
as conditions are given explicitly.
• Repeated columns are avoided to display in
natural join.
• SELECT <list_of_attributes> FROM <Table1>
INNER JOIN <Table2>
ON table1.attribute=table2.attribute

• SELECT * FROM FACULTY INNER JOIN


STUDENT ON PERSON.PID=STUDENT.PID
• SELECT * FROM FACULTY INNER
JOIN STUDENT USING (PID)
• SELECT <list_of_attributes> FROM <Table1>
NATURAL JOIN <Table2>

• SELECT * FROM FACULTY NATURAL


JOIN STUDENT
NESTED SUBQUERIES/ Subqueries
• A subquery is a select-from-where expression that
is nested within another query.
• use of subqueries is to perform tests for set
membership, make set comparisons, and determine
set cardinality.
• Mostly used in WHERE Clause
• (Can also use these in the HAVING clause)
NESTED SUBQUERIES/ Subqueries
• Widely used:
¤ Direct comparison with scalar-subquery results
¤ Set-membership tests: IN, NOT IN
¤ Empty-set tests: EXISTS, NOT EXISTS

• Less frequently used:


¤ Set-comparison tests: ANY, SOME, ALL
¤ Uniqueness tests: UNIQUE, NOT UNIQUE
Scalar-subquery
• use scalar subqueries in WHERE
clause comparisons
• Direct comparison with scalar-
subquery results

• select *
from table_name
where test-expression comparison
operator (subquery)
Sample Queries
• Find the name of the branch with the
smallest number of assets.

SELECT
branch_name FROM
branch WHERE
assets =
(SELECT
MIN(assets)
Sample Queries
• Find the names of all branches that have assets
greater than atleast one branch located in
Brooklyn.

select
branch_name from
branch
where assets >
(select min(assets)
from branch
where
branch_city =
Set Membership Tests
• Can use IN (...) and NOT IN (...) for set
membership tests
• IN (...) and NOT IN (...) support subqueries that
return multiple columns (!!!)
• The in connective, where the set is a collection of
values produced by a select clause.
• The not in connective tests for the absence of
set membership.
• Select *
from table_name
where test-expression [NOT] IN (Constan1,
constant2,
….)
Sample Queries
• Find all customers who have both an account and
a loan at the bank.

SELECT DISTINCT
customer_name FROM borrower
WHERE customer_name IN
(SELECT
customer_name FROM
depositor) ;
Sample Queries
• Find all customers who do have a loan at the
bank, but do not have an account at the bank.

SELECT DISTINCT
customer_name FROM borrower
WHERE customer_name NOT IN
(SELECT
customer_name FROM
depositor) ;
Sample Queries
• Find the details of the largest loan at each
branch, including the branch name and the
amount of the loan

SELECT *
FROM loan
WHERE (branch_name, amount) IN (
SELECT branch_name,
MAX(amount) FROM loan
GROUP BY branch_name);
Empty-Set Tests
• Can test whether or not a subquery generates any results
at all
• Can use EXISTS (...) and NOT EXISTS (...)
• is a test for a non-empty set and returns either TRUE
or FALSE.
• EXISTS is TRUE if the Table subquery returns at least one
row; otherwise it is FALSE.
• NOT EXISTS is TRUE if the Table subquery returns zero
rows; otherwise it is FALSE.
• SELECT column_1
FROM
Table_1
Sample Queries
• Find all customers who have both an account and
a loan at the bank

SELECT DISTINCT
customer_name FROM depositor d
WHERE EXISTS
(SELECT *
FROM borrower b
WHERE b.customer_name =
d.customer_name);
Sample Queries
• Find customers with an account but not a
loan.

SELECT DISTINCT
customer_name FROM depositor d
WHERE NOT EXISTS
(SELECT *
FROM borrower b
WHERE b.customer_name =
d.customer_name);
Set Comparison Tests
• Can compare a value to a set of values
¤ Is a value larger/smaller/etc. than some value in the set?
• SELECT *
FROM table_name
WHERE attribute comparison_op SOME (subquery);
¤ Can use any comparison operation
= SOME is same as IN
¤ ANY is a synonym for SOME
• Can also compare a value with
all values in a set
¤ Use ALL instead of SOME
ALL quantified comparison
• SELECT *
FROM table_name
WHERE scalar_expression comparison_operator ALL
(subquery);
• scalar_expression : that evaluates to a single value
• comparison_operator may be any one of:
= or > or < or >= or <= or <>.
• ALL returns TRUE if the Table subquery returns zero
rows or if the comparison operator returns TRUE for
every row returned by the Table subquery.
• ALL returns FALSE if the comparison operator returns
FALSE for at least one row returned by the Table
subquery
ALL quantified comparison
• ... WHERE 1000.00 >
ALL (SELECT column_1 FROM Table_1) ...
• If TABLE_1 contains the values {100.00, 200.00, 300.00}, the
expression is TRUE: all of TABLE_1’s values are less than 1000.00.
• If TABLE_1 contains the values {100.00, 2000.00, 300.00},
the expression is FALSE: one of TABLE_1’s values is greater
than 1000.00.
• If TABLE_1 contains the values {1000.00, 200.00, 300.00},
the expression is FALSE too: one of TABLE_1’s values is
equal to 1000.00.
• If TABLE_1 contains no values, the expression is TRUE: when
the set is empty, ALL is TRUE.
• If TABLE_1 contains the values {100.00, NULL, 300.00}, the
expression is UNKNOWN: when NULLs are involved, ALL
ANY or SOME quantified comparison
• SELECT *
FROM table_name
WHERE scalar_expression comparison_operator ANY/ SOME
(subquery);
• scalar_expression : that evaluates to a single value
• comparison_operator may be any one of:
= or > or < or >= or <= or <>.
• SOME and ANY are synonyms.
• They return TRUE if the comparison operator returns
TRUE for at least one row returned by the Table subquery.
• They return FALSE if the Table subquery returns zero rows or
if the comparison operator returns FALSE for every row
returned by the Table subquery.
ANY or SOME quantified comparison
• ... WHERE 1000.00 >
ANY (SELECT column_1 FROM Table_1) ...
• If TABLE_1 contains the values {100.00, 200.00, 300.00}, the
expression is TRUE: all of TABLE_1’s values are less than 1000.00.
• If TABLE_1 contains the values {100.00, 2000.00, 300.00}, the
expression is TRUE too: at least some of TABLE_1’s values are
less than 1000.00.
• If TABLE_1 contains no values, the expression is FALSE: when the
set is empty, ANY is FALSE.
• If TABLE_1 contains the values {1000.00, 2000.00, 3000.00}, the
expression is FALSE too: all of TABLE_1’s values are greater
than or equal to 1000.00.
• If TABLE_1 contains the values {100.00, NULL, 300.00}, the
expression is are UNKNOWN: when NULLs involved, ANY
Sample Queries
• Find the names of all branches that have assets
greater than those of at least one branch located
in Brooklyn.

select
branch_name from
branch
where assets >
some(select assets
f
r
o
Sample Queries
• Find the names of all branches that have an asset
value greater than that of each branch in
Brooklyn.

select
branch_name from
branch
where assets >
all(select assets
f
r
o
Views
• A view is a kind of “virtual table”
• Views are tables whose contents are taken or derived from
other tables.
• To the user, the view appears like a table with columns and
rows
• But in reality, the view doesn’t exists in the database as a
stored set of values
• The rows and columns that we find inside a view are
actually the results generated by a query that defines
the view
Views
• Syntax to Create a view:
create view view_name( column1, column2, ……. ) as Query

• e.g. CREATE VIEW ViewCustomerDetails AS SELECT *


FROM Customer;
• Only names can be different. The data type etc
remain the same as the source table because, the values
are after all going to be derived from that table
• If no names are specified for columns, the same name as
used in the source table is used
• Syntax to drop a view:
• drop view view_name
Sample Queries
• Create view to be called all-customer contain
all the customers of bank.
Sample Queries
• Find the largest total account balance of
any branch.

create view branchwithbal as


SELECT branch_name, SUM(balance) AS
tot_bal FROM account
GROUP BY branch_name;

SELECT MAX(tot_bal) AS
large_bal FROM branchwithbal;

You might also like