You are on page 1of 11

Advanced Sub queries

6/2/2014

Neotel
Surabhi Baoker
NGM-MEA
surabhi.baoker@tcs.com

Confidentiality Statement
Include the confidentiality statement within the box provided. This has to be legally
approved
Confidentiality and Non-Disclosure Notice
The information contained in this document is confidential and proprietary to TATA
Consultancy Services. This information may not be disclosed, duplicated or used for any
other purposes. The information contained in this document may not be released in
whole or in part outside TCS for any purpose without the express written permission of
TATA Consultancy Services.

Tata Code of Conduct


We, in our dealings, are self-regulated by a Code of Conduct as enshrined in the Tata
Code of Conduct. We request your support in helping us adhere to the Code in letter and
spirit. We request that any violation or potential violation of the Code by any person be
promptly brought to the notice of the Local Ethics Counselor or the Principal Ethics
Counselor or the CEO of TCS. All communication received in this regard will be treated
and kept as confidential.

2
InternalUse

TableofContent
1.

Introduction .............................................................................................................................................................. 4
1.1Basicfeaturesofsubqueries .................................................................................................................................. 4

2.

Multiplecolumnsubquery ....................................................................................................................................... 5
2.1Pairwisecolumncomparisons................................................................................................................................. 5

2.2Nonpairwisecolumncomparisons ........................................................................................................................ 6
3.Scalarsubqueries ......................................................................................................................................................... 7
4.Correlatedsubqueries.................................................................................................................................................. 8
5.Typesofoperatorsinsubqueries................................................................................................................................. 9
5.1TheEXISTSOperator ............................................................................................................................................... 9
5.2The NOT EXISTS Operator................................................................................................................................ 9
5.3TheWITHclause...................................................................................................................................................... 9

3
InternalUse

1.

Introduction

A sub query is a select statement written in a clause of another SQL statement. The main query within which a sub
query is written is called the parent query.
Sub queries are very useful in case of extracting data from a condition which depends on data present in some
other table or data in itself. It is useful when data to be extracted depends on unknown conditional values.

1.1 Basic features of sub queries


Using a nested sub query is equivalent to two queries being performed sequentially. Sub queries can be used for
the following purposes:
Providing values for clauses of SQL statement. (WHERE, HAVING, START WITH)
Inserting rows in a target table using INSERT INTO, CREAT TABLE as SELECT statement
Defining rows to be updated according to specific condition
A sub query gets executed only once for the parent query. The syntax of the query will be as follows:
SELECT select_list
FROM table
WHERE expr operator (SELECT select_list
FROM table);

4
InternalUse

2.

Multiple column sub query

Sub queries can also be used for making column wise comparisons. If desired result is based on two or more
columns and their values, multiple column sub query can be used.
The syntax of the query will be as follows:
SELECT column, column, ...
FROM table
WHERE (column, column, ...) IN
(SELECT column, column, ...
FROM table
WHERE condition);

2.1 Pairwise column comparisons


A multi column sub query can be used to retrieve data in a pairwise fashion. By pairwise fashion it means that the
desired output contains two or more columns and with their respective values being used in the pairwise manner
by the parent query.
The syntax of the query will be as follows:

SELECT column1, column2, column3


