Sql Subqueries

Sql Subqueries

A subquery is a SQL query or statement or expression within a query. Subqueries are called nested queries or inner queires. It must be enclosed with parenthesis.

Subqueries are provide data or result to the enclosing query. It can return individual values or a list of rows to outer query or main query.

It can be nested into any valid sql statement, expression, or inside another subquery.

Sql subquery statement using subquery alias, subquery in where clause, subquery types, subquery return multiple columns, comma separated list, subquery count group by, subquery condition from main query, subquery efficiency and execution order, subquery exists vs in, subquery join with outer query, join two tables, multiple subquery, Nested Subquery, Delete Duplicate.

Sql Subquery Syntax

There is no general syntax; subqueries are normal sql queries placed inside parenthesis. Subqueries can be used in many ways and at many locations inside a query or expression:

A subquery usually take one of these below formats:

  1. WHERE expression [NOT] IN (subquery)
  2. WHERE expression comparison_operator [ANY | ALL] (subquery)
  3. WHERE [NOT] EXISTS (subquery)

Sample Database Table - Employee

ID EmpName Designation Dept JoinYear Salary
1 Geetha SQL Database Oracle 2013 10820
2 Bala Murugan Cloud Database Oracle 2015 11660
3 Hanumanthan Cloud Database SQL Server 2014 20270.8
4 Ranjani Mai Sql Head PHP 2013 8510.8
5 Padmavathi SQL Mining SQL Server 2013 3470.4
6 Vinoth Kumar Database Designer SQL Server 2014 14600

SQL Subquery With IN Operator

The following SQL statement will display records from employee table which is matched in the IN list.

SELECT * FROM Employee 
WHERE Dept IN (SELECT Dept FROM Employee WHERE Salary < 10000)

In the above query, "SELECT Dept FROM Employee WHERE Salary < 10000" is a subquery and it return list of values to outer query.

The sub-query returns "PHP" and "Sql Server" for which employee "Salary" is less than "10000".

The result of above query is:

ID EmpName Designation Dept JoinYear Salary
3 Hanumanthan Cloud Database SQL Server 2014 20270.8
4 Ranjani Mai Sql Head PHP 2013 8510.8
5 Padmavathi SQL Mining SQL Server 2013 3470.4
6 Vinoth Kumar Database Designer SQL Server 2014 14600

Sql server subquery using join performance, join multiple columns, subquery join same table, sql subquery multiple tables example, subquery multiple conditions, more than one value, subquery in select return multiple values, subquery with aggregate function, multiple columns, Subquery Not Exists, Subquery Not In, Pass Value, Update Multiple Rows, Subquery with Alias Name.

sql multiple subquery

Only one field was compared in the WHERE clause utilising logical operators or the HAVING clause of the SELECT statement to the outer SQL statement in single-row subqueries and multiple-row subqueries. To deal with a subquery that returns numerous rows, utilise the IN, ANY, or ALL operators in the outer query.

You can use multiple-column subqueries to merge multiple WHERE conditions into a single WHERE clause.

A correlated subquery is executed once for each candidate row in the containing query's intermediate result set, unlike non-correlated subqueries, which are processed exactly once before the containing statement is executed.


The following statement illustrates the syntax of a correlated subquery:

SELECT column1,column2,..
FROM table 1 outer
WHERE column1 operator( SELECT column1 from table 2 WHERE  column2=outer.column4)

The value of column4 from the outer table will be passed to the inner query and compared to column2 from table 2. As a result, column1 will be obtained from table 2 and compared to column1 of the outer table, depending on the operator. The row will be passed if the expression was true; else, it will not show in the result.

Example 1: In the outer query 'agent_code' of 'orders' table must be in the list within IN operator in inner query :

in inner query : 'working_area' of 'agents' table must be 'Bangalore',

Here is the complete SQL statement:

SELECT ord_num,ord_amount,ord_date,
cust_code, agent_code
FROM orders
WHERE agent_code IN(
SELECT agent_code FROM agents
WHERE working_area='Bangalore');

Output :

------- ---------- --------- ---------- ----------
200130       2500   30-JUL-08   C00025     A011
200105       2500   18-JUL-08   C00025     A011
200117        800   20-OCT-08   C00014     A001
200124        500   20-JUN-08   C00017     A007
200112       2000   30-MAY-08   C00016     A007

Example 2: Using Multiple-Column Subqueries

Display the order number, product number, and quantity of any item whose product number and amount match an item's product number and quantity in ordid 365.

SELECT  ordid, prodid, qty
FROM           item
WHERE        (prodid,   qty)    IN

(SELECT prodid,   qty
FROM        item
WHERE     ordid =   365)
AND  ordid   =   365 ;


365		    84		22

Example 3: Let's try to find all the employees who earn more than the average salary in their department:

SELECT last_name, salary, department_id
FROM employee outer
WHERE salary >
(SELECT AVG(salary)
FROM employee
WHERE department_id = outer.department_id);

