w3resource

SQL Nested subqueries

Nested subqueries

A subquery can be nested inside other subqueries. SQL has an ability to nest queries within one another. A subquery is a SELECT statement that is nested within another SELECT statement and which return intermediate results. SQL executes innermost subquery first, then next level. See the following examples :

Example -1 : Nested subqueries

If we want to retrieve that unique job_id and there average salary from the employees table which unique job_id have a salary is smaller than (the maximum of averages of min_salary of each unique job_id from the jobs table which job_id are in the list, picking from (the job_history table which is within the department_id 50 and 100)) the following SQL statement can be used :

Sample table: employees
employee_id  first_name  last_name   email       phone_number  hire_date   job_id      salary      commission_pct  manager_id  department_id
-----------  ----------  ----------  ----------  ------------  ----------  ----------  ----------  --------------  ----------  -------------
100          Steven      King        SKING       515.123.4567  6/17/1987   AD_PRES     24000                                   90
101          Neena       Kochhar     NKOCHHAR    515.123.4568  6/18/1987   AD_VP       17000                       100         90
102          Lex         De Haan     LDEHAAN     515.123.4569  6/19/1987   AD_VP       17000                       100         90
103          Alexander   Hunold      AHUNOLD     590.423.4567  6/20/1987   IT_PROG     9000                        102         60
104          Bruce       Ernst       BERNST      590.423.4568  6/21/1987   IT_PROG     6000                        103         60
105          David       Austin      DAUSTIN     590.423.4569  6/22/1987   IT_PROG     4800                        103         60
106          Valli       Pataballa   VPATABAL    590.423.4560  6/23/1987   IT_PROG     4800                        103         60
107          Diana       Lorentz     DLORENTZ    590.423.5567  6/24/1987   IT_PROG     4200                        103         60
108          Nancy       Greenberg   NGREENBE    515.124.4569  6/25/1987   FI_MGR      12000                       101         100
109          Daniel      Faviet      DFAVIET     515.124.4169  6/26/1987   FI_ACCOUNT  9000                        108         100
110          John        Chen        JCHEN       515.124.4269  6/27/1987   FI_ACCOUNT  8200                        108         100
111          Ismael      Sciarra     ISCIARRA    515.124.4369  6/28/1987   FI_ACCOUNT  7700                        108         100
112          Jose Manue  Urman       JMURMAN     515.124.4469  6/29/1987   FI_ACCOUNT  7800                        108         100
113          Luis        Popp        LPOPP       515.124.4567  6/30/1987   FI_ACCOUNT  6900                        108         100
114          Den         Raphaely    DRAPHEAL    515.127.4561  7/1/1987    PU_MAN      11000                       100         30
115          Alexander   Khoo        AKHOO       515.127.4562  7/2/1987    PU_CLERK    3100                        114         30
116          Shelli      Baida       SBAIDA      515.127.4563  7/3/1987    PU_CLERK    2900                        114         30
117          Sigal       Tobias      STOBIAS     515.127.4564  7/4/1987    PU_CLERK    2800                        114         30
118          Guy         Himuro      GHIMURO     515.127.4565  7/5/1987    PU_CLERK    2600                        114         30
119          Karen       Colmenares  KCOLMENA    515.127.4566  7/6/1987    PU_CLERK    2500                        114         30
120          Matthew     Weiss       MWEISS      650.123.1234  7/7/1987    ST_MAN      8000                        100         50
121          Adam        Fripp       AFRIPP      650.123.2234  7/8/1987    ST_MAN      8200                        100         50
122          Payam       Kaufling    PKAUFLIN    650.123.3234  7/9/1987    ST_MAN      7900                        100         50
123          Shanta      Vollman     SVOLLMAN    650.123.4234  7/10/1987   ST_MAN      6500                        100         50
124          Kevin       Mourgos     KMOURGOS    650.123.5234  7/11/1987   ST_MAN      5800                        100         50
125          Julia       Nayer       JNAYER      650.124.1214  7/12/1987   ST_CLERK    3200                        120         50
126          Irene       Mikkilinen  IMIKKILI    650.124.1224  7/13/1987   ST_CLERK    2700                        120         50
127          James       Landry      JLANDRY     650.124.1334  7/14/1987   ST_CLERK    2400                        120         50
128          Steven      Markle      SMARKLE     650.124.1434  7/15/1987   ST_CLERK    2200                        120         50
129          Laura       Bissot      LBISSOT     650.124.5234  7/16/1987   ST_CLERK    3300                        121         50
130          Mozhe       Atkinson    MATKINSO    650.124.6234  7/17/1987   ST_CLERK    2800                        121         50
131          James       Marlow      JAMRLOW     650.124.7234  7/18/1987   ST_CLERK    2500                        121         50
132          TJ          Olson       TJOLSON     650.124.8234  7/19/1987   ST_CLERK    2100                        121         50
133          Jason       Mallin      JMALLIN     650.127.1934  7/20/1987   ST_CLERK    3300                        122         50
134          Michael     Rogers      MROGERS     650.127.1834  7/21/1987   ST_CLERK    2900                        122         50
135          Ki          Gee         KGEE        650.127.1734  7/22/1987   ST_CLERK    2400                        122         50
136          Hazel       Philtanker  HPHILTAN    650.127.1634  7/23/1987   ST_CLERK    2200                        122         50
137          Renske      Ladwig      RLADWIG     650.121.1234  7/24/1987   ST_CLERK    3600                        123         50
138          Stephen     Stiles      SSTILES     650.121.2034  7/25/1987   ST_CLERK    3200                        123         50
139          John        Seo         JSEO        650.121.2019  7/26/1987   ST_CLERK    2700                        123         50
140          Joshua      Patel       JPATEL      650.121.1834  7/27/1987   ST_CLERK    2500                        123         50
141          Trenna      Rajs        TRAJS       650.121.8009  7/28/1987   ST_CLERK    3500                        124         50
142          Curtis      Davies      CDAVIES     650.121.2994  7/29/1987   ST_CLERK    3100                        124         50
143          Randall     Matos       RMATOS      650.121.2874  7/30/1987   ST_CLERK    2600                        124         50
144          Peter       Vargas      PVARGAS     650.121.2004  7/31/1987   ST_CLERK    2500                        124         50
145          John        Russell     JRUSSEL     011.44.1344.  8/1/1987    SA_MAN      14000       0.4             100         80
146          Karen       Partners    KPARTNER    011.44.1344.  8/2/1987    SA_MAN      13500       0.3             100         80
147          Alberto     Errazuriz   AERRAZUR    011.44.1344.  8/3/1987    SA_MAN      12000       0.3             100         80
148          Gerald      Cambrault   GCAMBRAU    011.44.1344.  8/4/1987    SA_MAN      11000       0.3             100         80
149          Eleni       Zlotkey     EZLOTKEY    011.44.1344.  8/5/1987    SA_MAN      10500       0.2             100         80
150          Peter       Tucker      PTUCKER     011.44.1344.  8/6/1987    SA_REP      10000       0.3             145         80
151          David       Bernstein   DBERNSTE    011.44.1344.  8/7/1987    SA_REP      9500        0.25            145         80
152          Peter       Hall        PHALL       011.44.1344.  8/8/1987    SA_REP      9000        0.25            145         80
153          Christophe  Olsen       COLSEN      011.44.1344.  8/9/1987    SA_REP      8000        0.2             145         80
154          Nanette     Cambrault   NCAMBRAU    011.44.1344.  8/10/1987   SA_REP      7500        0.2             145         80
155          Oliver      Tuvault     OTUVAULT    011.44.1344.  8/11/1987   SA_REP      7000        0.15            145         80
156          Janette     King        JKING       011.44.1345.  8/12/1987   SA_REP      10000       0.35            146         80
157          Patrick     Sully       PSULLY      011.44.1345.  8/13/1987   SA_REP      9500        0.35            146         80
158          Allan       McEwen      AMCEWEN     011.44.1345.  8/14/1987   SA_REP      9000        0.35            146         80
159          Lindsey     Smith       LSMITH      011.44.1345.  8/15/1987   SA_REP      8000        0.3             146         80
160          Louise      Doran       LDORAN      011.44.1345.  8/16/1987   SA_REP      7500        0.3             146         80
161          Sarath      Sewall      SSEWALL     011.44.1345.  8/17/1987   SA_REP      7000        0.25            146         80
162          Clara       Vishney     CVISHNEY    011.44.1346.  8/18/1987   SA_REP      10500       0.25            147         80
163          Danielle    Greene      DGREENE     011.44.1346.  8/19/1987   SA_REP      9500        0.15            147         80
164          Mattea      Marvins     MMARVINS    011.44.1346.  8/20/1987   SA_REP      7200        0.1             147         80
165          David       Lee         DLEE        011.44.1346.  8/21/1987   SA_REP      6800        0.1             147         80
166          Sundar      Ande        SANDE       011.44.1346.  8/22/1987   SA_REP      6400        0.1             147         80
167          Amit        Banda       ABANDA      011.44.1346.  8/23/1987   SA_REP      6200        0.1             147         80
168          Lisa        Ozer        LOZER       011.44.1343.  8/24/1987   SA_REP      11500       0.25            148         80
169          Harrison    Bloom       HBLOOM      011.44.1343.  8/25/1987   SA_REP      10000       0.2             148         80
170          Tayler      Fox         TFOX        011.44.1343.  8/26/1987   SA_REP      9600        0.2             148         80
171          William     Smith       WSMITH      011.44.1343.  8/27/1987   SA_REP      7400        0.15            148         80
172          Elizabeth   Bates       EBATES      011.44.1343.  8/28/1987   SA_REP      7300        0.15            148         80
173          Sundita     Kumar       SKUMAR      011.44.1343.  8/29/1987   SA_REP      6100        0.1             148         80
174          Ellen       Abel        EABEL       011.44.1644.  8/30/1987   SA_REP      11000       0.3             149         80
175          Alyssa      Hutton      AHUTTON     011.44.1644.  8/31/1987   SA_REP      8800        0.25            149         80
176          Jonathon    Taylor      JTAYLOR     011.44.1644.  9/1/1987    SA_REP      8600        0.2             149         80
177          Jack        Livingston  JLIVINGS    011.44.1644.  9/2/1987    SA_REP      8400        0.2             149         80
178          Kimberely   Grant       KGRANT      011.44.1644.  9/3/1987    SA_REP      7000        0.15            149
179          Charles     Johnson     CJOHNSON    011.44.1644.  9/4/1987    SA_REP      6200        0.1             149         80
180          Winston     Taylor      WTAYLOR     650.507.9876  9/5/1987    SH_CLERK    3200                        120         50
181          Jean        Fleaur      JFLEAUR     650.507.9877  9/6/1987    SH_CLERK    3100                        120         50
182          Martha      Sullivan    MSULLIVA    650.507.9878  9/7/1987    SH_CLERK    2500                        120         50
183          Girard      Geoni       GGEONI      650.507.9879  9/8/1987    SH_CLERK    2800                        120         50
184          Nandita     Sarchand    NSARCHAN    650.509.1876  9/9/1987    SH_CLERK    4200                        121         50
185          Alexis      Bull        ABULL       650.509.2876  9/10/1987   SH_CLERK    4100                        121         50
186          Julia       Dellinger   JDELLING    650.509.3876  9/11/1987   SH_CLERK    3400                        121         50
187          Anthony     Cabrio      ACABRIO     650.509.4876  9/12/1987   SH_CLERK    3000                        121         50
188          Kelly       Chung       KCHUNG      650.505.1876  9/13/1987   SH_CLERK    3800                        122         50
189          Jennifer    Dilly       JDILLY      650.505.2876  9/14/1987   SH_CLERK    3600                        122         50
190          Timothy     Gates       TGATES      650.505.3876  9/15/1987   SH_CLERK    2900                        122         50
191          Randall     Perkins     RPERKINS    650.505.4876  9/16/1987   SH_CLERK    2500                        122         50
192          Sarah       Bell        SBELL       650.501.1876  9/17/1987   SH_CLERK    4000                        123         50
193          Britney     Everett     BEVERETT    650.501.2876  9/18/1987   SH_CLERK    3900                        123         50
194          Samuel      McCain      SMCCAIN     650.501.3876  9/19/1987   SH_CLERK    3200                        123         50
195          Vance       Jones       VJONES      650.501.4876  9/20/1987   SH_CLERK    2800                        123         50
196          Alana       Walsh       AWALSH      650.507.9811  9/21/1987   SH_CLERK    3100                        124         50
197          Kevin       Feeney      KFEENEY     650.507.9822  9/22/1987   SH_CLERK    3000                        124         50
198          Donald      OConnell    DOCONNEL    650.507.9833  9/23/1987   SH_CLERK    2600                        124         50
199          Douglas     Grant       DGRANT      650.507.9844  9/24/1987   SH_CLERK    2600                        124         50
200          Jennifer    Whalen      JWHALEN     515.123.4444  9/25/1987   AD_ASST     4400                        101         10
201          Michael     Hartstein   MHARTSTE    515.123.5555  9/26/1987   MK_MAN      13000                       100         20
202          Pat         Fay         PFAY        603.123.6666  9/27/1987   MK_REP      6000                        201         20
203          Susan       Mavris      SMAVRIS     515.123.7777  9/28/1987   HR_REP      6500                        101         40
204          Hermann     Baer        HBAER       515.123.8888  9/29/1987   PR_REP      10000                       101         70
205          Shelley     Higgins     SHIGGINS    515.123.8080  9/30/1987   AC_MGR      12000                       101         110
206          William     Gietz       WGIETZ      515.123.8181  10/1/1987   AC_ACCOUNT  8300                        205         110
Sample table: jobs
JOB_ID JOB_TITLE MIN_SALARY MAX_SALARY
AD_PRES President 20000 40000
AD_VP Administration Vice President 15000 30000
AD_ASST Administration Assistant 3000 6000
FI_MGR Finance Manager 8200 16000
FI_ACCOUNT Accountant 4200 9000
AC_MGR Accounting Manager 8200 16000
AC_ACCOUNT Public Accountant 4200 9000
SA_MAN Sales Manager 10000 20000
SA_REP Sales Representative 6000 12000
PU_MAN Purchasing Manager 8000 15000
PU_CLERK Purchasing Clerk 2500 5500
ST_MAN Stock Manager 5500 8500
ST_CLERK Stock Clerk 2000 5000
SH_CLERK Shipping Clerk 2500 5500
IT_PROG Programmer 4000 10000
MK_MAN Marketing Manager 9000 15000
MK_REP Marketing Representative 4000 9000
HR_REP Human Resources Representative 4000 9000
PR_REP Public Relations Representative 4500 10500

