advanced sub queries

11
Advanced Sub queries 6/2/2014 Neotel Surabhi Baoker NGM-MEA [email protected]

Upload: rajesh-rai

Post on 18-Feb-2016

217 views

Category:

Documents


3 download

DESCRIPTION

na

TRANSCRIPT

Page 1: Advanced Sub Queries

 

 

Advanced Sub queries

6/2/2014

Neotel

Surabhi Baoker

NGM-MEA

[email protected]

Page 2: Advanced Sub Queries

  

 2 

Internal Use 

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.

 

Page 3: Advanced Sub Queries

  

 3 

Internal Use 

Table of Content 

1.  Introduction .............................................................................................................................................................. 4 

1.1 Basic features of sub queries .................................................................................................................................. 4 

2.  Multiple column sub query ....................................................................................................................................... 5 

2.1 Pairwise column comparisons................................................................................................................................. 5 

    2.2  Non pairwise column comparisons ........................................................................................................................ 6 

3. Scalar sub queries ......................................................................................................................................................... 7 

4. Correlated sub queries.................................................................................................................................................. 8 

5. Types of operators in sub queries................................................................................................................................. 9 

5.1 The EXISTS Operator ............................................................................................................................................... 9 

5.2 The NOT EXISTS Operator ................................................................................................................................9 

5.3 The WITH clause...................................................................................................................................................... 9 

Page 4: Advanced Sub Queries

  

 4 

Internal Use 

 

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);

Page 5: Advanced Sub Queries

  

 5 

Internal Use 

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);   

Page 6: Advanced Sub Queries

  

 6 

Internal Use 

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);

Page 7: Advanced Sub Queries

  

 7 

Internal Use 

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

Page 8: Advanced Sub Queries

  

 8 

Internal Use 

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);  

Page 9: Advanced Sub Queries

  

 9 

Internal Use 

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:

Page 10: Advanced Sub Queries

  

 10 

Internal Use 

ν 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.

 

 

Page 11: Advanced Sub Queries

  

Thank You 

Contact

For more information, contact [email protected] (Email Id of ISU)

 

About Tata Consultancy Services (TCS) 

Tata Consultancy Services is an IT services, consulting and business solutions organization that delivers real results to global business, ensuring a level of certainty no other firm can match. TCS offers a consulting‐led, integrated portfolio of IT and IT‐enabled infrastructure, engineering and assurance services. This is delivered through its unique Global Network Delivery ModelTM, recognized as the benchmark of excellence in software development. A part of the Tata Group, India’s largest industrial conglomerate, TCS has a global footprint and is listed on the National Stock Exchange and Bombay Stock Exchange in India. 

For more information, visit us at www.tcs.com. 

 

IT Services Business Solutions 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