The value of department_id will be provided into the inner query for each row from the employee table (let's say the value of department_id for the first row is 30), and the inner query will try to discover the average wage for that particular department_id = 30. If the pay of that specific record is higher than the average salary of department_id = 30, the expression is true, and the record appears in the output.

SQL Nested Subquery

Main Article :- Sql difference between Subuery, Nested Subquery, and Corelated Subquery

Subqueries can be nested within subqueries. SQL allows you to stack queries within each other. A subquery is a SELECT statement that returns intermediate results and is nested within another SELECT statement. The innermost subquery is executed first, followed by the following level.

Example 1: A query is written inside another query in nested queries. The inner query's result is used to execute the outer query. To comprehend nested queries, we'll use the STUDENT, COURSE, and STUDENT_COURSE databases.


S1	    RAM	    DELHI		9455123451	18
S2	    RAMESH	GURGAON		9652431543	18
S3	    SUJIT	ROHTAK		9156253131	20
S4	    SURESH	DELHI		9156768971	18


C1	    DSA
C2	    Programming
C3	    DBMS


S1  	C1
S1  	C3
S2  	C1
S3  	C2
S4  	C2
S4  	C3

There are mainly two types of nested queries:

Independent Nested Inquiries: In independent nested queries, the innermost query executes first, followed by the outermost query. Inner queries are executed independently of outer queries, however the results of inner queries are used to execute outer queries. In writing independent nested queries, many operators such as IN, NOT IN, ANY, ALL, and so on are employed.

IN: We can use an independent nested query using the IN operator to discover S  ID who are enrolled in C NAME 'DSA' or 'DBMS'. C_ID for C_NAME 'DSA' or 'DBMS' can be found in the COURSE table, and these C_IDs can be used to locate S_IDs in the STUDENT COURSE TABLE.

STEP 1: Finding C_ID for C_NAME =’DSA’ or ‘DBMS’

Select C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME = ‘DBMS’

STEP 2: Using C_ID of step 1 for finding S_ID

Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME=’DBMS’);

The inner query returns a set with members C1 and C3, whereas the outer query returns all S IDs for which C ID equals any member of set (C1 and C3 in this case). As a result, S1, S2, and S4 will be returned.

Example 2: If we want to extract that unique job_id and their average salary from the employees table, whose unique job_id has a salary that is less 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 inside the department_id 50 and 100)), we can use the following SQL statement:

SELECT job_id,AVG(salary) 
SELECT job_id,AVG(salary) 
FROM employees   
GROUP BY job_id   
HAVING AVG(salary)<
(SELECT MAX(myavg) from (select job_id,AVG(min_salary) as myavg
FROM jobs             
WHERE job_id IN                 
(SELECT job_id FROM job_history                  
WHERE department_id                   
BETWEEN 50 AND 100)            
GROUP BY job_id) ss);


---------- -----------
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 3: You look at the Sales.SalesOrderDetail database from the inside out, using a LIKE expression to match the ProductNumber value. The SalesPersonIDs are obtained by connecting these entries to the Sales.SalesOrderHeader table. The SalesPersonID is then used to create a connection to the HumanResources.Employee table. Finally, you connect to the Person by using the ContactID. Table of contact.

USE AdventureWorks ;

SELECT DISTINCT c.LastName, c.FirstName 
FROM Person.Contact c JOIN HumanResources.Employee e
ON e.ContactID = c.ContactID WHERE EmployeeID IN 
(SELECT SalesPersonID 
FROM Sales.SalesOrderHeader
WHERE SalesOrderID IN 
(SELECT SalesOrderID 
FROM Sales.SalesOrderDetail
(SELECT ProductID 
FROM Production.Product p 
WHERE ProductNumber LIKE'FW%')));

This sample demonstrates a few of SQLServer's advantages. It is clear that the IN() parameter can be replaced by a SELECT query. You do it twice in this case, resulting in a nested subquery.

SQL Subqueries and Join

With a JOIN operation, you can use a subquery.

When you wish to extract aggregate data from a child/details table and display it alongside records from the parent/header table, you usually join a subquery. You might wish to get a count of child records, an average of a numeric column in child records, or the top or bottom row based on a date or numeric field, for example.

What are Joins?

A query that joins records from two or more tables is known as a join. When many tables exist in the FROM clause of a query, a join is done. Any column from any of these tables can be selected from the query's choose list. A Cartesian product is created if the join condition is missing or faulty. If any of these tables share a column name, you must qualify these columns using table or table alias names throughout the query to prevent confusion. At least one join condition appears in most join queries, either in the FROM or WHERE clauses.

Advantages Of Joins:

  • It is faster to execute join.
  • A join-based query will almost always be faster than a subquery in terms of retrieval time.
  • By utilizing joins, you can reduce the database's calculation load by performing one query instead of numerous searches. This means you can make greater use of the database's search, filter, and sort capabilities.

Disadvantages Of Joins:

The disadvantage of joins is that they are harder to interpret than subqueries.

More joins in a query imply the database server has to do more work, which means retrieving data takes longer.

Because there are so many distinct types of joins, it might be difficult to know which one to employ to get the desired outcome set.

When getting data from a normalized database, joins are unavoidable, but they must be executed appropriately, as incorrect joins can cause substantial performance reduction and inaccurate query results.

Note: The join keyword's left and right tables must both yield a common key that may be used for the join.

what is Subquery?

