0% found this document useful (0 votes)
16 views10 pages

Dbslab 13

Uploaded by

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

Dbslab 13

Uploaded by

evren.saviour
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Database Systems

Experiment 13
Implementing of Nested queries, Sub -queries,
related queries.
Co

CLO-3: Use modern tools and languages.


CLO-4: Build the projects of varying complexities.
CLO-5: Demonstrate the implementation of problem solving process.
CLO-6: Work individually as well as in teams.
CLO-7: Propose a unique solution that exhibits originality of idea
1-Sub queries:
SQL provides the subquery technique which involves placing an inner query (SELECT,
FROM,WHERE) within a WHERE or HAVING clause of another (outer) query. The inner query
provides values for the search condition of the outer query. Such queries are referred to as
subqueries or nested subqueries. Subqueries can be nested multiple times.

Sometimes, either the joining or the subquery technique can be used to accomplish the same
result, and different people will have different preferences about which technique to use. Other
times, only a join or a subquery will work.

The joining technique is useful when data from several relations are to be retrieved and displayed
and the relationships are not necessarily nested.

Let’s compare the two techniques that return the same result.

First, we will use a join query.

Example 1: What is the name and address of the customer who placed order
number 1003?
CUSTOMER_T

ORDER_T

SELECT CUSTOMER_NAME, CUSTOMER_ADDRESS, CITY, STATE, POSTAL_CODE


FROM CUSTOMER_T, ORDER_T
WHERE CUSTOMER_T. CUSTOMER_ID=ORDER_T. CUSTOMER_ID AND
ORDER_ID=1003;
OUTPUT:
CUSTOMER_NAME CUSTOMER_ADDRESS CITY STATE POSTAL_CODE

------------------------- ----------------------------- -------------------- ----- -----------

Impressions 5585 Westcott Ct. Sacramento CA 94206

This query finds the subset of the ORDER_T table for ORDER_ID=1003 and then matches the

row(s) in that subset with the rows in the CUSTOMER_T table that have the same
CUSTOMER_ID values.

Now, look at the equivalent query using the subquery technique.

Example 2: What is the name and address of the customer who placed order
number 1003?
SELECT CUSTOMER_NAME, CUSTOMER_ADDRESS, CITY, STATE, POSTAL_CODE
FROM CUSTOMER_T
WHERE CUSTOMER_T.CUSTOMER_ID=
(SELECT ORDER_T.CUSTOMER_ID
FROM ORDER_T
WHERE ORDER_ID=1003);

OUTPUT:

CUSTOMER_NAME CUSTOMER_ADDRESS CITY STATE POSTAL_CODE

------------------------- ----------------------------- -------------------- ----- -----------

Impressions 5585 Westcott Ct. Sacramento CA 94206

The inner query could stand on its own as an independent query. That is, the result of the
subquery, as with any query, is a set of rows, in this case, a set of CUSTOMER_ID values. To be
safe, we can, and probably should, use the IN operator rather than “=” when writing subqueries.

The subquery approach may be used for this query because we need to display data from only
the table in the outer query.

The value for ORDER_ID does not appear in the query result; it is used as the selection criterion
in the inner query. To include data from the subquery in the result, use the join technique,
because data from a subquery cannot be included in the final results.
This subquery will return at most one value, the CUSTOMER_ID associated with ORDER_ID
1003. The result will be empty if an order with that ID does not exist.

2- Subquery using Keyword IN:


A subquery can also return a list (set) of values (with zero, one, or many entries) by using the
keyword IN.

Because the result of the subquery is used to compare with one attribute (CUSTOMER_ID in
the query), the select list of a subquery may include only one attribute.

Example 3: Which customers have placed orders?

SELECT CUSTOMER_NAME FROM


CUSTOMER_T
WHERE CUSTOMER_ID IN
(SELECT DISTINCT CUSTOMER_ID
FROM ORDER_T);

OUTPUT:

CUSTOMER_NAME

--------------------

Contemporary Casuals
Furniture Gallery
Impressions
Eastern Furniture
Value Furniture
5 rows selected

As required, the subquery select list contains only the one attribute, CUSTOMER_ID, needed in the
WHERE clause of the outer query. Distinct is used in the subquery because we do not care how many
orders a customer has placed, just as long as they have placed an order.

For each customer identified in the ORDER_T table, that customer’s name has been returned from
CUSTOMER_T.
The qualifiers NOT, ANY and ALL may be used in front of IN or with logical operators such as =,>,
and <. Because IN works with zero, one, or many values from the inner query, many programmers
simply use IN instead of = for all queries, even if the equal sign would work.
Example 4: Which customers have not placed any orders for computer desks?

CUSTOMER_T

ORDER_T

ORDER_LINE_T

PRODUCT_T

SELECT CUSTOMER_NAME FROM


