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
1085
votes
20 answers

Join vs. sub-query

I am an old-school MySQL user and have always preferred JOIN over sub-query. But nowadays everyone uses sub-query, and I hate it; I don't know why. I lack the theoretical knowledge to judge for myself if there is any difference. Is a sub-query as…
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
816
votes
17 answers

MySQL Error 1093 - Can't specify target table for update in FROM clause

I have a table story_category in my database with corrupt entries. The next query returns the corrupt entries: SELECT * FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category.id FROM category INNER JOIN …
Sergio del Amo
  • 76,835
  • 68
  • 152
  • 179
514
votes
8 answers

updating table rows in postgres using subquery

I have this table in a postgres 8.4 database: CREATE TABLE public.dummy ( address_id SERIAL, addr1 character(40), addr2 character(40), city character(25), state character(2), zip character(5), customer boolean, supplier boolean, …
stackover
  • 6,275
  • 6
  • 22
  • 20
501
votes
3 answers

Nested select statement in SQL Server

Why doesn't the following work? SELECT name FROM (SELECT name FROM agentinformation) I guess my understanding of SQL is wrong, because I would have thought this would return the same thing as SELECT name FROM agentinformation Doesn't the inner…
Brennan Vincent
  • 10,736
  • 9
  • 32
  • 54
492
votes
4 answers

What is the error "Every derived table must have its own alias" in MySQL?

I am running this query on MySQL SELECT ID FROM ( SELECT ID, msisdn FROM ( SELECT * FROM TT2 ) ); and it is giving this error: Every derived table must have its own alias. What's causing this error?
silverkid
  • 9,291
  • 22
  • 66
  • 92
442
votes
28 answers

Remove duplicate rows in MySQL

I have a table with the following fields: id (Unique) url (Unique) title company site_id Now, I need to remove rows having same title, company and site_id. One way to do it will be using the following SQL along with a script (PHP): SELECT title,…
Chetan
  • 4,885
  • 4
  • 22
  • 15
295
votes
4 answers

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

In this excellent SO question, differences between CTE and sub-queries were discussed. I would like to specifically ask: In what circumstance is each of the following more efficient/faster? CTE Sub-Query Temporary Table Table…
whytheq
  • 34,466
  • 65
  • 172
  • 267
287
votes
5 answers

What is the difference between a LATERAL JOIN and a subquery in PostgreSQL?

Since PostgreSQL came out with the ability to do LATERAL joins, I've been reading up on it since I currently do complex data dumps for my team with lots of inefficient subqueries that make the overall query take four minutes or more. I understand…
jdotjdot
  • 16,134
  • 13
  • 66
  • 118
187
votes
10 answers

Difference between CTE and SubQuery?

From this post How to use ROW_NUMBER in the following procedure? There are two versions of answers where one uses a sub-query and the other uses a CTE to solve the same problem. Now then, what is the advantage of using a CTE (Common Table…
dance2die
  • 35,807
  • 39
  • 131
  • 194
181
votes
12 answers

How to do this in Laravel, subquery where in

How can I make this query in Laravel: SELECT `p`.`id`, `p`.`name`, `p`.`img`, `p`.`safe_name`, `p`.`sku`, `p`.`productstatusid` FROM `products` p WHERE `p`.`id` IN ( SELECT `product_id` FROM…
Marc Buurke
  • 1,917
  • 2
  • 13
  • 14
164
votes
11 answers

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

I've got a couple of duplicates in a database that I want to inspect, so what I did to see which are duplicates, I did this: SELECT relevant_field FROM some_table GROUP BY relevant_field HAVING COUNT(*) > 1 This way, I will get all rows with…
quano
  • 18,812
  • 25
  • 97
  • 108
147
votes
8 answers

SQL Joins Vs SQL Subqueries (Performance)?

I wish to know if I have a join query something like this - Select E.Id,E.Name from Employee E join Dept D on E.DeptId=D.Id and a subquery something like this - Select E.Id,E.Name from Employee Where DeptId in (Select Id from Dept) When I…
Vishal
  • 12,133
  • 17
  • 82
  • 128
146
votes
2 answers

subquery in FROM must have an alias

I have this query I have written in PostgreSQL that returns an error saying: [Err] ERROR: LINE 3: FROM (SELECT DISTINCT (identifiant) AS made_only_recharge This is the whole query: SELECT COUNT (made_only_recharge) AS made_only_recharge FROM ( …
roykasa
  • 2,907
  • 6
  • 28
  • 29
136
votes
7 answers

How can I insert values into a table, using a subquery with more than one result?

I really would appreciate your help. Probably it's a quite simple problem to solve - but I'm not the one .. ;-) I have two tables in SQL Server: article prices Now I want to select a certain set of ids and insert some entries into the prices-table…
Futuretec
  • 1,371
  • 2
  • 9
  • 4
128
votes
2 answers

SQL LEFT JOIN Subquery Alias

I'm running this SQL query: SELECT wp_woocommerce_order_items.order_id As No_Commande FROM wp_woocommerce_order_items LEFT JOIN ( SELECT meta_value As Prenom FROM wp_postmeta WHERE meta_key = '_shipping_first_name' …
CharleyXIV
  • 1,590
  • 3
  • 13
  • 24
1
2 3
99 100