A subquery, also known as an inner query or nested query, is a query that is placed within the WHERE clause of a SQL query. A subquery is a SELECT statement that is nested within another SQL statement's clause. They can be particularly handy for selecting rows from a table based on data in the same or another table. A subquery is used to return data that will be utilized as a condition in the main query to further limit the data that may be obtained. WHERE clause, HAVING clause, and FROM clause are the SQL clauses where the subquery can be used.

Since no indexes may be used on a temporary table in memory, using subqueries in JOIN operations should typically be omitted if you can rewrite the query in a different manner.

Advantages Of Subquery:

  • Subqueries break down a complex question into separate portions, allowing it to be broken down into logical steps.
  • It's simple to understand, and code administration is simple.
  • You can use the results of another query in the outer query with subqueries.
  • Subqueries can sometimes take the role of sophisticated joins and unions.

Disadvantages of Subquery:

Because the optimizer for joins is more mature than for subqueries in MYSQL, rewriting a statement that uses a subquery as a join can often result in a more efficient execution.

Inside the same SQL statement, we cannot edit a table and select from the same table.

Example 1: Use subquery in SELECT statement with an aggregate function:

The subquery returns a temporary table in the example below, which is handled in memory by the database server. The alias for the temporary table from the subquery is used in the outer select statement to link to it.

We choose to know what the average unit pricing was for each product category that was sold, as well as what the average unit price we wish to sell for.

Table x returns the average unit price sold for each product category and is retrieved using a subquery in the FROM clause.

The average unit price we want to sell for each product category is returned by table y in the join clause.

Then table x is joined with table y for each category.

select y.CategoryID, 
    round(x.actual_unit_price, 2) as "Actual Avg Unit Price",
    round(y.planned_unit_price, 2) as "Would-Like Avg Unit Price"
    select avg(a.UnitPrice) as actual_unit_price, c.CategoryID
    from order_details as a
    inner join products as b on b.ProductID = a.ProductID
    inner join categories as c on b.CategoryID = c.CategoryID
    group by c.CategoryID
) as x
inner join 
    select a.CategoryID, b.CategoryName, avg(a.UnitPrice) as planned_unit_price
    from products as a
    inner join categories as b on b.CategoryID = a.CategoryID
    group by a.CategoryID
) as y on x.CategoryID = y.CategoryID

Example 2: This example employs aliases, which, in theory, make queries easier to interpret when several tables are involved. This is an example of a standard subquery join. We are obtaining all rows from the parent table Purchase Orders and only the first row for each parent record of the child table PurchaseOrderLineItems in this example.

SELECT po.Id, po.PODate, po.VendorName, po.Status, item.ItemNo, 
  item.Description, item.Cost, item.Price
FROM PurchaseOrders po
       SELECT l.PurchaseOrderId, l.ItemNo, l.Description, l.Cost, l.Price, Min(l.id) as Id 
       FROM PurchaseOrderLineItems l
       GROUP BY l.PurchaseOrderId, l.ItemNo, l.Description, l.Cost, l.Price
     ) AS item ON item.PurchaseOrderId = po.Id

SQL Subquery

A subquery is typically added to another SQL SELECT statement's WHERE Clause.

You can utilize comparison operators like >, <, and = to make your calculations. A multiple-row operator, such as IN, ANY, or ALL, can likewise be used as a comparison operator.

Subqueries allow you to integrate data from multiple tables into a single result. These are also known as nested inquiries. Subqueries, as the name suggests, include one or more queries, one inside the other.

Subqueries are extremely adaptable, which might make them difficult to comprehend. In most circumstances, utilize them whenever an expression or table specification can be used.

Important rules for Subqueries:

  • The WHERE clause, HAVING clause, and FROM clause are all possible ways to put the Subquery.
  • Only with expression operator, subqueries can be utilised with the SELECT, UPDATE, INSERT, and DELETE statements. It could be a comparison or equality operator like =, >, =, ==, or Like.
  • A Subquery is essentially a query inside another query in SQL. In other words, a Subquery is a query that is contained within the WHERE clause of another SQL query.
  • The subquery usually runs first, and the results are used to satisfy the query condition for the main or outer query.
  • The parenthesis must surround the subquery.
  • The comparison operator has subqueries on the right side.
  • In a Subquery, the ORDER BY command is not valid. The GROUPBY command can serve the same job as the ORDER BY command.
  • Single-row operators should be used with single-row Subqueries. When working with multiple-row Subqueries, you should use multiple-row operators.

The following tasks can be accomplished with a subquery in a SELECT, INSERT, DELETE, or UPDATE statement:

  • Match an expression to the query's result.
  • Determine whether the query's results include an expression.
  • Check to see if the query returns any results.


Subqueries do not have a standard syntax. However, as illustrated below, subqueries are most commonly utilized using the SELECT query:

SELECT column_name
FROM table_name
WHERE column_name expression operator 

Example 1: Sample Table:

Ram	    101	Chennai		9988775566
Raj	    102	Coimbatore	8877665544
Sasi	103	Madurai		7766553344
Ravi	104	Salem		8989898989
Sumathi	105	Kanchipuram	8989856868


Ravi	    104	    A
Sumathi	    105 	B
Raj	        102	    A

