module 09 advance query techniques

Upload: sathish-kumar-r

Post on 29-May-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 Module 09 Advance Query Techniques

    1/28

    Module 9:Advanced QueryTechniques

    Vidya Vrat Agarwal. | MCT, MCSD

  • 8/9/2019 Module 09 Advance Query Techniques

    2/28

    Overview

    Introduction to Subqueries

    Subqueries Vs. Joins

    Parallel Subqueries

    Correlated SubqueriesUsing the EXISTS and NOT EXISTS Keywords

  • 8/9/2019 Module 09 Advance Query Techniques

    3/28

    Introduction to Subqueries

    Subqueries are Nested Select Statements.Subqueries are Select.From.Where expression nested inside another

    such expression.

    USE pubs

    SELECT pub_name

    FROMpublishersWHERE pub_idIN

    (SELECT pub_id

    FROMtitles

    WHERE type = 'business')

    Inner Query

    Inner Select

    Outer Query

    Outer Select

    The Inner query evaluate first and then based on its reslut the outerquery will be executed. i.e., Bottom-to-Top

  • 8/9/2019 Module 09 Advance Query Techniques

    4/28

    Introduction to Subqueries

    Why to Use Subqueries

    To break down a complex query into a series of logical steps

    To answer a query that relies on the results of another query

    The ability to usea Query within a Queryor Nested Queryis the original reason for the wordStructuredin the name

    SQL ( Structured Query Language)

  • 8/9/2019 Module 09 Advance Query Techniques

    5/28

    Subqueries Vs. Joins

    select distinctpub_name,title

    from publishers pJOINtitles t

    on p.pub_id =t.pub_id

    where t.type = 'business

    One difference in using a join rather than a subquery is that the join lets you show columns from more than one table in theresult.

    Why to Use Joins Rather Than Subqueries

    SQL Server executes joins faster than subqueries

  • 8/9/2019 Module 09 Advance Query Techniques

    6/28

    Using Subqueries

    Enclose Subqueries in Parentheses

    Use Only One Expression or Column Name in theselect list, cant use select * in Subquery.

    Use Subqueries in Place of an ExpressionRelational Database Engine processes the nested SQLstatement first and then result will be returned to theouter query.

    Cannot Use Subqueries on Columns Containing Textand Image Data Types

    No Limit to the Levels of Subqueries

  • 8/9/2019 Module 09 Advance Query Techniques

    7/28

    USE northwindSELECT orderid, customeridFROM orders

    WHERE orderdate = (SELECT max( orderdate )FROM orders)

    USE northwindSELECT orderid, customeridFROM orders

    WHERE orderdate = (SELECT max( orderdate )FROM orders)

    Subqueries Returning a Single Value

    Subquery Replaces Expression in:

    select list

    WHERE clause introduced with = comparison operator

  • 8/9/2019 Module 09 Advance Query Techniques

    8/28

    USE northwindSELECT companynameFROM customersWHERE customerid IN

    (SELECT customeridFROM ordersWHERE orderdate >'1/1/95')

    USE northwindSELECT companyname

    FROM customersWHERE customerid IN

    (SELECT customeridFROM ordersWHERE orderdate >'1/1/95')

    Subqueries Returning a List of Values

    Subquery Replaces Expression in:WHERE clause introduced with the IN keyword

    Server: Msg 512, Level 16, State 1, Line 2Subquery returned more than 1 value . This is not permitted when thesubquery follows =, !=, = or when the subquery is used as anexpression.

  • 8/9/2019 Module 09 Advance Query Techniques

    9/28

    Other Comparison Operator

    USE northwindSELECT orderid, customerid

    FROM orders

    WHERE orderdate> (SELECT orderdate FROM orders)

    Server: Msg 512, Level 16, State 1, Line 2

    Subquery returned more than 1 value. This is not permitted

    when the subquery follows =, !=, = or when thesubquery is used as an expression.

  • 8/9/2019 Module 09 Advance Query Techniques

    10/28

    Other Comparison Operator

    USE northwindSELECT orderid, customerid

    FROM orders

    WHERE orderdate > Any or Some (SELECT orderdateFROM orders)

    ANYor SOMEmust be greater thanat least one of the

    values in the list of values returned by the subquery

  • 8/9/2019 Module 09 Advance Query Techniques

    11/28

    Subqueries in UPDATE

    Subqueries can be nested in UPDATE statements.The following query doubles the price of all books published by New Moon

    Books. The query updates the titles table; its subquery references thepublishers table.

    UPDATE titles SET price = price * 2WHERE pub_id IN

    (SELECT pub_id

    FROM publishers

    WHERE pub_name = 'New Moon Books')

  • 8/9/2019 Module 09 Advance Query Techniques

    12/28

    Subqueries in DELETE

    DELETE sales

    WHERE title_id IN

    (SELECT title_id

    FROM titles

    WHERE type = 'business')

    Subqueries can be nested in DELETE statements .

  • 8/9/2019 Module 09 Advance Query Techniques

    13/28

    Paraller Subqueries

    A Query having a Compound Where clause.

    Select * from Distributer

    Where discount >= ( Select Avg(discount)from distributor)

    And Ltime > (select Avg(Ltime)from Distributor)

    AndCredit < (select Avg ( Credit)from distributor where city-London )

  • 8/9/2019 Module 09 Advance Query Techniques

    14/28

    Correlated Subquery

    Back to Step 1Back to Step 1

    SELECT orderid, customeridFROM orders or1WHERE 20 < (SELECT quantity

    FROM [order details] odWHERE or1.orderid = od.orderid

    AND od.productid = 23)

    SELECT orderid, customeridFROM orders or1WHERE 20 < (SELECT quantity

    FROM [order details] odWHERE or1.orderid = od.orderid

    AND od.productid = 23)

    Outer query passescolumn values to the inner query

    Outer query passescolumn values to the inner query

    111

    Inner query usesthat value to satisfy the inner query

    Inner query usesthat value to satisfy the inner query

    222

    Inner query returnsa value back to the outer query

    Inner query returnsa value back to the outer query

    333

    The process is repeated for the nextcolumn value of the outer query

    The process is repeated for the nextcolumn value of the outer query

    444

  • 8/9/2019 Module 09 Advance Query Techniques

    15/28

    Using the EXISTS and NOT EXISTS Keywords

    Use with Correlated Subqueries

    Determine Whether Data Exists in a List of Values

    SQL Server Process

    Outer query tests for the existence of rows

    Inner query returns TRUE or FALSE

    Data is not produced

    USE northwindSELECT lastname, employeeidFROM employees eWHERE EXISTS (SELECT * FROM orders

    WHERE e.employeeid = orders.employeeidAND orderdate = '9/5/97')

    USE northwindSELECT lastname, employeeidFROM employees eWHERE EXISTS (SELECT * FROM orders

    WHERE e.employeeid = orders.employeeidAND orderdate = '9/5/97')

  • 8/9/2019 Module 09 Advance Query Techniques

    16/28

    Check Your Understanding.

  • 8/9/2019 Module 09 Advance Query Techniques

    17/28

    Q.1 What is SubQuery ?

  • 8/9/2019 Module 09 Advance Query Techniques

    18/28

    Q.2. Why to use Subqueries ?

  • 8/9/2019 Module 09 Advance Query Techniques

    19/28

    Q.3. A Subquery can be a Union ?

    1. True

    2. False

  • 8/9/2019 Module 09 Advance Query Techniques

    20/28

    Q.4. Will this query produce result .?SELECT *

    FROM publishers

    WHERE pub_id IN

    (SELECT pub_idFROM titles

    WHERE type = 'business')

    1. Yes2. No

  • 8/9/2019 Module 09 Advance Query Techniques

    21/28

    Q.5. Is there any limit to nest the queries. ?

    1. Yes

    2. No

  • 8/9/2019 Module 09 Advance Query Techniques

    22/28

    Q.6. What is the Mistake in the following SQL Subquery.?

    USE northwind

    SELECT orderid, customeridFROM orders

    WHERE orderdate > (SELECT orderdate FROM orders)

  • 8/9/2019 Module 09 Advance Query Techniques

    23/28

    Q.7. Does SQL Server executes Joins faster thanSubqueries.?

    1. True

    2. False

  • 8/9/2019 Module 09 Advance Query Techniques

    24/28

    Q.8.Subqueries can not be nested in updatestatements..?

    1. True

    2. False

  • 8/9/2019 Module 09 Advance Query Techniques

    25/28

    Q.9. What will be the sequence of Execution of this query.USE pubsSELECT au_lname, au_fname

    FROM authors

    WHERE au_idIN( SELECT au_idFROM titleauthor WHERE title_idIN

    ( SELECT title_idFROM titles

    WHERE type = 'popular_comp'))

  • 8/9/2019 Module 09 Advance Query Techniques

    26/28

    Q.10. What is the difference between SubQuery andCorrelated Query.?

  • 8/9/2019 Module 09 Advance Query Techniques

    27/28

    Overview

    Introduction to Subqueries

    Subqueries Vs. Joins

    Parallel Subqueries

    Correlated SubqueriesUsing the EXISTS and NOT EXISTS Keywords

  • 8/9/2019 Module 09 Advance Query Techniques

    28/28

    A burning desire is

    The starting point of

    All accomplishment.

    Thank You.