Vous êtes sur la page 1sur 7

4.1.

Using SubQuery

SQL Subquery
1.1 Objective

Understand SQL Subqueries

Understand Single row, Multiple row and Column Subqueries

Understand Correlated Subqueries

1.2 Introduction

A SUBQUERY is a SQL query nested inside another query.

It is also called as INNER QUERY as it is placed as a part of another query called as


MAIN QUERY / OUTER QUERY.

Subqueries are an alternate way of returning data from multiple tables.

It can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside


another subquery.

It is usually added within the WHERE Clause of another SQL statement.

Subquery in a SELECT statement may occur in:

a SELECT clause

a FROM clause

a WHERE clause

Subqueries can be used with the comparison operators such as =, <, >, >=, <=, and also
with the multiple row operators such as IN, ANY or ALL.

Execution Process:

Inner query executes first and passes the result to outer query.

Outer query executes based on the result of inner query.

Syntax:
SELECT select_list
FROM table
WHERE expression comparison_operator
(SELECT select_list
FROM table);

1.3 SubQueries Guidelines

A Subquery must be enclosed in parentheses.

It must be placed on the right side of the comparison operator.

Use comparison operators with single row subqueries.

Inner query should return only one column when comparison operators are used in the
outer query.

The column used in the WHERE clause of outer query should be compatible with the
column information returned by the inner query.

Subqueries cannot manipulate their results internally, therefore ORDER BY clause


cannot be added in to a subquery. ORDER BY clause can be used in the main SELECT
statement (outer query).

GROUP BY and HAVING clauses cannot be used in the inner query when comparison
operators are used in the outer query.

If inner query returns a null value to the outer query, the outer query will not return any
rows when using certain comparison operators in a WHERE clause.

Subqueries that return more than one row can only be used with multiple value
operators, such as the IN operator.

The ntext, text, and image data types cannot be used in the select list of subqueries.
Note: If an error occurs while executing a subquery, execute the inner query
separately to check and fix the error.

1.4 Types of Operators


Following are the operators that can be used in subqueries:
1.

Comparison Operators (<, >, <=, >=, =, <>) can be used only when the inner query
returns a single value.

2.

List Operators (IN, NOT IN) can be used if the inner query returns a single column
with multiple values.

3.

Modified Comparison Operators (ANY or ALL) can be used if the inner query returns
multiple values for outer query evaluation. ANY, ALL operators always used in combination
with comparison operators.
Ex: =any, <any, >any, <all, >all.

4.

Existence Operators (Exits or NOT Exists) can be used to check the existence of
records in the inner query, and returns TRUE or FALSE based on the existence of data.
Note: The select list of a subquery introduced with EXISTS, by convention,
has an asterisk (*) instead of a single column name.

1.5 Subquery in SELECT Statement


A Subquery in SELECT statement can be used in a SELECT clause, a FROM clause or a
WHERE clause.
SELECT CLAUSE:
When subquery is used in SELECT clause, it must return a scalar (single) value for each row
returned by the outer query. It is generally used when we wish to retrieve a calculation using an
aggregate function such as the SUM, COUNT, MIN, or MAX function, but do not want the
aggregate function to apply to the main query.
Example: Display the maximum salary of each department.

SELECT d1.dept_name, d1.location,


(SELECT MAX(salary)
FROM tblemployees e1
WHERE d1.dept_no=e1.dept_no) highest_salary
FROM tblDepartment d1
FROM CLAUSE:
A subquery can also be used in the FROM clause to return multiple rows and columns. The
results returned by such a subquery are referred to as a derived table / inline views. A derived
table is useful to work with a subset of data from one or more tables without needing to create a
view or temporary table.
Example: Display the employee details with department name for those whose
department name has letter e.
SELECT emp_id, first_name, last_name, salary, d1.dept_name
FROM tblEmployees e1,
(SELECT dept_no, dept_name
FROM tblDepartment
WHERE dept_name LIKE '%e%')
AS d1
WHERE e1.dept_no=d1.dept_no
WHERE CLAUSE:
Most often, the subquery will be found in the WHERE clause. For instance, different subquery
operators can be used to compare a columns value to a value returned by the subquery.
Single row operator Ex: Use comparison operators such as =, <>, >, <, <=,>=
Display the employee details of Sales Department.
SELECT emp_id, first_name, last_name, salary, designation

FROM tblemployees
WHERE dept_no =
(SELECT dept_no
FROM tblDepartment
WHERE dept_name='sales')
Note: When single row operator is used, and if a subquery returns more than one row
then the query will become invalid and an error will be returned.
Multi row operator Ex: Use IN, ANY, or ALL operator in outer query to handle a subquery that
returns multiple rows.
Display the employee details of Learning and Sales Department.
SELECT emp_id, first_name, last_name, salary, designation
FROM tblemployees
WHERE dept_no IN
(SELECT dept_no
FROM tblDepartment
WHERE dept_name IN ('sales',learning))

1.6 Subquery in INSERT Statement


Subquery can be used with INSERT statement to add rows of data from one or more tables
to another table. Consider a table tblEMPLOYEES_BKP with similar structure as
tblEMPLOYEES table. Lets try to copy employee details of sales department from
tblEMPLOYEES table into tblEMPLOYEES _BKP:
INSERT INTO tblEMPLOYEES_BKP
SELECT * FROM tblEMPLOYEES
WHERE dept_no =
(SELECT dept_no FROM tblDepartment

WHERE dept_name = 'sales')

1.7 Subquery in UPDATE Statement


The subquery can be used in conjunction with the UPDATE statement. Either single or
multiple columns in a table can be updated when using a subquery with the UPDATE
statement.
Example: Update the SALARY by 0.25 times in EMPLOYEES table for
employees working in Sales department.
UPDATE tblEMPLOYEES
SET salary = salary * 0.25
WHERE dept_no =
(SELECT dept_no FROM tblDepartment
WHERE dept_name = 'sales')

1.8 Subquery in DELETE Statement


DELETE statement can be used with subqueries.
Example: Delete the Learning department employee details from EMPLOYEES
table.
DELETE tblEMPLOYEES
WHERE dept_no =
(SELECT dept_no FROM tblDepartment
WHERE dept_name = 'learning')

1.9 Correlated Subquery


A query is called correlated subquery when both the inner query and the outer query are
interdependent. These are used to select data from a table referenced in the outer query.

In correlated subquery, the inner query processing depends on the execution of outer query.
Depending on the results of the correlated subquery execution, it will determine if the row of
the outer query is returned in the final result set.
In this type of queries, a table alias must be used to specify which table reference is to be
used.
Execution Process:

Outer query executes first and passes the result to inner query.

For each row of Outer query result, inner query will be executed.
Display the Departments information where at least one employee is working.
SELECT dept_no, dept_name, location
FROM tbldepartment d1
WHERE EXISTS
(SELECT * FROM tblEmployees e1 WHERE e1.dept_no=d1.dept_no)
Display the list of all employees whose salary is above the average salary for each
employees department.
SELECT emp_id, first_name, last_name
FROM tblEmployees e1
WHERE salary >
(SELECT AVG(salary)
FROM tblEmployees e2
WHERE e1.dept_no=e2.dept_no)

Vous aimerez peut-être aussi