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
2
votes
1 answer

Oracle select, how to access values from 'where exists' subquery in PHP?

I have a select in Oracle which has subquery. I need to access values from subquery in PHP code. For example I am able to access F.FILE_NAME and F.ID, but I need to access MI.ID and MCI.ITEM_ID as well. How to do this? $select ="SELECT…
MarciSM
  • 43
  • 7
2
votes
3 answers

SELECT First Group

Problem Definition I have an SQL query that looks like: SELECT * FROM table WHERE criteria = 1 ORDER BY group; Result I get: group | value | criteria ------------------------ A | 0 | 1 A | 1 | 1 B | 2 | 1 …
Shadowen
  • 838
  • 5
  • 14
2
votes
1 answer

Replace subquery with variable SQL Server

I have multiple delete statements to run on SQL Server 2008 R2 DELETE FROM A WHERE A_id in (SELECT B_id FROM B WHERE B_name = 'Target') DELETE FROM B WHERE B_id in (SELECT B_id FROM B WHERE B_name = 'Target') DELETE FROM C WHERE C_id in (SELECT B_id…
Sean
  • 981
  • 1
  • 9
  • 19
2
votes
1 answer

MySQL subquery not working

Please, can you review this query? I can't retrieve the correct values with the sub-query. I believe my logic is incorrect. I'm trying to make this work day after day, but without success. Above the SQL query in the SQLfiddle has the comments to…
Ailton
  • 165
  • 1
  • 12
2
votes
2 answers

How to execute sub query in if exists condition?

declare @qry varchar(100) declare @cnt int set @qry = ' where ' if exists( select * from ARTICLE_MANAGE +@qry+ article_id=65) BEGIN select top 1* from ARTICLE_MANAGE order by article_id desc END ELSE BEGIN select * from ARTICLE_MANAGE order by…
BALU K B
  • 135
  • 12
2
votes
2 answers

LINQ grouping/subquery to fill a hierarchy data strcuture

I have a DataTable that queries out something like below usergroupid...userid......username 1.............1...........John 1.............2...........Lisa 2.............3...........Nathan 3.............4...........Tim What I'm trying to do is write…
Fung
  • 7,530
  • 7
  • 53
  • 68
2
votes
3 answers

SQL: how to list values of a column that are not the 5 most occurring value of that same column?

I understand how to display the 5 most occurring value of a column like so: select top 5 col1, count(col1) from table1 group by col1 order by count(col1) desc; However, how do I create a query that displays all other values of the same column that…
DAT BOI
  • 183
  • 1
  • 1
  • 10
2
votes
2 answers

T-SQL Nested Subquery

Not being a SQL expert, and also only being semi-competent in CTE, how can I code this statement use the resultset from the following subquery within the main query, as our SQL Server is 2000. declare @subcategoryConcatenate varchar(3999) set…
ascomiller
  • 31
  • 2
2
votes
3 answers

How to fix SQL query with Left Join and subquery?

I have SQL query with LEFT JOIN: SELECT COUNT(stn.stocksId) AS count_stocks FROM MedicalFacilities AS a LEFT JOIN stocks stn ON (stn.stocksIdMF = ( SELECT b.MedicalFacilitiesIdUser FROM medicalfacilities AS b …
Babaev
  • 101
  • 10
2
votes
4 answers

Linq help - sub query gives null pointer exception

I writing a email system where we have a table of users "tblUsers" and a table of messages. A user can have many messages (from other users in tblusers) in his or her inbox (one:many). In tblUsers table, I have a column called ImageURL (string)…
Zuzlx
  • 1,246
  • 14
  • 33
2
votes
3 answers

Solving "single-row subquery returns more than one row" error in Oracle SQL

Given with the query below Select COLUMN_ID, (Select CASE COLUMN_ID WHEN 4 THEN 'WEIGHT' WHEN 6 THEN 'CARGO_LENGTH' WHEN 7 THEN 'WIDTH' WHEN 8 THEN 'HEIGHT' END GROOVE FROM ALL_TAB_COLS where TABLE_NAME = 'TBL_CARGO') FROM ALL_TAB_COLS where…
TDL
  • 126
  • 2
  • 13
2
votes
2 answers

convert nested query to join

I have two tables: entry id ...... individual id, entry_id, code where entry has a one to many relation to individual. I want to select all individuals that belong to an entry that contains more than 3 individuals which have…
Ibraheem
  • 100
  • 9
2
votes
4 answers

Help me turn a SUBQUERY into a JOIN

Two tables. emails id (int10) | ownership (int10) messages emailid (int10) indexed | message (mediumtext) Subquery (which is terrible in mysql). SELECT COUNT(*) FROM messages WHERE message LIKE '%word%' AND emailid IN (SELECT id FROM emails WHERE…
Christopher Padfield
  • 1,249
  • 2
  • 12
  • 18
2
votes
0 answers

Coredata NSPredicate with subquery

I need to search for Houses within a certain latitude and longitude area. I also need these houses to have at least one relationship with Object A where object A needs to have at least one relationship with Object B. The below predicate format seems…
pnizzle
  • 6,243
  • 4
  • 52
  • 81
2
votes
1 answer

SELECT [...] FROM (SELECT [...]) in DQL

I have the following query : SELECT COUNT(a0_.id) AS sclr0, LOWER(a0_.city) AS sclr1 FROM address a0_ INNER JOIN customer c1_ ON (c1_.customer_address = a0_.id) WHERE a0_.city IS NOT NULL AND a0_.city <> '' AND ( c1_.id IN ( SELECT…
VaN
  • 2,180
  • 4
  • 19
  • 43