CHAPTER -7
Sub-quERiES
Let’s make coding fun!
Sub-Query is a form of an SQL statement that appears inside
another SQL statement. Also known as NESTED Query i.e., SQL
query within a query A Subquery or Inner query or a Nested query
is a query within another SQL query and embedded within the
WHERE clause. A subquery is used to return data that will be used
in the main query as a condition to further restrict the data to be
retrieved. Subqueries can be used with the SELECT, INSERT,
UPDATE, and DELETE statements along with the operators like =,
<, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow −
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause,
unless multiple columns are in the main query for the
subquery to compare its selected columns.
An ORDER BY command cannot be used in a subquery,
although the main query can use an ORDER BY. The GROUP
BY command can be used to perform the same function as the
ORDER BY in a subquery.
Subqueries that return more than one row can only be used
with multiple value operators such as the IN operator.
The SELECT list cannot include any references to values that
evaluate to a BLOB, ARRAY, CLOB, or NCLOB.
A subquery cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a subquery.
However, the BETWEEN operator can be used within the
subquery.
The SQL UNION Operator
The UNION operator is used to combine the result-set of two or
more SELECT statements.
Each SELECT statement within UNION must have the same
number of columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the
same order
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
UNION ALL Syntax
The UNION operator selects only distinct values by default. To allow
duplicate values, use UNION ALL:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Note: The column names in the result-set are usually equal to the
column names in the first SELECT statement in the UNION.
CONCLuSiON
In this chapter, we have covered about sub-query and
learned how to create and composition of query using
operator and sub-queries.