TestingDocs.com
Software Testing website
  • Automation
    • Selenium
    • JBehave Framework
  • Tutorials
    • MySQL Tutorials
    • Testlink
    • Maven
    • Git
  • IDEs
    • IntelliJ IDEA
    • Eclipse
  • Flowcharts
    • Flowgorithm
    • Raptor
  • About

Database

SQL SubQuery

Overview

Subquery also called as inner query is used to return a value to the outer or the main query. There are two types of sub queries.

Nested Sub-query

Nested sub-query is executed first and its results are inserted in the WHERE clause of the outer main query. Sub queries can be single row or multiple row depending on the number of rows the query returns to the main query.

Let’s consider the problem on emp table.

Who has salary greater than Clark’s salary?

SQL> SELECT sal FROM emp WHERE ename='CLARK';

 SAL
----------
 2450

Now, we will write the main SQL query that uses the above one to find the employees who earn more than Clark.

SQL> SELECT ename,sal FROM emp where sal > (SELECT sal FROM emp where ename='CLARK');

ENAME SAL
---------- ----------
JONES 2975
BLAKE 2850
SCOTT 3000
KING 5000
FORD 3000

SQL Sub Query

 

Correlated sub-query

Correlated subquery is one that is executed after the outer main query is executed. The correlated subquery depends on some variable that it receives from the main query.

Example:

Find list of employees whose salary is more than their department’s average salary?

SQL> SELECT outer.deptno, outer.ename, outer.sal
 2 FROM emp outer
 3 WHERE sal >
 4 (SELECT AVG(inner.sal) FROM emp inner
 5 WHERE inner.deptno = outer.deptno)
 6 ORDER BY outer.deptno;

 DEPTNO ENAME SAL
---------- ---------- ----------
 10 KING 5000
 20 JONES 2975
 20 SCOTT 3000
 20 FORD 3000
 30 ALLEN 1600
 30 BLAKE 2850

6 rows selected.

SQL> SELECT deptno, AVG(sal) FROM emp
 2 GROUP BY deptno
 3 ORDER BY deptno;

 DEPTNO AVG(SAL)
---------- ----------
 10 2916.66667
 20 2175
 30 1566.66667

SQL>

Corelated Subquery

Related Posts

SQLite

Database /

SQLite database introduction

Database /

Popular NoSQL Databases

world database ERD

Database /

Entity-Relationship Model

Database /

Database Design Process

SQL_statements

Database /

SQL Questions for Beginners

‹ SQL Questions for Beginners› Database Design Process

Recent Posts

  • Update draw.io on Windows
  • Install RAPTOR Avalonia on CentOS
  • Download RAPTOR Avalonia Edition on Windows
  • npm doctor command
  • Build & Run CLion Project
  • Create New CLion C Project on Windows
  • Configure CLion Toolchains on Windows
  • Launch CLion IDE on Windows
  • Activate CLion IDE
  • CLion IDE for C/C++ Development

Back to Top

Links

  • Contact
  • Privacy Policy
  • Cookie Policy

www.TestingDocs.com