SQL Code:


-- Selecting job_id and the average salary from the employees table
SELECT job_id, AVG(salary) 
-- Grouping the results by job_id
FROM employees   
GROUP BY job_id   
-- Filtering the grouped results based on a condition
HAVING AVG(salary) <           
    (
        -- Selecting the maximum of the average of min_salary from the jobs table
        SELECT MAX(AVG(min_salary))            
        -- From the jobs table
        FROM jobs             
        -- Filtering jobs where the job_id is in the subquery result
        WHERE job_id IN                 
            (
                -- Selecting job_id from job_history table
                SELECT job_id 
                -- Filtering job_history where department_id is between 50 and 100
                FROM job_history                  
                WHERE department_id BETWEEN 50 AND 100
            )
        -- Grouping the results by job_id from the subquery
        GROUP BY job_id
    );

The above code is executed in Oracle 11g Express Edition.

Explanation:

  • This SQL query calculates the average salary for each job_id from the "employees" table.

  • It groups the results by job_id.

  • The HAVING clause filters the grouped results based on a condition.

  • The condition compares the average salary for each job_id with the maximum average of the minimum salary for jobs within specific department_ids.

  • The subquery selects the maximum of the average of min_salary from the "jobs" table, filtering it based on the job_ids present in the subquery result.

  • The subquery within the WHERE clause selects job_ids from the "job_history" table where the department_id falls between 50 and 100.

  • The main query then selects job_ids and their corresponding average salaries where the average salary is less than the maximum average of the minimum salary for jobs within specific department_ids.

