We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2
Practical 10
Retrieve data spread from multiple tables using subqueries
2.1 Subqueries - Multiple, Correlated
A Subquery or Inner query or 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. Subquery 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 Sub queries must follow: Subquery 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 cannot be used in a Subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a Subquery. Subquery 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. Syntax: SELECT column_name [, column_name] FROM table1 [, table2] WHERE column_name OPERATOR (SELECT column_name [, column_name] FROM table1 [, table2] [WHERE])
Example: Consider the CUSTOMERS table having the following records:
Now, let us check following Subquery with SELECT statement:
SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS
WHERE SALARY > 4500);
This would produce the following result:
Id Name Dept Age Salary Location
101 Hrithik Electronics 28 6500 Bangalore 102 Harsha Aeronautics 28 5500 Mysore Correlated Subquery A query is called correlated Subquery when both the inner query and the outer query are interdependent. For every row processed by the inner query, the outer query is processed as well. The inner query depends on the outer query before it can be processed.
SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID, MAX (SALARY) FROM