SQLforGeeks
  • Home
  • SQL
  • SQL Tutorial
  • SQL Syntax
  • Our Services
Contact
  1. SQL
  2. SQL Subquery

Text copied!

« Previous
Next »

SQL Subquery

June 28, 2023, 7:54 p.m. under SQL

  • Hi! You should check Store Procedure vs. Function post first.

    In SQL, When a query is enclosed inside another query is called as 'Subquery' or 'Inner query'. The query that includes another query inside it, is referred to as 'Main query' or 'Outer query'.

    'Outer query' uses the result of the 'Subquery' to perform data filtering or operations.

    Here's the general syntax :
    SQL query 
                      ( SQL query );
            

    • Inner query is always enclosed in 'parenthesis ( )' to indicate it's boundaries and separation from outer query.

    In SQL, 'Subqueries' can be used in SELECT, FROM, WHERE etc. clauses that enables user to merge and manipulate data with considerable power.

    Here's an example of Subquery in SELECT clause :

    Using subquery in 'SELECT' clause is known as 'scalar subquery'. It retrieves a single value from a subquery and include it as a column in the result-set of the outer query.

    Here's the syntax :

    SELECT column1, ( SELECT column2 FROM table2 WHERE condition ) AS subquery
    FROM table1;
            

    Suppose we have two tables : [i] Employees table [ii] Employees_2 table

    SQL Subquery

    Run below SQL statement :

    SELECT Emp.Employee_Name AS [Name], ( SELECT SUM(Salary) FROM [Employees_2] ) AS Subquery
    FROM [Employees] Emp;
            
    SQL Subquery

    The subquery "( SELECT SUM(Salary) FROM [Employees_2] )" retrieves the sum of Salary from [Employees_2] table. The result of the subquery is then included as a column named "subquery" in the result-set of the outer query.

    Here's an example of Subquery in FROM clause :

    Using subquery in 'FROM' clause is known as 'derived table' or 'inline view'. It is used to create a temp table and then utilize in the outer query.

    Here's the syntax :

    SELECT column3
    FROM ( SELECT column1, column2, column3 FROM table1 WHERE condition ) AS table_alias;
            

    Run below SQL statement :

    SELECT Salary
    FROM ( SELECT Employee_Id, Employee_Name, Salary FROM [Employees] WHERE Gender = 'Male' ) AS xyz;
            
    SQL Subquery

    The subquery "( SELECT Employee_Id, Employee_Name, Salary FROM [Employees] WHERE Gender = 'Male' )" retrieves specific columns from [Employees] table. This subquery result is treated as temp table and outer query retrieves only Salary column from this temp table.

    Here's an example of Subquery in WHERE clause, It is also known as 'Nested query' :

    Using subquery in 'WHERE' clause is useful to filter the result-set based on the result of the another query. Using a query inside another query is known as a subquery or a nested query.

    Here's the syntax :

    SELECT column1, column2, column3
    FROM table1
    WHERE column1 IN ( SELECT column1 FROM table2 WHERE condition );
            

    Run below SQL statement :

    SELECT Employee_Id, Employee_Name, Salary
    FROM [Employees]
    WHERE Employee_Id IN ( SELECT Employee_Id FROM [Employees_2] WHERE Gender = 'Male' );
            
    SQL Subquery

    The subquery "( SELECT Employee_Id FROM [Employees_2] WHERE Gender = 'Male' )" retrieves all the Employee_Id values from [Employees_2] table. The outer query retrieves all specified column data from [Employees] table where Employee_Id matches with the Employee_Id of subquery result.

    Frequently Asked Questions :

    What is subquery in SQL?

    A subquery in SQL is a query nested within another query.

    Why are subqueries used?

    Subqueries are used to retrieve data based on criteria derived from another query's result.

    Is subquery faster than two queries?

    Subquery performance depends on various factors; sometimes it can be faster, but not always.

    How do I write a subquery for two tables?

    To write a subquery for two tables, you typically use a WHERE clause with a comparison between columns from the main table and the subquery's result.
    Thank You! You should check SQL Aliases post next.
    « Previous
    Next »
    RELATED :

    What is SQL

    What is T-SQL

    Difference between DBMS and Data Warehouse

    Download SQL Server

    Install SQL Server

    Download SQL Server Management Studio SSMS

    SQL Server Management Studio

    SQL Database

    Download database

    Restore database

    Backup database

    Attach database

    Detach database

    Create database

    Delete database

    Rename database

    Select database

    Database offline

    Database online

    SQL Commands

    SQL Tables

    Create table

    Truncate table

    Delete table

    Rename table

    Select table

    Alter table

    SQL Data Types

    SQL Comments

    SQL Constraints

    SQL Joins

    SQL inner join

    SQL left join

    SQL right join

    SQL full join

    SQL cross join

    SQL self join

    INSERT INTO SELECT statement

    INSERT INTO statement

    SQL Clauses

    SELECT clause

    FROM clause

    WHERE clause

    GROUP BY clause

    HAVING clause

    ORDER BY clause

    JOIN clause

    UNION clause

    UNION ALL clause

    TOP clause

    DISTINCT clause

    SQL Operators

    SQL Arithmetic operators

    SQL Comparison operators

    SQL Logical operators

    UNION operator

    UNION ALL operator

    INTERSECT operator

    EXCEPT operator

    LIKE operator

    NOT LIKE operator

    IN operator

    NOT IN operator

    IS NULL operator

    IS NOT NULL operator

    EXISTS operator

    NOT EXISTS operator

    BETWEEN operator

    NOT BETWEEN operator

    SQL Functions

    SQL Built-In functions

    CHARINDEX function

    DATEADD function

    CONCAT function

    LEN function

    REPLACE function

    SUBSTRING function

    CASE statement

    GETDATE function

    DATEPART function

    DATEDIFF function

    CAST function

    TRY_CAST function

    CONVERT function

    TRY_CONVERT function

    ISNULL function

    NULLIF function

    COALESCE function

    SQL Window functions

    ROW_NUMBER function

    RANK function

    DENSE_RANK function

    IIF function

    CHOOSE function

    SQL Store Procedure

    Store Procedure vs. Function

    SQL Aliases

    Temp table

    SQL Error Handling

    SQL Variables

    SQL Views

    SQL Merge

    SQL CTE

    SQL WITH TIES

    Define Transaction in DBMS

    ACID properties in DBMS

    Types of Triggers in DBMS


    • Have Some Questions?
    logo

    Elevate your data experience with SQL excellence

    Quick Links
    •  Home
    •  SQL Tutorial
    •  SQL Syntax
    •  Our Services
    Our Services
    • Web Development
    • BI Development
    • Data Warehousing
    • Data Integration ETL


    Follow Us

    GST Registered: XXAXXXXXXXZX
    Mumbai, Maharashtra, India support@sqlforgeeks.com

    © 2025 Copyright™ | All Rights Reserved | Privacy Policy