or


-- Selecting job_id and the average salary from the employees table
SELECT job_id, AVG(salary) 
-- Grouping the results by job_id
FROM employees   
GROUP BY job_id   
-- Filtering the grouped results based on a condition
HAVING AVG(salary) <           
    (
        -- Selecting the maximum of the myavg column from the subquery
        SELECT MAX(myavg) 
        -- Selecting job_id and average minimum salary as myavg from the jobs table
        FROM (SELECT job_id, AVG(min_salary) as myavg
              -- From the jobs table
              FROM jobs             
              -- Filtering jobs where the job_id is in the subquery result
              WHERE job_id IN                 
                  (
                      -- Selecting job_id from job_history table
                      SELECT job_id 
                      -- Filtering job_history where department_id is between 50 and 100
                      FROM job_history                  
                      WHERE department_id BETWEEN 50 AND 100
                  )
              -- Grouping the results by job_id
              GROUP BY job_id) ss
    );

The above code is executed in PostgreSQL 9.3

Explanation:

  • This SQL query calculates the average salary for each job_id from the "employees" table.

  • It groups the results by job_id.

  • The HAVING clause filters the grouped results based on a condition.

  • The condition compares the average salary for each job_id with the maximum average of the minimum salary for jobs within specific department_ids.

  • The subquery selects the maximum value from the "myavg" column.

  • This subquery selects job_ids and their corresponding average minimum salaries, filtering it based on the job_ids present in the subquery result.

  • The subquery within the WHERE clause selects job_ids from the "job_history" table where the department_id falls between 50 and 100.

  • The main query then selects job_ids and their corresponding average salaries where the average salary is less than the maximum average of the minimum salary for jobs within specific department_ids.

