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

Difference between WITH clause and subquery?

What is the difference between WITH clause and subquery? 1. WITH table_name as ( ... ) 2. select * from ( select curr from tableone t1 left join tabletwo t2 on (t1.empid = t2.empid) ) as temp_table
Hari Rao
  • 2,990
  • 3
  • 21
  • 34
64
votes
6 answers

Postgres Error: More than one row returned by a subquery used as an expression

I have two separate databases. I am trying to update a column in one database to the values of a column from the other database: UPDATE customer SET customer_id= (SELECT t1 FROM dblink('port=5432, dbname=SERVER1 user=postgres password=309245', …
user3182502
  • 671
  • 1
  • 5
  • 5
64
votes
6 answers

INSERT INTO with SubQuery MySQL

I have this Statement: INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice) VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1)); I'm trying to insert a value copy the same data of item_costprice, but show…
John Nuñez
  • 1,780
  • 13
  • 35
  • 51
60
votes
9 answers

How to reuse a result column in an expression for another result column

Example: SELECT (SELECT SUM(...) FROM ...) as turnover, (SELECT SUM(...) FROM ...) as cost, turnover - cost as profit Sure this is invalid (at least in Postgres) but how to achieve the same in a query without rewriting the sub-query twice?
Wernight
  • 36,122
  • 25
  • 118
  • 131
56
votes
1 answer

Use results from one sql query in another where statement (subquery?)

I see many similar questions but they're either so complex I can't understand them, or they don't seem to be asking the same thing. It's simple: I have two columns: users (dmid) and downloads (dfid). Select all users who downloaded a specific…
Josh Bond
  • 1,719
  • 4
  • 17
  • 26
54
votes
2 answers

Why is there a HUGE performance difference between temp table and subselect

This is a question about SQL Server 2008 R2 I'm not a DBA, by far. I'm a java developer, who has to write SQL from time to time. (mostly embedded in code). I want to know if I did something wrong here, and if so, what I can do to avoid it to happen…
Ward
  • 2,802
  • 1
  • 23
  • 38
53
votes
2 answers

Postgresql - Using subqueries with alter sequence expressions

Is it possible to use subqueries within alter expressions in PostgreSQL? I want to alter a sequence value based on a primary key column value. I tried using the following expression, but it wouldn't execute. alter sequence public.sequenceX restart…
Danmaxis
  • 1,710
  • 4
  • 17
  • 27
51
votes
2 answers

in postgres select, return a column subquery as an array?

(have done this before, but memory fades, as does goggle) wish to get select from users with the tag.tag_ids for each user returned as an array. select usr_id, name, (select t.tag_id from tags t where t.usr_id = u.usr_id) as…
cc young
  • 18,939
  • 31
  • 90
  • 148
50
votes
3 answers

PostgreSQL: Sub-select inside insert

I have a table called map_tags: map_id | map_license | map_desc And another table (widgets) whose records contains a foreign key reference (1 to 1) to a map_tags record: widget_id | map_id | widget_name Given the constraint that all map_licenses…
Bantha Fodder
  • 1,242
  • 1
  • 11
  • 19
49
votes
3 answers

How we can use CTE in subquery in sql server?

How we can use a CTE in a subquery in SQL Server? like: SELECT id (I want to use CTE here), name FROM table_name
Paresh
  • 3,659
  • 6
  • 27
  • 32
49
votes
8 answers

Difference between Subquery and Correlated Subquery

Is the following piece of SQL Query a normal query or a Correlated Subquery ?? SELECT UserID, FirstName, LastName, DOB, GFName, GLName, LoginName, LoginEffectiveDate, LoginExpiryDate, …
Divakar
  • 652
  • 2
  • 7
  • 18
46
votes
2 answers

How do I concatenate strings from a subquery into a single row in MySQL?

I have three tables: table "package" ----------------------------------------------------- package_id int(10) primary key, auto-increment package_name varchar(255) price decimal(10,2) table…
mrbinky3000
  • 4,055
  • 8
  • 43
  • 54
44
votes
3 answers

When to use SQL sub-queries versus a standard join?

I am working on rewriting some poorly written SQL queries and they are over-utilizing sub-queries. I am looking for best-practices regarding the use of sub-queries. Any help would be appreciated.
Brad Krusemark
  • 503
  • 1
  • 4
  • 10
42
votes
5 answers

Use columns from the main query in the subquery

Is there any way to get a column in real time, from a main query, and use it in a subquery? Something like this: (Use A.item in the subquery) SELECT item1, * FROM TableA A INNER JOIN ( select * from TableB B where A.item = B.item )…
João Guilherme
  • 503
  • 1
  • 5
  • 8
42
votes
2 answers

Selecting max record for each user

This seems if it should be fairly simple, but I'm stumbling in trying to find a solution that works for me. I have a member_contracts table that has the following (simplified) structure. MemberID | ContractID | StartDate | End Date…
Scott
  • 887
  • 2
  • 10
  • 10