To display NAME, LOCATION, PHONE_NUMBER of the students from DATABASE table whose section is A


Example 2: List all suppliers with the number of products they offer.

SELECT CompanyName, 
       ProductCount = (SELECT COUNT(P.id)
                         FROM [Product] P
                        WHERE P.SupplierId = S.Id)
  FROM Supplier S

Example 3: Run the subquery to get the list of territories that had year to date sales less than 5,000,000:

SELECT TerritoryID
FROM   Sales.SalesTerritory
WHERE  SalesYTD < 5000000

Example 4: To write a query to identify all students who get better marks than that of the student who's StudentID is 'V002', but we do not know the marks of 'V002'.

To solve the problem, we require two queries. One query returns the marks (stored in Total_marks field) of 'V002' and a second query identifies the students who get better marks than the result of the first query.

FROM `marks`  
WHERE studentid = 'V002';

SQL Subquery Case

Use a subquery with a 'where' condition within a Case statement to bind to the parent query.

Example 1: Add subqueries inside case statement

SELECT dbo.tPerson.pNameLast, 
CASE WHEN tApplication.aDeptChair IS NOT NULL THEN CASE WHEN tApplication.aDeptChair <> 0 THEN
''subquery 1
  (SELECT pNameFirst + ' ' + pNameLast + CHAR(13) + CHAR(10)
          FROM tPerson AS Chair
          WHERE Chair.pID = 16 AND tApplication.aID = 10) +
''subquery 2
  (SELECT pNameFirst + ' ' + pNameLast
          FROM tPerson AS Chair
          WHERE Chair.pID = 16 AND tApplication.aID = 10) END END AS Dept_Chair_LName
     dbo.tApplication ON tApplication.aPersonID = tPerson.pID;

Example 2:

case when salary between 6 and 8 then '6-8'
  when salary in (9,10)       then '9-10'
  when exists (select null from avg_sal where avg_sal = salary)
  then 'EXISTS'
  when to_char(salary) like '2%' then 'Like2'
  when salary is null then 'Null'
  else 'ELSE Empno: '|| emp_no
   AS case_test
from emp;



Example 3: use SUBQUERY in the Case Statement

= 10 THEN 'GOOD '

AS Rank

Example 4:

Select T.idperson , CASE WHEN  T.type = 'C' THEN (SELECT name from Customers where C.idcustomer = T.idperson) 
 (SELECT name from Providers where idprovider = T.idperson)
 END Name 
from myTable T

SQL Subquery Count

The count rows of a subquery.


SELECT COUNT(*) FROM (subquery) AS some_name;

Example 1: The FROM keyword should be followed by the subquery. (Assigning a name to a subquery of this type (which is technically termed a derived table) is also required in MySQL, which is why the AS some_name follows it.) MySQL sees your script as two separate queries because of the way you've written it, which is why you're getting two sets of results.

SELECT DISTINCT ip_address FROM `ports` WHERE status IS TRUE

the complete query would look like this:

    SELECT DISTINCT ip_address FROM `ports` WHERE status IS TRUE
) AS derived;

Example 2:

select COUNT(select userid from users inner join credit on
      select userid  FROM users inner JOIN jobs
      ON users.userid=jobsuserid)

SQL Subquery Delete Duplicate

PostgreSQL supports several methods for removing duplicate records. Subqueries can also be utilised in the same way.

Use the following way to eliminate the duplicate name using a subquery.

Example 1: A subquery is used in the following statement to eliminate duplicate entries and keep the one with the lowest id.

   (SELECT id
   (SELECT id,
    ORDER BY  id ) AS row_num
    FROM basket ) t
WHERE t.row_num > 1 );

In this case, the duplicate rows were returned except for the first row in the duplicate group. The subquery's duplicate rows were eliminated by the outer DELETE command.

Example 2: Delete duplicate records using Sub Query:

DELETE FROM `tbl_users` WHERE `id` NOT IN 
(SELECT `id` FROM (SELECT MAX(id) AS id FROM `tbl_users` GROUP BY `name`) AS tbl);

Example 3:

              FROM  SQLPractice.[dbo].[CURRENCY]
            ) t
WHERE t.Flag > 1

SQL Subquery Distinct

The IN subquery's SELECT DISTINCT function has no effect. There is nothing. Because anything is in (1, 2, 3), the IN conducts an implicit SELECT DISTINCT (1, 1, 1, 2, 2, 3).

GROUP BY, COUNT(*), and HAVING are common approaches.

Example 1: You want to count how many times idProdotto appears in the table. The idProdotto values that only appear once are what you desire.

SELECT Location.LocationID, Location.Location
FROM Location
WHERE Location.LocationID IN 
  (SELECT DISTINCT TransactionLocation 
   FROM Transactions
   WHERE Transactions.TransactionActivity = [Enter Activity] 
   AND Transactions.TransactionDate Between [Enter the start date:] And [Enter the end date:]);

Example 2:

subquery using Distinct:

  , Name
 FROM Employee AS e
 WHERE 1 =
  FROM Job As j
  WHERE j.ID = e.ID)

SQL Subquery Exists