Output

JOB_ID     AVG(SALARY)
---------- -----------
IT_PROG           5760
AC_ACCOUNT        8300
ST_MAN            7280
AD_ASST           4400
SH_CLERK          3215
FI_ACCOUNT        7920
PU_CLERK          2780
SA_REP            8350
MK_REP            6000
ST_CLERK          2785
HR_REP            6500

Let's break the example down into three parts and observes the results returned.

Atfirst the nested subquery as follows:

SQL Code:


-- Selecting job_id from the job_history table
SELECT job_id 
-- Filtering job_history records based on department_id
WHERE department_id      
-- Specifying the range for department_id filtering
BETWEEN 50 AND 100;

Explanation:

  • This SQL query retrieves job_ids from the "job_history" table.

  • It filters the records based on the department_id.

  • The BETWEEN operator is used to specify a range for department_id filtering, including values between 50 and 100.

  • The query returns job_ids associated with department_ids falling within the specified range.

This nested subquery retrieves the job_id(s) from job_history table which is within the department_id 50 and 100.

Here is the output.

Output:

JOB_ID
----------
ST_CLERK
ST_CLERK
IT_PROG
SA_REP
SA_MAN
AD_ASST
AC_ACCOUNT

Here is the visual representation of how the above output comes.

Sql subqueries with in