CUSTOMER_T
WHERE CUSTOMER_ID NOT IN
(SELECT CUSTOMER_ID FROM ORDER_T, ORDER_LINE_T, PRODUCT_T
WHERE ORDER_T.ORDER_ID= ORDER_LINE_T.ORDER_ID
AND
ORDER_LINE_T.PRODUCT_ID = PRODUCT_T.PRODUCT_ID
AND PRODUCT_DESCRIPTION='Computer Desk');
OUTPUT:

CUSTOMER_NAME

-------------------------

Contemporary Casuals

Value Furniture

Eastern Furniture

Home Furnishings

4 rows selected

Description:

The result shows that four of our customers have not yet ordered computer desks. The inner query
returned a list (set) of all customers who had ordered computer desks. The outer query listed the
names of those customers who were not in the list returned by the inner query.

3- Sub queries using EXISTS and NOT EXISTS:


Subqueries with EXISTS and NOT EXISTS. These keywords are included in an SQL query
at the same location where IN would be, just prior to the beginning of the subquery.

EXISTS will take a value of true if the subquery returns an intermediate results table that
contains one or more rows (i.e.,a non empty set), and false if no rows are returned (i.e., an empty set).
NOT EXISTS will take a value of true if no rows are returned, and false if one or more rows are
returned.

Example 5: What are the orders ID’s for all orders that have included furniture finished in
natural ash?

SELECT DISTINCT ORDER_ID FROM ORDER_LINE_T


WHERE EXISTS (SELECT * FROM PRODUCT_T WHERE PRODUCT_ID=
ORDER_LINE_T.PRODUCT_ID AND PRODUCT_FINISH='Natural Ash');

The subquery checks for each order line to see if the finish for the product on that order line is natural
ash. If this is true (EXISTS), the main query displays the order ID for that order. The outer query
checks this for every row in the set of referenced rows (the ORDER_LINE_T table). There have been
three such orders, as the result shows.
OUTPUT:

-------------------------------------------------------------------------------------------------------

ORDER_ID

----------------------

1003

1001

1002

-----------------------

3 rows selected

Description:

When EXISTS or NOT EXISTS is used in a subquery, the select list of the subquery will usually just
select all columns (SELECT *) as a placeholder because it does not matter which columns are
returned. The purpose of the subquery is to test whether any rows fit the conditions, not to return
values from particular columns for comparison purposes in the outer query. The columns will be
displayed are determined strictly by the outer query. The EXISTS subquery,like almost all EXISTS
subqueries, is a correlated subquery. Queries containing the keyword NOT EXISTS will return a
results table when no rows are found that satisfy the subquery.

Nested queries are processed inside out, although another type of subquery, a correlated subquery, is
processed outside in.

4-Correlated Sub queries:


Correlated subqueries use the result of the outer query to determine the processing of the inner query.
That is, the inner query is somewhat different for each row referenced in the outer query. In this case,
the inner query must be computed for each outer row, whereas in the earlier examples, the inner
query was computed only once for all rows processed in the outer query.

Example 6: List the details about the product with the highest unit price.
SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, STANDARD_PRICE
FROM PRODUCT_T PA
WHERE STANDARD_PRICE > ALL
(SELECT STANDARD_PRICE FROM PRODUCT_T PB
WHERE PB.PRODUCT_ID != PA.PRODUCT_ID);

OUTPUT:

PRODUCT_DESCRIPTION PRODUCT_FINISH STANDARD_PRICE

------------------------------------------ -------------------- ----------------------

Entertainment center White Ash 650

5-Using Derived Tables:


Subqueries are not limited to inclusion in the WHERE clause. They may also be used in the FROM
clause, creating a temporary derived table (or set) that is used in the query. Creating a derived table
that has an aggregate value in it, such as MAX, AVG, or MIN, allows the aggregate to be used in the
WHERE clause.

Example 7: Which products have a standard price that is higher than the average standard
price?

SELECT PRODUCT_DESCRIPTION, STANDARD_PRICE, AVGPRICE


FROM
(SELECT AVG(STANDARD_PRICE) AVGPRICE FROM PRODUCT_T), PRODUCT_T
WHERE STANDARD_PRICE > AVGPRICE;
OUTPUT:

PRODUCT_DESCRIPTION STANDARD_PRICE AVGPRICE

----------------------------- ---------------------- ----------------------

Computer Desk 375 329.166666666666666666666666666666666667

Entertainment center 650 329.166666666666666666666666666666666667


LAB TASKS:
CUSTOMER_T

ORDER_T

ORDER_LINE_T

PRODUCT_T
Lab Tasks:

Lab Task #1:Which customers have not placed any orders for writer’s desks?

Lab Task # 2: What is the name and address of the customer who placed order
number 1001?

Lab Task # 3:What is the total value of orders placed for each furniture
product?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy