• TestingDocs
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 /

Types of NoSQL databases

Database /

Popular NoSQL Databases

Database /

Database Characteristics

3-Tier Architecture

Database /

3-Tier Architecture

‹ SQL Questions for Beginners› Database Design Process

Recent Posts

  • How to secure your SQL Database: Tips and Tricks
  • Shaping the Future of Development: Exploring Key Trends in Software Engineering
  • Improving Java Performance with Multithreading
  • Difference between PHP and JavaScript?
  • Bing Conversation Styles
  • ChatGPT Introduction
  • Open Source AI Frameworks
  • Artificial Intelligence Tools
  • Top AI Music Applications
  • Top AI Website Design Tools

Back to Top

Links

  • Contact
  • Privacy Policy
  • Cookie Policy

www.TestingDocs.com