Now the subquery that receives output from the nested subquery stated above.


SELECT MAX(AVG(min_salary))
FROM jobs WHERE job_id 
IN(.....output from the nested subquery......)
GROUP BY job_id

The subquery internally works as follows:

SQL Code:


-- Selecting the maximum of the average of min_salary from the jobs table
SELECT MAX(AVG(min_salary))
-- From the jobs table
FROM jobs 
-- Filtering jobs based on job_id
WHERE job_id 
-- Specifying the list of job_ids for filtering
IN (
    'ST_CLERK', 'ST_CLERK', 'IT_PROG', 'SA_REP', 'SA_MAN', 'AD_ASST', 'AC_ACCOUNT'
)
-- Grouping the results by job_id
GROUP BY job_id;

Explanation:

  • This SQL query calculates the average minimum salary for each job_id from the "jobs" table.

  • It first filters the jobs based on specific job_ids listed.

  • The MAX() function is then applied to get the maximum value of the average minimum salary across all the job_ids.

  • The GROUP BY clause groups the results by job_id, allowing the calculation of the average minimum salary for each job_id separately.

  • The query returns the maximum value among these averages.

Here is the output:

Output:

MAX(AVG(MIN_SALARY))
--------------------
               10000

Here is the Visual representation of how the above output returns.

Sql subqueries with in

Now the outer query that receives output from the subquery and which also receives the output from the nested subquery stated above.


SELECT job_id,AVG(salary) 
FROM employees   
GROUP BY job_id   
HAVING AVG(salary)<   
(.....output from the subquery(         
output from the nested subquery)......)

The outer query internally works as follows:

SQL Code:


-- Selecting job_id and the average salary from the employees table
SELECT job_id, AVG(salary) 
-- Grouping the results by job_id
FROM employees   
GROUP BY job_id   
-- Filtering the grouped results based on a condition
HAVING AVG(salary) < 10000;

Explanation:

  • This SQL query calculates the average salary for each job_id from the "employees" table.

  • It groups the results by job_id.

  • The HAVING clause filters the grouped results based on a condition.

  • The condition specifies that only those records should be selected where the average salary for each job_id is less than 10000.

  • The query returns job_ids and their corresponding average salaries where the average salary is less than 10000.

Output:

JOB_ID     AVG(SALARY)
---------- -----------
IT_PROG           5760
AC_ACCOUNT        8300
ST_MAN            7280
AD_ASST           4400
SH_CLERK          3215
FI_ACCOUNT        7920
PU_CLERK          2780
SA_REP            8350
MK_REP            6000
ST_CLERK          2785
HR_REP            6500

Example -2 : Nested subqueries

Here is an another nested subquery example.

Sample table: orders
   ORD_NUM ORD_AMOUNT ADVANCE_AMOUNT ORD_DATE  CUST_CODE       AGENT_CODE      ORD_DESCRIPTION