When the SQL EXISTS criterion is used with a subquery, it is deemed met if the subquery returns at least one row. In a SELECT, INSERT, UPDATE, or DELETE statement, it can be utilized.

EXISTS subquery returns TRUE, and NOT EXISTS subquery returns FALSE.

Examine the subquery that is correlated. It shows how the subquery uses data from the outer query and runs once for each row in the outer query. The subquery delivers the value TRUE to the outer query when a matched row is discovered.

It's important to note that the outer query only provides a record if the subquery returns TRUE.


WHERE EXISTS ( subquery );

Parameters or Arguments

subquery - The SELECT statement is used in the subquery. The EXISTS clause evaluates to true and the EXISTS condition is satisfied if the subquery returns at least one entry in its result set. The EXISTS clause will analyze to false if the subquery returns no results, and the EXISTS condition will not be satisfied.

Example 1:

The subquery receives a value for CustomerID from the outer query. The event occurs in the subquery's WHERE clause.

The subquery looks up ShipCountry of UK in the orders table using the CustomerID value provided in.

The CustomerID and CompanyName for this row in the Customers table are returned by the outer query.

The query engine then moves on to the next row in the Customers table, where Steps 1 through 4 are repeated for the following client.

It gives the query result once all customers in the Customers table have been reviewed.

To return a list of customers whose purchases were transported to the United Kingdom, this query utilizes the EXISTS keyword in the WHERE clause.

select CustomerID, CompanyName 
from customers as a
where exists
    select * from orders as b
    where a.CustomerID = b.CustomerID
    and ShipCountry = 'UK'

Example 2:


Traditionally, an EXISTS subquery starts with SELECT *, but it could begin with SELECT 5 or SELECT column1 or anything at all. MySQL ignores the SELECT list in such a subquery, so it makes no difference.

Example 3:

locate all records from the customers table having the same customer_id as at least one entry in the orders table. Enter the SELECT statement below:

FROM customers
   FROM orders
   WHERE customers.customer_id = orders.customer_id);

Example 4: For example, this query finds the names of all the publishers who publish business books:

select pub_name 
from publishers 
where exists 
   (select * 
    from titles 
    where pub_id = publishers.pub_id 
    and type = "business")

SQL Subquery for Same Table

Example 1: Here's a SQL Fiddle to show that the code above works. Although I used Oracle, you should be able to adapt it to any dataset:

SELECT item_num, sum(i.price) + sum(nvl(x.ingred_price,0))
  FROM invoices i
     (SELECT parent_item_id
             , sum(price) ingred_price
          FROM invoices
         WHERE parent_item_id IS NOT NULL
       GROUP BY parent_item_id) x
ON x.parent_item_id = i.item_id
WHERE i.parent_item_id IS NULL      
GROUP BY item_num

Assumption: You don't have more than one level in a parent child relationship. E.g. A can have a child B, but B won't have any other children.

Example 2: The normal behaviour is that the id corresponds to the closest table in scope in the subquery WHERE id =... That concludes t2. Only if t2 did not have an id field would it refer to my table in the external query.

However, because you used WHERE id IN, the WHERE id = t2.id - which is interpreted as WHERE t2.id = t2.id - is not actually required (subquery). It wouldn't work as intended if you had an EXISTS version.

As a result, the right approach to create the query is to prefix all column references:

FROM my_table AS t1
WHERE ... AND t1.id IN 
   (SELECT t2.id
   FROM my_table t2
   WHERE --- t1.id = t2.id AND  -- remove, we don't need this 
   ... );

SQL Subquery from Clause

Subqueries that appear as nested SELECT statements in the FROM clause of an outer SELECT statement are more typically placed in a WHERE clause. Because the outer query uses the subquery's outputs as a data source, these subqueries are also known as derived tables or table expressions.

Derived tables are the name given to such subqueries. When using a subquery in this method, you must additionally use an AS clause to name the subquery's result.

Because no indexes may be used on a temporary table in memory, utilising subqueries in the FROM clause should be avoided if you can rewrite the query in a different way. Also, because it can't be assessed every row of the outer query, a subquery in the FROM clause can't be correlated.

Example 1: Query is a more complicated example in which the outer query only chooses the first qualifying row of a derived table that is specified as a simple join on the customer and cust_calls tables by a subquery in the FROM clause.

   (SELECT c.customer_num, c.lname, c.company, 
    c.phone, u.call_dtime, u.call_descr
     FROM customer c, cust_calls u
     WHERE c.customer_num = u.customer_num
    ORDER BY u.call_dtime DESC);

Example 2: The alias x is assigned to the subquery so that it may be referenced in the outer select statement.

select x.ProductID, 
    select ProductID, max(UnitPrice) as max_unit_price
    from order_details
    group by ProductID
) as x
inner join products as y on x.ProductID = y.ProductID

Example 3:

SELECT Managers.Id, Employees.Salary
  FROM Employees
) AS Managers
JOIN Employees ON Managers.Id = Employees.Id

SQL Subquery Groupby

Example 1: Here's a GROUP BY clause that uses an IN-subquery:

