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

Quick Explanation of SUBQUERY in NSPredicate Expression

There appears to be zero documentation about the SUBQUERY keyword from Apple and I can't find a simple explanation about it on SO or on Google. It's a conspiracy! ;) Please, could someone from the inner-circle please just provide a quick explanation…
ApeOnFire
  • 649
  • 2
  • 6
  • 11
28
votes
10 answers

T-SQL Subquery Max(Date) and Joins

I'm trying to join multiple tables, but one of the tables has multiple records for a partid with different dates. I want to get the record with the most recent date. Here are some example tables: Table: MyParts Partid Partnumber Description 1 …
MaxGeek
  • 1,105
  • 6
  • 21
  • 32
28
votes
3 answers

sql server sub query with a comma separated resultset

I need to return records on a table and my result set needs to contain a comma separated list. I have attached an image of the 3 tables. I need to do a select that returns the record in the first table and include the last of AwardFocusName that…
obautista
  • 3,517
  • 13
  • 48
  • 83
28
votes
2 answers

How does Subquery in select statement work in oracle

I have looked all over for an explanation, to how does the subquery in a select statement work and still I cannot grasp the concept because of very vague explanations. I would like to know how do you use a subquery in a select statement in oracle…
user3054901
  • 367
  • 1
  • 4
  • 11
27
votes
2 answers

SQL use column from subselect in where clause

I have a query that looks something like that: SELECT a, b, c, (SELECT d from B limit 0,1) as d FROM A WHERE d >= 10 I get the result that I want when I run the query without the whereclause but when I add the where clause the query fails. Does…
Chris
  • 3,057
  • 5
  • 37
  • 63
27
votes
5 answers

Subqueries with EXISTS vs IN - MySQL

Below two queries are subqueries. Both are the same and both works fine for me. But the problem is Method 1 query takes about 10 secs to execute while Method 2 query takes under 1 sec. I was able to convert method 1 query to method 2 but I don't…
Techie
  • 44,706
  • 42
  • 157
  • 243
26
votes
6 answers

MySQL #1093 - You can't specify target table 'giveaways' for update in FROM clause

I tried: UPDATE giveaways SET winner = '1' WHERE ID = (SELECT MAX(ID) FROM giveaways) But it gives: #1093 - You can't specify target table 'giveaways' for update in FROM clause This article seems relevant but I can't adapt it to my query. How can…
Eray
  • 7,038
  • 16
  • 70
  • 120
26
votes
2 answers

PostgreSQL DELETE FROM (SELECT * FROM table FETCH FIRST 10 ROWS ONLY)

How do I delete only a few rows in postgreSQL? I want to fetch 10 rows to delete in a subquery. My table
ArthurDatur
  • 265
  • 1
  • 3
  • 7
26
votes
3 answers

Inner Join with derived table using sub query

Environment: SQL 2008 R2 I created a derived table using sub query and joined with main table. I just like to know if subquery is executed only once or will it be executed for each row in result set. Consider following example (fictional table names…
love kumar
  • 375
  • 1
  • 4
  • 6
25
votes
2 answers

SQL query to look for a Kevin Bacon number of 2

Using the IMDB database, I have tables actor, casts, and movie, and I need to select actors with a Kevin Bacon number of 2. I thought this should do it, but I'm getting 0 rows returned. What is my error? select fname, lname from actor join casts on…
Colleen
  • 23,899
  • 12
  • 45
  • 75
24
votes
3 answers

JPA/hibernate subquery in from clause

We're using JPA with hibernate as the provider, we have a query that contains a join with a subquery in the FROM clause, but we get the following error: org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 75…
gads
  • 436
  • 1
  • 5
  • 10
24
votes
3 answers

Hibernate Criteria Subquery

I need to do this SQL query with detachedCriteria: SELECT g.id FROM games g WHERE NOT EXISTS ( SELECT 1 FROM users_games ug WHERE ug.user_id = 1 AND g.id = ug.game_id) The idea is to get the ids from the games that aren't owned by the user. I…
Gonzalo
  • 1,126
  • 2
  • 12
  • 21
24
votes
4 answers

SQL Like with a subquery

How can i make this work? SELECT * FROM item WHERE item_name LIKE '%' || (SELECT equipment_type FROM equipment_type GROUP BY equipment_type) …
jordan
  • 3,436
  • 11
  • 44
  • 75
24
votes
4 answers

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

I have a stored procedure that select * from book table , using sub query my query is USE [library] GO /****** Object: StoredProcedure [dbo].[report_r_and_l] Script Date: 04/17/2013 12:42:39 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER…
Roshan
  • 287
  • 2
  • 4
  • 11
23
votes
3 answers

How to select most frequent value in a column per each id group?

I have a table in SQL that looks like this: user_id | data1 0 | 6 0 | 6 0 | 6 0 | 1 0 | 1 0 | 2 1 | 5 1 | 5 1 | 3 1 | 3 1 | 3 1 | 7 I want to write a query that returns two…
cjh193
  • 309
  • 2
  • 3
  • 9