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
127
votes
5 answers

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I am trying to write the following query on postgresql: select name, author_id, count(1), (select count(1) from names as n2 where n2.id = n1.id and t2.author_id = t1.author_id ) from names as n1 group by name,…
Ricardo
  • 7,785
  • 8
  • 40
  • 60
112
votes
3 answers

PostgreSQL 'NOT IN' and subquery

I'm trying to execute this query: SELECT mac, creation_date FROM logs WHERE logs_type_id=11 AND mac NOT IN (select consols.mac from consols) But I get no results. I tested it, and I know that there is something wrong with the syntax. In MySQL…
kskaradzinski
  • 4,954
  • 10
  • 48
  • 70
112
votes
9 answers

MySQL DELETE FROM with subquery as condition

I am trying to do a query like this: DELETE FROM term_hierarchy AS th WHERE th.parent = 1015 AND th.tid IN ( SELECT DISTINCT(th1.tid) FROM term_hierarchy AS th1 INNER JOIN term_hierarchy AS th2 ON (th1.tid = th2.tid AND th2.parent !=…
mikl
  • 23,749
  • 20
  • 68
  • 89
106
votes
4 answers

How to delete from select in MySQL?

This code doesn't work for MySQL 5.0, how to re-write it to make it work DELETE FROM posts where id=(SELECT id FROM posts GROUP BY id HAVING ( COUNT(id) > 1 )) I want to delete columns that dont have unique id. I will add that most of the time its…
IAdapter
  • 62,595
  • 73
  • 179
  • 242
99
votes
2 answers

Get records with highest/smallest per group

How can one get records with highest/smallest per group? Former title of this question was "using rank (@Rank := @Rank + 1) in complex query with subqueries - will it work?" because I was looking for solution using ranks, but now I see that the…
Tomas
  • 57,621
  • 49
  • 238
  • 373
86
votes
5 answers

Subqueries in activerecord

With SQL I can easily do sub-queries like this User.where(:id => Account.where(..).select(:user_id)) This produces: SELECT * FROM users WHERE id IN (SELECT user_id FROM accounts WHERE ..) How can I do this using rails' 3 activerecord/ arel/…
gucki
  • 4,582
  • 7
  • 44
  • 56
80
votes
8 answers

Can you define "literal" tables in SQL?

Is there any SQL subquery syntax that lets you define, literally, a temporary table? For example, something like SELECT MAX(count) AS max, COUNT(*) AS count FROM ( (1 AS id, 7 AS count), (2, 6), (3, 13), (4, 12), (5, 9) )…
thomasrutter
  • 114,488
  • 30
  • 148
  • 167
78
votes
7 answers

MySQL How do you INSERT INTO a table with a SELECT subquery returning multiple rows?

MySQL How do you INSERT INTO a table with a SELECT subquery returning multiple rows? INSERT INTO Results ( People, names, ) VALUES ( ( SELECT d.id FROM Names f JOIN People d ON d.id = f.id …
stackoverflow
  • 18,348
  • 50
  • 129
  • 196
77
votes
4 answers

Return pre-UPDATE column values using SQL only

I posted a related question, but this is another part of my puzzle. I would like to get the OLD value of a column from a row that was UPDATEd - WITHOUT using triggers (nor stored procedures, nor any other extra, non -SQL/-query entities). I have a…
pythonlarry
  • 2,316
  • 2
  • 20
  • 17
75
votes
6 answers

Efficient latest record query with Postgresql

I need to do a big query, but I only want the latest records. For a single entry I would probably do something like SELECT * FROM table WHERE id = ? ORDER BY date DESC LIMIT 1; But I need to pull the latest records for a large (thousands of…
Sheldon Ross
  • 5,364
  • 7
  • 31
  • 37
71
votes
2 answers

Find duplicate entries in a column

I am writing this query to find duplicate CTN Records in table1. So my thinking is if the CTN_NO appears more than twice or higher , I want it shown in my SELECT * statement output on top. I tried the following sub-query logic but I need pulls …
anwarma
  • 2,005
  • 5
  • 21
  • 21
68
votes
3 answers

MySQL: Returning multiple columns from an in-line subquery

I'm creating an SQL statement that will return a month by month summary on sales. The summary will list some simple columns for the date, total number of sales and the total value of sales. However, in addition to these columns, i'd like to include…
ticallian
  • 1,631
  • 7
  • 24
  • 34
66
votes
4 answers

JPA 2.0, Criteria API, Subqueries, In Expressions

I have tried to write a query statement with a subquery and an IN expression for many times. But I have never succeeded. I always get the exception, " Syntax error near keyword 'IN' ", the query statement was build like this, SELECT t0.ID,…
Keating
  • 3,380
  • 10
  • 34
  • 42
66
votes
6 answers

How to specify the parent query field from within a subquery in MySQL?

How do I specify the parent query field from within a subquery in MySQL? For Example: I have written a basic Bulletin Board type program in PHP. In the database each post contains: id(PK) and parent_id(the id of the parent post). If the post is…
justinl
  • 10,448
  • 21
  • 70
  • 88
65
votes
3 answers

SQLAlchemy - subquery in a WHERE clause

I've just recently started using SQLAlchemy and am still having trouble wrapping my head around some of the concepts. Boiled down to the essential elements, I have two tables like this (this is through Flask-SQLAlchemy): class User(db.Model): …
Chad Birch
  • 73,098
  • 23
  • 151
  • 149