FROM scott.emp
	WHEN deptno  IN (
	SELECT	deptno
	FROM	scott.dept

Example 2: GROUP and HAVING with sub query

SELECT ArticleID, SUM(Quantity) AS Total
   FROM ArticleOrders
   GROUP BY ArticleID
   HAVING ArticleID IN
   (SELECT ArticleID FROM AuthorArticle WHERE AuthID IN
    SELECT AuthID FROM AuthorArticle


| ArticleID | Total |
|     19264 |     1 |
|     19354 |     3 |

Example 3: use group by in a subquery

select w.userID,count(w.id) 
from (select id,max(bidAmount),userID from Bids group by id, userID) w 
group by w.userID

Example 4: you seem to be looking for is a LATERAL join, which as far as I can tell is not supported by MySQL. Something like:

SELECT P.id, B.barcode AS barcode_sample
FROM publisher P
    SELECT publisher_id, MAX(barcode) AS barcode
    FROM product x
    WHERE x.publisher_id = P.id
    GROUP BY publisher_id
) B
    ON P.id = B.publisher_id
WHERE P.name LIKE '%tes%'

It can be used if the DBMS supports LATERAL. Some optimizers will push the predicates inside the sub-query even without LATERAL, but I don't think MySQL's optimizer does.

SQL Subquery Insert

With INSERT statements, subqueries are possible.

The INSERT statement inserts data into another table using the data supplied by the subquery. Any of the character, date, or numeric functions can be used to change the selected data in the subquery.

Insert rows using the INSERT INTO statement, where rows are the results of a subquery consisting of SQL SELECT statements with the WHERE clause.


INSERT INTO table_name [ (column1 [, column2 ]) ]
   SELECT [ *|column1 [, column2 ]
   FROM table1 [, table2 ]

Example 1:

INSERT INTO premium_customers 
SELECT * FROM customers 
WHERE cust_id IN (SELECT DISTINCT cust_id FROM orders 
WHERE order_value > 5000);

Using the data received from subquery, the above statement will insert premium_customer records into a database called premium customers. Customers who have placed orders totaling more than $5,000 are considered premium customers.

Example 2: Consider the following scenario: we want to create invoices for all wine orders we got during the day. A section of our invoicing table is shown below:

Invoice_id	Date		Client_id	Amount	Description			    Order_id
1	    	2020-01-10	100 		$135	50 bottles of Catedral		1
2	    	2020-02-15	103	    	$5520	230 bottles of Santiago		2
3	     	2020-03-12	102		    $2890	85 bottles of West Side		3
4	    	2020-03-30	100	    	$4650	150 bottles of Oro Rosso	4
5   		2020-05-03	100		    $930	30 bottles of Oro Rosso		5

If we add an INSERT clause before the query, we may insert the query's result into the table wine, as seen in the example below:

INSERT INTO invoice (date, client_id, amount, wine_name, order_id)
SELECT  o.date,
        o.quantity * w.price as amount,
        o.quantity || ’ bottles of ‘ || o.wine_name,
FROM    order o
JOIN    wine w ON w.name = o.wine_name
WHERE   o.date = ‘2020-06-28’

Example 3: Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the following syntax.


Example 4: To insert records into 'agent1' table from 'agents' table with the following condition :

1. 'working_area' of 'agents' table must be 'London', the following SQL statement can be used:

SELECT * FROM  agents
WHERE working_area="London";

SQL Subquery Like

You can only have one response from a subquery using the LIKE operator. The IN operator allows it to match all of the subquery's values.

Example 1: If you're using LIKE, keep in mind that if you're utilising wildcards, you may need to adjust your strategy:

SELECT * FROM Contacts
join searchvalues on first_name like myvalues

Example 2: This appears to be what you're looking for; no Regex is required. It's basically a correlated subquery with the exception that the LIKE condition is used instead of the general equality condition:

FROM tablename AS b 
      ( SELECT * 
        FROM words AS w 
        WHERE b.name LIKE '%' || w.word || '%'
      ) ;

Example 3:

SELECT COUNT(*) num_owned, a.owner
  FROM dba_objects a
  WHERE a.owner NOT IN (SELECT b.owner FROM dba_objects b
  WHERE b.owner LIKE 'S%')
  GROUP BY a.owner;


       473 MDSYS
         3 TSMSYS
      1143 FLOWS_020100
      2769 PUBLIC
         8 OUTLN
       575 JAVA2S
       339 CTXSYS
        34 HR
        12 FLOWS_FILES
        46 DBSNMP
       668 XDB

SQL Subquery Max Function

Only a subquery included in a HAVING clause or a select list may contain an aggregate, and the column being aggregated must be an outside reference in SQL.

Replace the max sub-query with a Max Function that returns an Entity's MAX HID Value (the function uses the sub-query statement with DAO logic within VBA).

Example 1:

select e.ename, e.job, e.sal
   from   emp e
   where  e.sal > (select max(x.sal)
    from   emp x
    where  x.job = 'Designer');

Example 2: Reduce two sub-queries into single query:

TABLE1.COLUMN1 in ( 4420,4697 )
(SELECT max(COLUMN2) as Key

Example 3: The HOME sub-query which is part of main Query (the main query needs to return one row per entity as (EID, Home.Address, Mail.Address) :

Select *
From tbAddresses As tba1
Where tba1.aType = "Home"
  And tba1.HID = (Select MAX(tba2.HID) 
  From tbAddresses As tba2 
  Where tba1.EID = tba2.EID)

When the Where clauses for both Home and Mail (not shown) are replaced with the code below If the MAX sub-query, the main query works well.

Example 4: Actual table INFO maximum ID value The correct solution, based on the problem statement, is as follows, which does not result in an error:


SQL Subquery Multiple Columns

Only one column was matched in the WHERE clause or HAVING clause of the SELECT statement for single-row subqueries and multiple-row subqueries. You must build a compound WHERE clause using logical operators if you want to compare two or more columns. Duplicate WHERE criteria can be combined into a single WHERE clause with multiple-column subqueries.

Syntax :

SELECT column, column, ...
FROM table
WHERE (column, column, ...) IN
(SELECT column, column, ...
FROM table
WHERE condition);

Example 1: Mysql Subquery With Multiple Rows.

'select row_x from table_1 where row_y = 
'<first row from subquery>' or row_y = '<second row from subquery>' etc. 

Multiple rows are returned from a subquery. My issue is that if the subquery produces several rows, my query must return multiple rows as well.

Example 2: In the item table, display the order id, product id, and number of items that match both the product id and quantity of an item in order 605:

SELECT ordid, prodid, qty
 FROM item
 WHERE (prodid, qty) IN
 (SELECT prodid, qty
 FROM item
 WHERE ordid = 605)
 AND ordid <> 605;

SQL Subquery Not Exists

The SQL NOT EXISTS Operator will behave in a completely different way from the EXISTS Operator. It's used to limit how many rows the SELECT Statement returns. NOT EXISTS in SQL Server will search the Subquery for rows and return TRUE if none exist, else FALSE.

Except when no rows are returned by the subquery, the where clause in which it is utilized is fulfilled.

Statement in SQL If we use the EXISTS operator, all records whose values match the subquery return values will be returned. If we use NOT with the EXISTS operator, all records whose values do not satisfy the subquery values will be returned.

Example 1: Example for NOT EXIST: This query will have the exact opposite effect as the last one. All other entries will be returned except the sane sales_id.

SELECT * FROM sales WHERE NOT EXISTS (select * from orders where sales.sales_id = orders.sales_id);

Example 2: SQL Not Exists Operator Example:

The not exists operator in SQL returns records with values that do not exist in the subquery result or rows.

SELECT * FROM EmployeeDetails WHERE NOT EXISTS(SELECT * FROM EmployeeDetails WHERE empid =1)

Example 3: With the contents of the tables as in “Example: EXISTS with Correlated Subqueries”, the following rows are returned:

Choose the names of all students who have enrolled in at least one course offered by each department.

FROM student s
  (SELECT * 
  FROM department d 
  WHERE d.Dept IN 
  (SELECT Dept 
 FROM course c, registration r, class cl 
 WHERE c.Dept=d.Dept 
 AND c.CNo=r.CNo 
 AND s.SNo=r.SNo
 AND r.CNo=cl.CNo 
 AND r.Sec=cl.Sec)));


SName          SNo
-----          ---
Helen Chu      1

Example 4: To find the names of publishers who do not publish business books, the query is:

select pub_name 
from publishers 
where not exists 
   (select * 
    from titles 
    where pub_id = publishers.pub_id 
    and type = "business")


Binnet & Hardley

SQL Subquery Not In

In general, a NOT IN (...) subquery can be replaced with a NOT EXISTS (...), which is faster. Though they are logically equivalent, some database optimizers manage NOT EXISTS better since they can halt the subquery check after the first match.

Example 1: Several other tables refer to one table called "Common" in a database. I wanted to see what orphaned records there were in the Common table (i.e., had no references from any of the other tables).

select *
from Common
where common_id not in (select common_id from Table1)
and common_id not in (select common_id from Table2)

Example 2: If the DB optimizer can't figure out what you're doing and the subquery includes a lot of rows, it'll have to buffer all of the rows for each subquery before executing each NOT IN check.

FROM table1 a
   FROM table2 b
   WHERE b.user_id = 2
   AND b.index_field = a.field1)

The optimizer only needs to check if a single row exists for the matching subquery in this case, even with the additional filter on b.user id = 2. If an index on the index field and user id is available, it should be used.

SQL Subquery Pass Value

SQL Query Execution Before we run SQL Task, we must supply parameter/parameter values to Inner Query or Sub Query.

Example 1: GROUP BY is a useful tool. Each user should have SUM(total). id is used to pass specific cat id values. I'm not sure how the rest of your question looks, but you can simply:

SELECT users.id AS id,
FROM image_totals
WHERE cat_id IN ('5', '3')
GROUP BY users.id

Example 2: SQL, particularly in MySQL, has a limitation. All of the other SQL products I'm aware of lack it.

In general, there doesn't appear to be a solution to this problem: in MySQL, you can't force a column reference to be recognized more than one level down. In your case, though, there is an easy workaround: simply replace the parts. id with craft_w8_a.elementId in the innermost query:

SELECT elements.id, [ ... ],
  COALESCE(craft_w8_a.weight, 0) + COALESCE(SUM(craft_w8_b.weight), 0) 
  FROM `craft_w8` `craft_w8_a`
  LEFT JOIN `craft_w8` `craft_w8_b` 
  ON craft_w8_b.elementId
  IN ( SELECT targetId FROM `craft_relations`
  WHERE fieldId IN (15, 16)
  AND sourceId = craft_w8_a.elementId)
    WHERE craft_w8_a.elementId = elements.id
) as w8
FROM `craft_elements` `elements`
[ ... ]
GROUP BY `elements`.`id`
ORDER BY `w8` DESC, `name` ASC LIMIT 100

This is an equivalent substitute because whatever craft_w8_a.elementId will be passed to the IN subquery is going to match elements.id based on the filter in the query that passes the value.

Example 3: Lets say here is the query we want to run in Execute SQL Task:

FROM table1
WHERE id1 = (
  SELECT id2
  FROM table2
  WHERE col1 = @VarParamter1
    AND id3 = (
  SELECT id4
  FROM table3
  WHERE col2 = @VarParameter2

SQL Subquery Top

I heard that LIMIT 1 should work instead of TOP1, but I'm still getting the same problem associated subquery cannot have TOP or ORDER BY.

Using "top x" in a subquery strikes me as ambiguous (which may be why it's not allowed).

Example 1:

(select PROFIT_CTR from "MySchema"."MyTable" where COMP_CODE = '1234' LIMIT 1) as PC)

Example 2: Because there is no WHERE clause in the UPDATE statement, all records will be updated with a date. The "TOP 1" clause is a brand-new addition. The Order table returns only one record for the TOP 1 phrase.

SET OrderDate = (SELECT TOP 1 OrderDate FROM Order WHERE Order.CustomerId=Customer.CustomerId) 

If you didn't utilize the TOP 1 phrase and had more than one record for a given client, SQL will produce an error since your subquery returns more than one record.

Example 3: What do you expect the processing to be:

1. In your subquery, get only the first 8 matches of the join condition,


2. Only get 8 rows from t2, then look for matches in the outer table for those 8 rows.

if the answer is (1) then,

select top 8 field1, field2 from table where field2 in (select field2 from
table t2 where t2.field1 = table.field1)

is equivalent.

If the answer is (2, and it seems a strange query to write), you need to probably create a #temp table first, then use that #temp table in your


select top 8 field1, field2 into #temp from table
select field1, field2 from table where field2 in (select field2 from #temp
t2 where t2.field1 = table.field1)

SQL Subquery Update Multiple Rows

To update a table's single or many columns, use subqueries in conjunction with the UPDATE command.

Using a subquery, you can update many columns in one table from another table.


Update looks like this:

SET ( COL1, COL2 ) =

Example 1: Your table 004 is not necessary into the subsellect. Try this:

update table_004 t4
set (t4.status, t4.bar_date) =
    select  99,  max(foo_date)
    from table_001 t1
    inner join table_002 t2 on  t1.keyA = t2.keyA
    inner join table_003 t3 on  t2.keyA = t3.keyA
    where t1.id in(1, 2, 3, 4, 5) and t4.keyB = t3.keyB
    group by t1.id
where exists
    select *
    from table_001 t1
    inner join table_002 t2 on  t1.keyA = t2.keyA
    inner join table_003 t3 on  t2.keyA = t3.keyA
    where t1.id in(1, 2, 3, 4, 5) and t4.keyB = t3.keyB

Example 2: mysql update multiple rows with different values:

UPDATE config
   SET config_value = CASE config_name 
    WHEN 'name1' THEN 'value' 
    WHEN 'name2' THEN 'value2' 
    ELSE config_value
 WHERE config_name IN('name1', 'name2');

Example 3: Update the multiple table records:

UPDATE orders
SET order_value = order_value + 10
WHERE cust_id IN (SELECT cust_id FROM customers 
                      WHERE postal_code = 75016);

By increasing the current order value by $10, the above line will update the order value in the orders table for clients who live in the 75016 postal code area.

SQL Subquery with Alias Name

Even though I have given the aliases, the sql subquery with alias name produces this error notice.

Example 1: Way to give an Alias to name to subquery

SELECT payments.*,
(SELECT sum(allocations.amount) FROM allocations WHERE payments.id = allocations.payment_id) as allocation_sum
FROM payments
WHERE payments.amount <> allocation_sum;

Example 2: Add an ALIAS onto the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable   

Example 3:

SELECT e1.empID, e1.ClassID, (
  SELECT COUNT(*) FROM dept e2
  WHERE e1.ClassID = e2.ClassID)-1
  AS OtherempsInClass
    FROM dept e1
    WHERE empID = 6;

Example 4: subquery in FROM must have an alias at character 15 :

select a,b
	from (billing.item JOIN (
	select *
	from ( billing.invoice JOIN billing.customer
on (id_customer_shipped = customer_uid and address = 'pgh' ))
 as temp2 ))
as temp;

Because I have two from clauses, I have provided two alias names for those two clauses. However, I continue to receive the problem notice.


ERROR: subquery in FROM must have an alias at character 15
HINT: For example, FROM (SELECT ...) [AS] foo.


This log event is similar to a syntax error, but it's a unique problem that many people have because it's not immediately evident that queries should be written in this manner.