---------- ---------- -------------- --------- --------------- --------------- -----------------
    200114       3500           2000 15-AUG-08 C00002          A008
    200122       2500            400 16-SEP-08 C00003          A004
    200118        500            100 20-JUL-08 C00023          A006
    200119       4000            700 16-SEP-08 C00007          A010
    200121       1500            600 23-SEP-08 C00008          A004
    200130       2500            400 30-JUL-08 C00025          A011
    200134       4200           1800 25-SEP-08 C00004          A005
    200108       4000            600 15-FEB-08 C00008          A004
    200103       1500            700 15-MAY-08 C00021          A005
    200105       2500            500 18-JUL-08 C00025          A011
    200109       3500            800 30-JUL-08 C00011          A010
    200101       3000           1000 15-JUL-08 C00001          A008
    200111       1000            300 10-JUL-08 C00020          A008
    200104       1500            500 13-MAR-08 C00006          A004
    200106       2500            700 20-APR-08 C00005          A002
    200125       2000            600 10-OCT-08 C00018          A005
    200117        800            200 20-OCT-08 C00014          A001
    200123        500            100 16-SEP-08 C00022          A002
    200120        500            100 20-JUL-08 C00009          A002
    200116        500            100 13-JUL-08 C00010          A009
    200124        500            100 20-JUN-08 C00017          A007
    200126        500            100 24-JUN-08 C00022          A002
    200129       2500            500 20-JUL-08 C00024          A006
    200127       2500            400 20-JUL-08 C00015          A003
    200128       3500           1500 20-JUL-08 C00009          A002
    200135       2000            800 16-SEP-08 C00007          A010
    200131        900            150 26-AUG-08 C00012          A012
    200133       1200            400 29-JUN-08 C00009          A002
    200100       1000            600 08-JAN-08 C00015          A003
    200110       3000            500 15-APR-08 C00019          A010
    200107       4500            900 30-AUG-08 C00007          A010
    200112       2000            400 30-MAY-08 C00016          A007
    200113       4000            600 10-JUN-08 C00022          A002
    200102       2000            300 25-MAY-08 C00012          A012
