Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

SQL Queries5

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

SQL Queries5

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

CMSC325

Advanced SQL
DR. RICHA SHARMA
L O C K H AV E N U N I V E R S I T Y

1
Review of Select Query
 Most frequently used DML query – meant to retrieve
data from one or more tables (join) based on conditions
we request.

 The SELECT command allows us to add restrictions to


search criteria to show a subset of the rows or columns.
Syntax:

SELECT columnlist
FROM tablelist
[ WHERE conditionlist ] ;

2
Review of Select Query
 We can use with select query:
 Wildcard character * to fetch all columns
 Logical operators within Where clause

 Column alias, an example:


Select P_PRICE as “Unit Price” from
PRODUCT;
 Computed columns such as product

 Distinct clause to fetch unique values for non-primary


attributes
 Order by clause to sort data on an attribute (ascending
order is by default).

 Special operators and Aggregate operators


3
Review of Select Query
 Special Operators:

 BETWEEN - to check whether an attribute value is within a range. If this


does not work, we can use comparison operators!

 LIKE - to check whether an attribute value matches a given string pattern.


% is wildcard character indicating any number of characters.

 IS NULL - to check whether an attribute value is null.

 IN - to check whether an attribute value matches any value within a value


list (WHERE V_STATE in (‘TN’, ‘FL’))

 EXISTS – to check if a subquery returns any rows as result.


 NOT IN , NOT BETWEEN – work opposite of IN & BETWEEN.

4
Review of Select Query
 Aggregate Operators:
 COUNT – returns the number of non-null values of an
attribute.
 MAX & MIN
 SUM – computes total for a specified attribute.
 AVG - computes average for a specified attribute.
 select * from EMP where EMP_MGR > (select
avg(EMP_MGR) from EMp);
 An example: SELECT COUNT(*), AVG(P_PRICE) FROM
PRODUCT;

5
Review of Select Query
 Aggregate Operators and grouping: when we want to
compute results of aggregate operator on sub-groups
within the data, i.e. work with frequency distribution!

 Syntax:
SELECT columnlist
FROM tablelist
[WHERE conditionlist]
[GROUP BY columnlist]
[HAVING conditionlist]
[ORDER BY columnlist [ASC | DESC] ] ;

6
SQL JOIN
Operators

7
Types of Join
 Inner join returns only rows from the tables that match on a common
value.
 Outer join returns the same matched rows as the inner join, plus
unmatched rows from one table or the other (can be left, right or full
outer join).

 Left returns nonmatching rows from table on left side


 Right returns nonmatching null rows from table on right side
 Natural join returns all rows with matching values in the matching
columns and eliminates duplicate columns. Natural join is used when the
tables share one or more common attributes with common names.
 select * from product P, vendor V where P.v_code = V.v_code
 select * from product P join vendor V on P.v_code = V.v_code

 Cross join is the cartesian product!

8
Tables Join (ctd.)
 We use alias to identify the source table from which data
is selected – useful with recursive joins!

 Syntax - several variations:


 Explicitly matching the columns with a WHERE clause

 NATURAL JOIN command

 INNER JOIN command (or just JOIN) USING command


 INNER JOIN command (or just JOIN) ON command

 OUTER JOIN, FULL OUTER JOIN, LEFT OUTER JOIN

9
Self or Recursive Join
 When a table is joined to itself!
 Special Type of Inner Join.

 Example with Employee table:

SELECT E.EMP_NUM, E.EMP_LNAME,


E.EMP_MGR, M.EMP_LNAME

FROM EMP E JOIN EMP M

ON E.EMP_MGR = M.EMP_NUM

10
SQL Subqueries

11
Subqueries
 Often, it is necessary to process data based on other
processed data!
 Subquery is a query inside a query, normally inside
parentheses. Thus, we have:
 Outer query
 Inner query or nested query

 Inner query is executed first. Its output becomes input of


outer query.
 Subqueries can be used in any of these clauses: WHERE,
IN, HAVING, ALL, ANY, EXISTS or as a table substitute in
FROM clause.

12
WHERE Subqueries
 Most common type uses inner SELECT subquery on right
side of WHERE comparison requires a subquery that
returns only one single value (comparison could be =, >, <,
>=, <=)

 The inner query should return one value! Value generated


by subquery must be of comparable data type.

 Example:
SELECT p_code, p_price FROM Product WHERE p_price >=
(SELECT AVG(p_price) FROM Product)

13
IN Subqueries
 When we want to compare a single attribute to a list of
values, we use IN operator (NOT IN works as well!)

 Example:
 select cus_code from customer where cus_code in (select
cus_code from invoice)

 select cus_code from customer where cus_code not in


(select cus_code from invoice where cus_code is not null)

14
HAVING Subqueries
 Just like WHERE clause, we can use subquery with
HAVING clause.

 Example:
select P_CODE, SUM(LINE_UNITS) as total FROM LINE

GROUP BY P_CODE HAVING

SUM(LINE_UNITS) > (select AVG(LINE_UNITS)


FROM LINE)

15
FROM Subqueries
 Specifies the tables from which the data will be drawn

 We can use SELECT subquery in the FROM clause to


create a "table"

 Example:

SELECT sum(p_price) FROM (SELECT p_price FROM


Product, Vendor WHERE v_state = 'KY') NP

Note: there can be more than one attribute in nested select query. *
is also allowed if we don’t have columns by same name on the
joined tables!

16
EXISTS Subqueries
 EXISTS special operator can be used whenever there is a
requirement to execute a command based on the result of
another query!
 If a subquery returns any rows, run the main query;
otherwise, do not!

 Example – following query lists all vendors, but only if there


are products with the quantity on hand less than double the
minimum quantity:
SELECT * FROM VENDOR WHERE EXISTS (SELECT *
FROM PRODUCT WHERE P_QOH <= 2* P_MIN)
Same as - select distinct v.V_CODE, v_name from vendor v
left outer join product p on v.V_CODE = p.V_CODE and
P_QOH <= 2* P_MIN;
17
Correlated Subquery
 A correlated subquery is a subquery that executes once for
each row in the outer query!

 Execution of correlated subquery is similar to the typical


nested loop in a programming language as:

FOR X = 1 TO 2
{
FOR Y = 1 TO 3
{
PRINT "X = "X, "Y = "Y
}
}

18
Correlated Subquery
 Exists query is an example of correlated subquery!

 Another example: this query lists all product sales in which the
units sold value is greater than the average units sold value
for that product (as opposed to the average for all products).

SELECT INV_NUMBER, P_CODE, LINE_UNITS

FROM LINE LS WHERE LS.LINE_UNITS >

(SELECT AVG(LINE_UNITS) FROM LINE LA WHERE


LA.P_CODE = LS.P_CODE)

19
ALL & ANY Subqueries
 Useful for inequality comparison of one value to a list of
values!
 For instance, we can use the ALL to know which
products cost more than all individual products provided by
vendors from Florida:

SELECT P_CODE, P_QOH* P_PRICE TOTALVALUE FROM

PRODUCT WHERE P_QOH*P_PRICE > ALL

(SELECT P_QOH*P_PRICE FROM PRODUCT where v_code


in (select v_code from VENDOR WHERE V_STATE = 'FL’))

20

You might also like