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
41
votes
3 answers

Joining 2 SQL SELECT result sets into one

I've got 2 select statements, returning data like this: Select 1 col_a col_b Select 2 col_a col_c If I do union, I get something like col_a col_b And rows joined. What i need is getting it like this: col_a col_b col_c Joined on data in…
Vance
  • 413
  • 1
  • 4
  • 4
40
votes
1 answer

How can I recreate this complex SQL Query using NHibernate QueryOver?

Imagine the following (simplified) database layout: We have many "holiday" records that relate to going to a particular Accommodation on a certain date etc. I would like to pull from the database the "best" holiday going to each accommodation (i.e.…
Chris Haines
  • 6,445
  • 5
  • 49
  • 62
39
votes
2 answers

Equivalent of ON CONFLICT DO NOTHING for UPDATE postgres

I want to update rows in my postgres database if the updated version wouldn't violate the primary key constraint. If it would, I want to leave the row as it is. Assuming the table has primary keys on col1, col2, col3, if I run a query like…
BHC
  • 889
  • 1
  • 7
  • 18
39
votes
5 answers

In which sequence are queries and sub-queries executed by the SQL engine?

Hello I made a SQL test and dubious/curious about one question: In which sequence are queries and sub-queries executed by the SQL engine? the answers was primary query -> sub query -> sub sub query and so on sub sub query -> sub query -> prime…
Igor
  • 2,619
  • 6
  • 24
  • 36
38
votes
9 answers

WHERE col1,col2 IN (...) [SQL subquery using composite primary key]

Given a table foo with a composite primary key (a,b), is there a legal syntax for writing a query such as: SELECT ... FROM foo WHERE a,b IN (SELECT ...many tuples of a/b values...); UPDATE foo SET ... WHERE a,b IN (SELECT ...many tuples of a/b…
Phrogz
  • 296,393
  • 112
  • 651
  • 745
37
votes
7 answers

PostgreSQL - Using a Subquery to Update Multiple Column Values

I need to be able to update multiple columns on a table using the result of a subquery. A simple example will look like below - UPDATE table1 SET (col1, col2) = ((SELECT MIN (ship_charge), MAX (ship_charge) FROM orders)) WHERE col4 = 1001; How…
user558122
  • 851
  • 3
  • 11
  • 15
36
votes
2 answers

Sequelize - subquery in where clause

I'm using Sequelize in my Express app. I need to generate a query that has a subquery in the WHERE clause. SELECT * FROM MyTable WHERE id NOT IN ( SELECT fkey FROM MyOtherTable WHERE field1 = 1 AND field2 = 2 …
hungerstar
  • 21,206
  • 6
  • 50
  • 59
34
votes
4 answers

Count rows with a specific condition in aggregate query

I have this query to get the number of PlayerSessions with reconnect = TRUE, grouped by Player.country: SELECT country, COUNT(*) AS with_reconnect FROM PlayerSession S LEFT JOIN Player P ON (P.id = S.player_id) WHERE reconnect = TRUE GROUP…
Bart van Heukelom
  • 43,244
  • 59
  • 186
  • 301
33
votes
4 answers

MYSQL update with WHERE SELECT subquery error

I have an issue with getting select sub-queries to work on an UPDATE. I'm trying something like the following: UPDATE foo SET bar=bar-1 WHERE baz= ( SELECT baz FROM foo WHERE fooID='1' ) Where foo is the table…
Erik
  • 2,276
  • 1
  • 20
  • 20
33
votes
6 answers

How to alias a field or column in MySQL?

I'm trying to do something like this. But I get an unknown column error: SELECT SUM(field1 + field2) AS col1, col1 + field3 AS col3 from core Basically, I want to just use the alias so that I won't need to perform the operations performed earlier.…
user225269
  • 10,743
  • 69
  • 174
  • 251
32
votes
2 answers

Example of an Oracle PIVOT clause with subquery

Oracle's definition of the PIVOT clause specifies that there is a possibility to define a subquery in the IN clause. A fictional example of what I would imagine this to be is this ... PIVOT (AVG(salary) FOR (company) IN (SELECT DISTINCT company FROM…
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
32
votes
5 answers

How to make a "distinct" join with MySQL

I have two MySQL tables (product and price history) that I would like to join: Product table: Id = int Name = varchar Manufacturer = varchar UPC = varchar Date_added = datetime Price_h table: Id = int Product_id = int Price = int Date = datetime I…
Steven Potter
  • 619
  • 1
  • 8
  • 13
30
votes
4 answers

SUM(subquery) in MYSQL

Basically, I am trying the following: SELECT m.col1, SUM(SELECT col5 FROM table WHERE col2 = m.col1) FROM table AS m This doesn't seem to work. Is there any solution?
Dänu
  • 5,791
  • 9
  • 43
  • 56
30
votes
3 answers

CAML query with nested ANDs and ORs for multiple fields

I am working on proof-of-concept code to dynamically generate CAML based on keywords provided to a highly-specific search web service that I am writing. I am not using the SharePoint-provided search web service for this proof. I have done so already…
Alban
  • 704
  • 1
  • 6
  • 11
30
votes
2 answers

Is possible to reuse subqueries?

I'm having some problems trying to perform a query. I have two tables, one with elements information, and another one with records related with the elements of the first table. The idea is to get in the same row the element information plus several…
Gothmog
  • 871
  • 1
  • 8
  • 20