Professional Documents
Culture Documents
http://www.tuto rialspo int.co m/sql_ce rtificate /subque rie s_to _so lve _que rie s.htm
Types of Subqueries
Sing le Row Sub Q uery: Sub query which returns sing le row output. T hey mark the usag e of sing le row
comparison operators, when used in WHERE conditions.
Multiple row sub query: Sub query returning multiple row output. T hey make use of multiple row
comparison operators like IN, ANY, ALL. T here can be sub queries returning multiple columns also.
Correlated Sub Q uery: Correlated subqueries depend on data provided by the outer query.T his type of
subquery also includes subqueries that use the EXIST S operator to test the existence of data rows satisfying
specified criteria.
A HAVING clause is used when the g roup results of a query need to be restricted based on some condition. If a
subquery's result must be compared with a g roup function, you must nest the inner query in the outer query's
HAVING clause.
Note in the above query, IN matches department ids returned from the sub query,compares it with that in the
main query and returns employee's name who satisfy the condition.
A join would be better solution for above query, but for purpose of illustration, sub query has been used in it.
When a multiple-column subquery is used in the outer query's FROM clause, it creates a temporary table that can
be referenced by other clauses of the outer query. T his temporary table is more formally called an inline view.
T he subquery's results are treated like any other table in the FROM clause. If the temporary table contains
g rouped data, the g rouped subsets are treated as separate rows of data in a table. Consider the FROM clause
in the below query. T he inline view formed by the subquery is the data source for the main query.
SELECT *
FROM (SELECT salary, department_id
FROM employees
WHERE salary BETWEEN 1000 and 2000);