SUB QUERIES

From rbachwiki
Revision as of 20:40, 14 November 2017 by Bacchas (talk | contribs)
Jump to navigation Jump to search

A SUB QUERY is a query within a query which can return one or more rows

SELECT * FROM SALES
WHERE CUSTOMER_ID =
(SELECT CUSTOMER_ID FROM CUSTOMER WHERE LAST_NAME = 'JOSEPH'

A SUBQUERY executes first before the main query, SO the customer id was returned from the the subquery then passed to the original query

When the subquery returns more than one value use the IN instead of the =

SELECT * FROM SALES
WHERE CUSTOMER_ID IN  
(SELECT CUSTOMER_ID FROM CUSTOMER WHERE REGION ='SOUTH')
SELECT * FROM SALES
WHERE CUSTOMER_ID IN
(SELECT CUSTOMER_ID FROM CUSTOMER WHERE LAST_NAME = 'JOSEPH' OR last_name = 'mann'

SUBQUERY ON MULTIPLE COLUMNS

SELECT sales_date, order_id, customer_id, product_id, unit_price
FROM sales
WHERE (product_id, unit_price) IN
(
SELECT product_id, unit_price
FROM sales
WHERE sales_date = '01-jan-2015'
)

Back To Top- Home - Category