FROM table
WHERE (column1, column2) IN
(SELECT column1, column2
FROM table
WHERE column2 IN (values);

Example:
SELECT employee_id, manager_id, department_id
FROM employees
WHERE (manager_id, department_id) IN
(SELECT manager_id, department_id
FROM employees
WHERE employee_id IN (178,174))
AND employee_id NOT IN (178,174);

5
InternalUse

2.2 Non pairwise column comparisons


In a non-pairwise comparison, each of the columns from the WHERE clause of the parent SELECT statement are
individually compared to multiple values retrieved by the inner select statement. The individual columns can
match any of the values retrieved by the inner select statement. But collectively, all the multiple conditions of the
main SELECT statement must be satisfied for the row to be displayed.
Here each of the condition required in the parent statement can query the table separately column wise.
The syntax of the query will be as follows:

SELECT column1, column2, column3


FROM table
WHERE cloumn2 IN
(SELECT column2
FROM table
WHERE column1 IN (values))
AND column3 IN
(SELECT column3
FROM table
WHERE column2 IN (values));
Example:
SELECT employee_id, manager_id, department_id
FROM employees
WHERE manager_id IN
(SELECT manager_id
FROM employees
WHERE employee_id IN (174,141))
AND department_id IN
(SELECT department_id
FROM employees
WHERE employee_id IN (174,141))
AND employee_id NOT IN(174,141);

6
InternalUse

3. Scalar sub queries


Scalar sub query returns a single column value from one row. Multiple column sub queries do not come under
scalar sub query. This can be used when exact conditional value to be used by the parent query is known. If the
sub query returns zero rows then the value of scalar sub query is null.
The usage of scalar sub query can be best explained with the following examples:

SELECT
(SELECT MAX(salary) FROM employees) AS Highest_sal,
(SELECT AVG(salary) FROM employess) AS Average_sal
FROM employees
WHERE department_id = 10;
SELECT employee_id, last_name,
(CASE
WHEN department_id =
THEN Canada ELSE USA END) location
FROM employees;
(SELECT department_id FROM departments
WHERE location_id = 1800)
The scalar sub query can be used in most of the queries which are expression (expr) type. However, scalar sub
queries cannot be used in the below conditions:

As default values for columns


As hash expressions for clusters
In the RETURNING clause of DML statements
As the basis of a function-based index
In CHECK constraints
In WHEN conditions of CASE expressions
In GROUP BY and HAVING clauses
In START WITH and CONNECT BY clauses
In statements that are unrelated to queries, such as CREATE PROFILE

7
InternalUse

4. Correlated sub queries

The Oracle Server performs a correlated sub query when the sub query references a column from a table referred
to in the parent statement. A correlated sub query is evaluated once for each row processed by the parent
statement. Correlated sub queries are used for row-by-row processing. Each sub query is executed once for every
row of the outer query.
Correlated Sub query is executed according to the following steps:

Get a candidate row (fetched by the outer query).


Execute the inner query using the value of the candidate row.
Use the values resulting from the inner query to qualify or disqualify the candidate.
Repeat until no candidate row remains.

The syntax of the query will be as follows:

SELECT column1, column2,...


FROM table1
WHERE column1 operator
(SELECT colum1, column2
FROM table2
WHERE expr1 = .expr2);
Example:
SELECT last_name, salary, department_id
FROM employees outer
WHERE salary >
(SELECT AVG(salary)
FROM employees
WHERE department_id =
outer.department_id);
SELECT e.employee_id, last_name,e.job_id
FROM employees e
WHERE 2 <= (SELECT COUNT(*)
FROM job_history
WHERE employee_id = e.employee_id);

8
InternalUse

5. Types of operators in sub queries

Sub queries also facilitate use of few operators which help in limiting the search operations in the database. Each
of the operators has a unique style which makes retrieving data easy and also enhances performance.
Few are discussed below.

5.1 The EXISTS Operator


The EXISTS operator ensures that the search in the inner query does not continue when at least one match is
found.

Example:

SELECT employee_id, last_name, job_id, department_id


FROM employees outer
WHERE EXISTS (SELECT X
FROM employees
WHERE manager_id =
outer.employee_id);

5.2 The NOT EXISTS Operator


Just as the EXISTS operator, the NOT EXISTS can limit the query search with a negation condition. It works to
extract result from the table which are not present in the sub query.
Example:

SELECT department_id, department_name


FROM departments d
WHERE NOT EXISTS (SELECT X
FROM employees
WHERE department_id
= d.department_id);

5.3 The WITH clause


At times the data extraction from the database demands writing of the same SELECT statement in a complex
query more than once. This can be easily catered by the WITH clause. The WITH clause retrieves the result of a
query block and stores it in a temporary tablespace.
The WITH clause makes the query easy to read. Moreover it evaluates the clause only once even if it is used many
times in the query, thereby enhancing the performance immensely.
Usage of WITH clause:

9
InternalUse

Used with SELECT statements only


A query name is visible to all WITH element query blocks (including their sub query blocks) defined after it
and the main query block itself (including its sub query blocks)
The WITH clause can hold more than one query. Each query is then separated by a comma.
When the query name is the same as an existing table name, the parser searches from the inside out, the
query block name takes precedence over the table name.

10
InternalUse

Thank You

Contact
For more information, contact gsl.cdsfiodg@tcs.com (Email Id of ISU)

AboutTataConsultancyServices(TCS)
TataConsultancyServicesisanITservices,consultingandbusinesssolutions
organizationthatdeliversrealresultstoglobalbusiness,ensuringalevelofcertaintyno
otherfirmcanmatch.TCSoffersaconsultingled,integratedportfolioofITandIT
enabledinfrastructure,engineeringandassuranceservices.Thisisdeliveredthroughits
TM
uniqueGlobalNetworkDeliveryModel ,recognizedasthebenchmarkofexcellencein
softwaredevelopment.ApartoftheTataGroup,Indiaslargestindustrialconglomerate,
TCShasaglobalfootprintandislistedontheNationalStockExchangeandBombay
StockExchangeinIndia.
Formoreinformation,visitusatwww.tcs.com.

ITServices
BusinessSolutions
Consulting

All content / information present here is the exclusive property of Tata Consultancy Services Limited (TCS). The content /
information contained here is correct at the time of publishing. No material from here may be copied, modified, reproduced,
republished, uploaded, transmitted, posted or distributed in any form without prior written permission from TCS.
Unauthorized use of the content / information appearing here may violate copyright, trademark and other applicable laws,
and could result in criminal or civil penalties. Copyright 2011 Tata Consultancy Services Limited

You might also like