Sample table : customer
+-----------+-------------+-------------+--------------+--------------+-------+-------------+-------------+-------------+---------------+--------------+------------+  
|CUST_CODE  | CUST_NAME   | CUST_CITY   | WORKING_AREA | CUST_COUNTRY | GRADE | OPENING_AMT | RECEIVE_AMT | PAYMENT_AMT |OUTSTANDING_AMT| PHONE_NO     | AGENT_CODE |
+-----------+-------------+-------------+--------------+--------------+-------+-------------+-------------+-------------+---------------+--------------+------------+
| C00013    | Holmes      | London      | London       | UK           |     2 |     6000.00 |     5000.00 |     7000.00 |       4000.00 | BBBBBBB      | A003       |
| C00001    | Micheal     | New York    | New York     | USA          |     2 |     3000.00 |     5000.00 |     2000.00 |       6000.00 | CCCCCCC      | A008       |
| C00020    | Albert      | New York    | New York     | USA          |     3 |     5000.00 |     7000.00 |     6000.00 |       6000.00 | BBBBSBB      | A008       |
| C00025    | Ravindran   | Bangalore   | Bangalore    | India        |     2 |     5000.00 |     7000.00 |     4000.00 |       8000.00 | AVAVAVA      | A011       |
| C00024    | Cook        | London      | London       | UK           |     2 |     4000.00 |     9000.00 |     7000.00 |       6000.00 | FSDDSDF      | A006       |
| C00015    | Stuart      | London      | London       | UK           |     1 |     6000.00 |     8000.00 |     3000.00 |      11000.00 | GFSGERS      | A003       |
| C00002    | Bolt        | New York    | New York     | USA          |     3 |     5000.00 |     7000.00 |     9000.00 |       3000.00 | DDNRDRH      | A008       |
| C00018    | Fleming     | Brisban     | Brisban      | Australia    |     2 |     7000.00 |     7000.00 |     9000.00 |       5000.00 | NHBGVFC      | A005       |
| C00021    | Jacks       | Brisban     | Brisban      | Australia    |     1 |     7000.00 |     7000.00 |     7000.00 |       7000.00 | WERTGDF      | A005       |
| C00019    | Yearannaidu | Chennai     | Chennai      | India        |     1 |     8000.00 |     7000.00 |     7000.00 |       8000.00 | ZZZZBFV      | A010       |
| C00005    | Sasikant    | Mumbai      | Mumbai       | India        |     1 |     7000.00 |    11000.00 |     7000.00 |      11000.00 | 147-25896312 | A002       |
| C00007    | Ramanathan  | Chennai     | Chennai      | India        |     1 |     7000.00 |    11000.00 |     9000.00 |       9000.00 | GHRDWSD      | A010       |
| C00022    | Avinash     | Mumbai      | Mumbai       | India        |     2 |     7000.00 |    11000.00 |     9000.00 |       9000.00 | 113-12345678 | A002       |
| C00004    | Winston     | Brisban     | Brisban      | Australia    |     1 |     5000.00 |     8000.00 |     7000.00 |       6000.00 | AAAAAAA      | A005       |
| C00023    | Karl        | London      | London       | UK           |     0 |     4000.00 |     6000.00 |     7000.00 |       3000.00 | AAAABAA      | A006       |
| C00006    | Shilton     | Torento     | Torento      | Canada       |     1 |    10000.00 |     7000.00 |     6000.00 |      11000.00 | DDDDDDD      | A004       |
| C00010    | Charles     | Hampshair   | Hampshair    | UK           |     3 |     6000.00 |     4000.00 |     5000.00 |       5000.00 | MMMMMMM      | A009       |
| C00017    | Srinivas    | Bangalore   | Bangalore    | India        |     2 |     8000.00 |     4000.00 |     3000.00 |       9000.00 | AAAAAAB      | A007       |
| C00012    | Steven      | San Jose    | San Jose     | USA          |     1 |     5000.00 |     7000.00 |     9000.00 |       3000.00 | KRFYGJK      | A012       |
| C00008    | Karolina    | Torento     | Torento      | Canada       |     1 |     7000.00 |     7000.00 |     9000.00 |       5000.00 | HJKORED      | A004       |
| C00003    | Martin      | Torento     | Torento      | Canada       |     2 |     8000.00 |     7000.00 |     7000.00 |       8000.00 | MJYURFD      | A004       |
| C00009    | Ramesh      | Mumbai      | Mumbai       | India        |     3 |     8000.00 |     7000.00 |     3000.00 |      12000.00 | Phone No     | A002       |
| C00014    | Rangarappa  | Bangalore   | Bangalore    | India        |     2 |     8000.00 |    11000.00 |     7000.00 |      12000.00 | AAAATGF      | A001       |
| C00016    | Venkatpati  | Bangalore   | Bangalore    | India        |     2 |     8000.00 |    11000.00 |     7000.00 |      12000.00 | JRTVFDD      | A007       |
| C00011    | Sundariya   | Chennai     | Chennai      | India        |     3 |     7000.00 |    11000.00 |     7000.00 |      11000.00 | PPHGRTS      | A010       |
+-----------+-------------+-------------+--------------+--------------+-------+-------------+-------------+-------------+---------------+--------------+------------+
Sample table : agents
 
+------------+----------------------+--------------------+------------+-----------------+---------+
| AGENT_CODE | AGENT_NAME           | WORKING_AREA       | COMMISSION | PHONE_NO        | COUNTRY |
+------------+----------------------+--------------------+------------+-----------------+---------+
| A007       | Ramasundar           | Bangalore          |       0.15 | 077-25814763    |         |
| A003       | Alex                 | London             |       0.13 | 075-12458969    |         |
| A008       | Alford               | New York           |       0.12 | 044-25874365    |         |
| A011       | Ravi Kumar           | Bangalore          |       0.15 | 077-45625874    |         |
| A010       | Santakumar           | Chennai            |       0.14 | 007-22388644    |         |
| A012       | Lucida               | San Jose           |       0.12 | 044-52981425    |         |
| A005       | Anderson             | Brisban            |       0.13 | 045-21447739    |         |
| A001       | Subbarao             | Bangalore          |       0.14 | 077-12346674    |         |
| A002       | Mukesh               | Mumbai             |       0.11 | 029-12358964    |         |
| A006       | McDen                | London             |       0.15 | 078-22255588    |         |
| A004       | Ivan                 | Torento            |       0.15 | 008-22544166    |         |
| A009       | Benjamin             | Hampshair          |       0.11 | 008-22536178    |         |
+------------+----------------------+--------------------+------------+-----------------+---------+

SQL Code:


