Questions tagged [subquery]

"subquery" is vague SQL terminology, used to describe when there's either more than one `SELECT` statement in a query, or when used in Data Manipulation Language (DML) statements (IE: DELETE, UPDATE, INSERT, MERGE). The subquery's SELECT statement is always found within brackets/parenthesis.

A subquery is a query that is nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or inside another subquery. A subquery can be used anywhere an expression is allowed. In this example a subquery is used as a column expression named MaxUnitPrice in a SELECT statement.

"Subquery" is vague SQL terminology, used to describe when there's:

  • either more than one SELECT statement in a query, or when used in Data Manipulation Language (DML) statements (IE: DELETE, UPDATE, INSERT, MERGE).
  • The subquery's SELECT statement is always found within brackets/parenthesis.

It's vague because most refer to any of the following as subqueries:

###Subselect The following can only return one value - more than one will cause an error.

SELECT f.column,
       (SELECT b.col
          FROM BAR b) AS col2
  FROM FOO f

Here's a correlated version of the subselect:

SELECT f.column,
       (SELECT b.col
          FROM BAR b
         WHERE b.col2 = f.col2) AS col2
  FROM FOO f

###Derived Table/Inline View

SELECT f.*
  FROM (SELECT t.*
          FROM FOOBAR t) AS f

###IN/NOT IN

SELECT f.*
  FROM FOO f
 WHERE f.column IN (SELECT b.col
                      FROM BAR b)


SELECT f.*
  FROM FOO f
 WHERE f.column NOT IN (SELECT b.col
                          FROM BAR b)

###EXISTS/NOT EXISTS Most would call the following a "correlated subquery", but only if they don't know how the EXISTS operator works in SQL.

SELECT f.*
  FROM FOO f
 WHERE EXISTS (SELECT NULL
                 FROM BAR b
                WHERE b.col = f.column)


SELECT f.*
  FROM FOO f
 WHERE NOT EXISTS (SELECT NULL
                     FROM BAR b
                    WHERE b.col = f.column)

Conclusion

Subqueries (and correlated subqueries) only return one value, and the database will return an error if the subquery will return more than one value.

Through better use of terminology, it becomes easier to communicate issues when problems are encountered.


Helpful articles

11317 questions
19
votes
4 answers

Subquery in select clause with JPA Criteria API

I'm trying, as in title, to insert a subquery in select clause like in this simple SQL: SELECT id, name, (select count(*) from item) from item this is obviously only a mock query just to make my point. (The point would be to get the last invoice…
lelmarir
  • 593
  • 2
  • 7
  • 24
19
votes
3 answers

MySQL/MariaDB - order by inside subquery

I used the following query with MySQL 5.5 (or previous versions) for years without any problems: SELECT t2.Code from (select Country.Code from Country order by Country.Code desc ) AS t2; The order of the result was always descending as I…
G. Plante
  • 429
  • 1
  • 5
  • 13
19
votes
7 answers

How to use MAX() on a subquery result?

I am new to Oracle and the SQL world. I have a slight issue with a query that I cannot figure out for the life of me, I have spent a few hours trying different approaches and I cannot get the result I expect. So heres my query: SELECT * from(Select…
user1916441
  • 211
  • 1
  • 2
  • 4
19
votes
1 answer

Having clause vs subquery

I could write a query using an aggregate function in two ways: select team, count(min) as min_count from table group by team having count(min) > 500 or select * from ( select team, count(min) as min_count from table group by team ) as…
ferics2
  • 5,241
  • 7
  • 30
  • 46
18
votes
3 answers

CROSS/OUTER APPLY in MySQL

I need to use CROSS APPLY in MySQL (EC2 RDS MySQL instance). Looks like MySQL doesn't recognise the CROSS APPLY Syntax. Can someone help me please? Here's the query. SELECT ORD.ID ,ORD.NAME ,ORD.DATE ,ORD_HIST.VALUE FROM ORD CROSS APPLY…
hoz
  • 502
  • 2
  • 9
  • 25
18
votes
2 answers

SQL join subquery

I tried searching for an answer to my problem but failed to get an answer that actually helped. I've written an sql code but can't seem to find where the problem is. Is it possible to put a subquery in the "FROM" section? SELECT S2.ITEM, …
user2764786
  • 189
  • 1
  • 1
  • 3
18
votes
1 answer

How to reuse a sub query in sql?

I have query like the following select columns from (select columns1 from result_set where condition_common and condition1) as subset1 join (select columns2 from result_set where condition_common and condition2)…
Schu
  • 1,124
  • 3
  • 11
  • 23
18
votes
2 answers

The multi-part identifier could not be bound - SubQuery

Schema: create table TableA (A1 int) create table TableB (B1 int, B2 int) create table TableC (C1 int) Problematic query: SELECT * FROM TableA a INNER JOIN TableB b ON b.B1=a.A1 INNER JOIN (SELECT TOP 1 * FROM TableC c …
Matthew Azkimov
  • 467
  • 1
  • 4
  • 17
17
votes
3 answers

How to compare two query results for equality in MySQL?

I'm a MySQL user. I have two queries, and I wish to compare their results for equality. I would like to do this with a single query which would return true or false, so each of my two queries would most likely take the form of sub-queries. I would…
Gwen Avery
  • 173
  • 1
  • 1
  • 4
17
votes
2 answers

Cache/Re-Use a Subquery in MySQL

I have a very complex MySQL query that includes use of the same subquery three times. Will MySQL actually run the subquery three times? (It's an expensive one.) If so, is there a way for me to tell MySQL to save or cache the results so it won't do…
Doug Kaye
  • 1,565
  • 5
  • 23
  • 32
17
votes
3 answers

Selecting COUNT from different criteria on a table

I have a table named 'jobs'. For a particular user a job can be active, archived, overdue, pending, or closed. Right now every page request is generating 5 COUNT queries and in an attempt at optimization I'm trying to reduce this to a single…
nzifnab
  • 15,876
  • 3
  • 50
  • 65
17
votes
5 answers

How can I treat a UNION query as a sub query

I have a set of tables that are logically one table split into pieces for performance reasons. I need to write a query that effectively joins all the tables together so I use a single where clause of the result. I have successfully used a UNION on…
Michael Rutherfurd
  • 13,815
  • 5
  • 29
  • 40
17
votes
3 answers

Is order in a subquery guaranteed to be preserved?

I am wondering in particular about PostgreSQL. Given the following contrived example: SELECT name FROM (SELECT name FROM people WHERE age >= 18 ORDER BY age DESC) p LIMIT 10 Are the names returned from the outer query guaranteed to be be in the…
knpwrs
  • 15,691
  • 12
  • 62
  • 103
17
votes
3 answers

How do I perform update query with subquery in Access?

I want to port this SQL query, which works just fine on SQL Server, MySQL, and Oracle, to an Access database. How do I do that? Right now it prompts me for a Company_ID for some reason. Edit: I was getting the prompt because I forgot to first…
Kip
  • 107,154
  • 87
  • 232
  • 265
17
votes
6 answers

How to get file extension of file as a result of sql query?

I have a table named datas and I'm executing a query like this: SELECT linkurl AS DOWNLOADURL, lastrevlevel AS VERSION, code AS DESCRIPTION, created AS RELEASEDATE, name AS TYPE FROM datas WHERE id IN (SELECT child_id …
anto
  • 315
  • 3
  • 9
  • 18