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

How to limit results of a LEFT JOIN

Take the case of two tables: tbl_product and tbl_transaction. tbl_product lists product details including names and ids while tbl_transaction lists transactions involving the products and includes dates, product-ids, customers etc. I need to…
eddy edu
  • 233
  • 1
  • 2
  • 6
23
votes
4 answers

Can HQL Select on the result set of another query?

Can HQL Select on the result set of another query? For example: SELECT COUNT(*) FROM (SELECT * FROM Table) I can do it in SQL but when I tried like above in HQL, it just showed me syntax error "unexpected token: ( near line 1, column 22 ..."
Red Bit
  • 455
  • 2
  • 6
  • 15
22
votes
3 answers

How do I get a count of associated rows in a left join in MySQL?

I have two tables, a vehicle table with columns: id stock year make model and an images table with columns: id vehicle_id name caption default tinyint(1) I am trying to list the vehicle's information, its default image, and a total count of…
Cris McLaughlin
  • 1,201
  • 2
  • 14
  • 23
22
votes
2 answers

Counting rows from a subquery

How could I count rows from a SELECT query as a value? Such as SELECT FUCNTIONIMLOOKINGFOR(SELECT * FROM anothertable) AS count FROM table; So that count is an integer of how many rows the subquery SELECT * FROM anothertable returns. EDIT SELECT…
Shoe
  • 74,840
  • 36
  • 166
  • 272
22
votes
4 answers

FetchMode Join vs SubSelect

I have two tables Employee and Department following are the entity classes for both of them Department.java @Entity @Table(name = "DEPARTMENT") public class Department { @Id @Column(name = "DEPARTMENT_ID") @GeneratedValue(strategy =…
eatSleepCode
  • 4,427
  • 7
  • 44
  • 93
22
votes
3 answers

Get data from multiple SELECT sub-queries for reporting from MySQL database

I'm trying to achieve is to create one complex query consisting of a few sub-queries. The idea is to give it to a business person to run on a weekly basis to pull reporting data. The effect would be similar to the query below, where all data from…
user1775967
  • 631
  • 2
  • 6
  • 14
22
votes
1 answer

spring-data subquery within a Specification

Spring-data, Oliver Gierke's excellent library, has something called a Specification (org.springframework.data.jpa.domain.Specification). With it you can generate several predicates to narrow your criteria for searching. Can someone provide an…
John Kroubalkian
  • 291
  • 1
  • 3
  • 11
22
votes
7 answers

MYSQL use 'LIKE' in 'WHERE' clause to search in subquery

How would you use 'LIKE' to search in a subquery? E.g. i've tried doing this, but doesn't work: SELECT * FROM mytable WHERE name LIKE '% (SELECT name FROM myothertable) %' I have this so far: SELECT * FROM t1 WHERE t1.name IN…
qwerty
  • 223
  • 1
  • 2
  • 5
21
votes
5 answers

Is it possible to use a Stored Procedure as a subquery in SQL Server 2008?

I have two stored procedures, one of which returns a list of payments, while the other returns a summary of those payments, grouped by currency. Right now, I have a duplicated query: the main query of the stored procedure that returns the list of…
isekaijin
  • 19,076
  • 18
  • 85
  • 153
21
votes
4 answers

Is there a way to give a subquery an alias in Oracle 11g SQL?

Is there a way to give a subquery in Oracle 11g an alias like: select * from (select client_ref_id, request from some_table where message_type = 1) abc, (select client_ref_id, response from some_table where message_type = 2) defg where …
Matt Pascoe
  • 8,651
  • 17
  • 42
  • 48
21
votes
2 answers

mysql subquery inside a LEFT JOIN

I have a query that needs the most recent record from a secondary table called tbl_emails_sent. That table holds all the emails sent to clients. And most clients have several to hundreds of emails recorded. I want to pull a query that displays the…
coffeemonitor
  • 12,780
  • 34
  • 99
  • 149
20
votes
2 answers

Using subselect to accomplish LEFT JOIN

Is is possible to accomplish the equivalent of a LEFT JOIN with subselect where multiple columns are required. Here's what I mean. SELECT m.*, (SELECT * FROM model WHERE id = m.id LIMIT 1) AS models FROM make m As it stands now doing this gives me…
Andre
  • 1,347
  • 3
  • 14
  • 23
20
votes
2 answers

MySQL Left Join Subquery with *

I'm putting together a fairly simple query with a subquery in the JOIN statement. It only works if I include an * in the subquery select. Why? This works $sql = 'SELECT locations.id, title, name, hours.lobby FROM locations LEFT JOIN…
MAZUMA
  • 913
  • 3
  • 10
  • 20
20
votes
7 answers

Procedurally transform subquery into join

Is there a generalized procedure or algorithm for transforming a SQL subquery into a join, or vice versa? That is, is there a set of typographic operations that can be applied to a syntactically correct SQL query statement containing a subquery that…
Justin R.
  • 23,435
  • 23
  • 108
  • 157
19
votes
5 answers

MySQL correlated subquery in JOIN syntax

I would like to provide a WHERE condition on an inner query by specifying innertable.id = outertable.id. However, MySQL (5.0.45) reports "Unknown column 'outertable.id' in 'where clause'". Is this type of query possible? The inner query is pivoting…
Taylor Gerring
  • 1,825
  • 1
  • 12
  • 17