-- Selecting specific columns from the orders table
SELECT ord_num, ord_date, ord_amount, advance_amount
-- Filtering orders based on multiple conditions
FROM orders 
-- Specifying conditions for filtering
WHERE ord_amount > 2000 
-- Filtering based on order amount greater than 2000
AND ord_date < '01-SEP-08' 
-- Filtering based on order date before 01-SEP-08
AND ADVANCE_AMOUNT <         
    -- Comparing advance_amount with values from a subquery result
    ANY(
        SELECT OUTSTANDING_AMT		
        -- Selecting outstanding amounts from the CUSTOMER table
        FROM CUSTOMER	
        -- Specifying conditions for filtering customers
        WHERE GRADE = 3 
        -- Filtering based on customer grade being 3
        AND CUST_COUNTRY <> 'India'	
        -- Filtering based on customer country not being India
        AND opening_amt < 7000 
        -- Filtering based on opening amount less than 7000
        AND EXISTS		        
            -- Checking for existence of records in a subquery
            (
                SELECT * 				 
                -- Selecting all columns from the agents table
                FROM agents				  
                -- Specifying conditions for filtering agents
                WHERE commission < .12
                -- Filtering based on commission less than 0.12
            )
    );

Explanation:

  • This SQL query retrieves specific columns from the "orders" table.

  • It filters the orders based on multiple conditions:

    • Orders with ord_amount greater than 2000.

    • Orders with ord_date before 01-SEP-08.

    • Orders with advance_amount less than any of the values retrieved from a subquery.

  • The subquery retrieves outstanding amounts from the CUSTOMER table based on several conditions.

  • The conditions include GRADE being 3, CUST_COUNTRY not being 'India', and opening_amt less than 7000.

  • The subquery also includes an EXISTS clause to check for the existence of records in another subquery.

  • This inner subquery selects all columns from the agents table and filters them based on the commission being less than 0.12.

  • Overall, the query selects orders that meet the specified conditions on ord_amount, ord_date, advance_amount, and the results of the subquery.

Output:

   ORD_NUM ORD_DATE  ORD_AMOUNT ADVANCE_AMOUNT
---------- --------- ---------- --------------
    200130 30-JUL-08       2500            400
    200127 20-JUL-08       2500            400
    200110 15-APR-08       3000            500
    200105 18-JUL-08       2500            500
    200129 20-JUL-08       2500            500
    200108 15-FEB-08       4000            600
    200113 10-JUN-08       4000            600
    200106 20-APR-08       2500            700
    200109 30-JUL-08       3500            800
    200107 30-AUG-08       4500            900
    200101 15-JUL-08       3000           1000
    200128 20-JUL-08       3500           1500
    200114 15-AUG-08       3500           2000

Let's break the code and analyze what's going on in inner query. Here is the first code of inner query with output :

SQL Code:

SELECT *
FROM agents
WHERE commission<.12;

Output:

AGENT_CODE AGENT_NAME      WORKING_AREA      COMMISSION PHONE_NO        COUNTRY
---------- --------------- ----------------- ---------- --------------- ---------
A009       Benjamin        Hampshair                .11 008-22536178
A002       Mukesh          Mumbai                   .11 029-12358964

Here is the second code of inner query (including first one) with output :

SQL Code:


-- Selecting outstanding amounts from the CUSTOMER table
SELECT OUTSTANDING_AMT
-- Filtering customers based on multiple conditions
FROM CUSTOMER
-- Specifying conditions for filtering customers
WHERE GRADE = 3 
-- Filtering based on customer grade being 3
AND CUST_COUNTRY <> 'India' 
-- Filtering based on customer country not being India
AND opening_amt < 7000 
-- Filtering based on opening amount less than 7000
AND EXISTS(
    -- Checking for existence of records in a subquery
    SELECT * 
    -- Selecting all columns from the agents table
    FROM agents
    -- Specifying conditions for filtering agents
    WHERE commission < .12
    -- Filtering based on commission less than 0.12
);

Explanation:

  • This SQL query retrieves outstanding amounts from the CUSTOMER table.

  • It filters the customers based on multiple conditions:

    • Customers with GRADE equal to 3.

    • Customers with CUST_COUNTRY not equal to 'India'.

    • Customers with opening_amt less than 7000.

  • The query also includes an EXISTS clause to check for the existence of records in a subquery.

  • The subquery selects all columns from the agents table and filters them based on the commission being less than 0.12.

  • Overall, the query selects outstanding amounts from customers who meet the specified conditions on GRADE, CUST_COUNTRY, opening_amt, and the existence of agents with a commission less than 0.12.

Output:

OUTSTANDING_AMT
---------------
           6000
           3000
           5000

See our Model Database

Check out our 1000+ SQL Exercises with solution and explanation to improve your skills.

Previous: Correlated subqueries using aliases
Next: Union



Follow us on Facebook and Twitter for latest update.