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

How to impose LIMIT on sub-query of JPA query?

Is it possible to impose LIMIT on sub-query in JPA query ? I have following query in pure SQL select * from ipinfo where RangeEnd < (select RangeStart from ipinfo where RangeStart >= 1537022421 order by RangeStart asc limit 1) and (1537022421 <=…
expert
  • 29,290
  • 30
  • 110
  • 214
16
votes
3 answers

query with count subquery, inner join and group

I'm definitely a noob with SQL, I've been busting my head to write a complex query with the following table structure in Postgresql: CREATE TABLE reports ( reportid character varying(20) NOT NULL, userid integer NOT NULL, reporttype character…
Roberto Betancourt
  • 2,375
  • 3
  • 27
  • 35
16
votes
4 answers

How can I extract the values from a record as individual columns in postgresql

How can I extract the values from a record as individual comuns in postgresql SELECT p.*, (SELECT ROW(id,server_id,format,product_id) FROM products_images pi WHERE pi.product_id = p.id LIMIT 1) AS image FROM products p WHERE p.company = 1 ORDER…
codeassembly
  • 1,112
  • 1
  • 9
  • 17
16
votes
8 answers

SELECT with multiple subqueries to same table

I'm using the same SQL pattern over and over, and I know there has to be a better way, but I'm having trouble piecing it together. Here's a simple version of the pattern, where I'm pulling back the student's information and the last book they…
Jon Smock
  • 9,451
  • 10
  • 46
  • 49
16
votes
2 answers

Does SparkSQL support subquery?

I am running this query in Spark shell but it gives me error, sqlContext.sql( "select sal from samplecsv where sal < (select MAX(sal) from samplecsv)" ).collect().foreach(println) error: java.lang.RuntimeException: [1.47] failure: ``)'' expected…
Rinku Buragohain
  • 197
  • 1
  • 2
  • 9
16
votes
1 answer

MySQL Subquery LIMIT

As the title says, I wanted a workaround for this... SELECT comments.comment_id, comments.content_id, comments.user_id, comments.`comment`, comments.comment_time, NULL FROM comments WHERE (comments.content_id IN (SELECT…
Atif
  • 10,623
  • 20
  • 63
  • 96
16
votes
1 answer

Laravel: how to use derived tables / subqueries in the laravel query builder

Edit: Though this question originally was specific for the query I'm describing underneath, the answer I got applies to almost all questions related to using derived tables / subqueries in Laravel Original Question: Lately I'm a bit stuck on the…
Luuk Van Dongen
  • 2,391
  • 6
  • 26
  • 40
16
votes
3 answers

subquery uses ungrouped column "i.date_time" from outer query

I have two tables: item_status_log and items. The items table has the columns itemid, status, and ordertype. The item_status_log table has itemid, date_time, new_status, and old_status. Basically, when the status is changed in my program, a record…
lucky.expert
  • 743
  • 1
  • 15
  • 24
16
votes
2 answers

Rails Activerecord Relation: using subquery as a table for a SQL select statement

Can somebody help me figure out how to write the following SQL using Rails (I'm using Rails 4) Activerecord methods? I know you can do this with find_by_sql but I'd like to preserve the active record relation. Here's the sql for a postGreSQL db…
Vee
  • 1,821
  • 3
  • 36
  • 60
16
votes
1 answer

Doctrine 2 limit IN subquery

I'm trying to use a subquery in a IN statement in Doctrine2. Here's what the raw SQL query should look like : SELECT * FROM license WHERE id IN (SELECT id FROM license WHERE subscription = x ORDER BY date DESC LIMIT 5) ORDER BY…
Growiel
  • 775
  • 1
  • 7
  • 20
16
votes
2 answers

MySql Select, Count(*) and SubQueries in Users<>Comments relations

I have a task to count the quantity of users having count of comments > X. My SQL-query looks like this: SELECT users.id, users.display_name, (SELECT COUNT(*) FROM cms_comments WHERE cms_comments.author_id =…
WesternTune
  • 199
  • 1
  • 1
  • 8
15
votes
2 answers

Hibernate Subselect vs Batch Fetching

Hibernate provides (at least) two options for getting around the N+1 query problem. The one is setting the FetchMode to Subselect, which generates a select with a IN-clause and a subselect within this IN-clause. The other is to specify a BatchSize,…
Zecrates
  • 2,952
  • 6
  • 33
  • 50
15
votes
2 answers

how to log/trace redis calls from java spring app

I'm looking for the simplest way to log the redis activity originating from my java springboot microservice (queries and responses). I want to see (in the main springboot log file) log lines whenever data is extracted/inserted from/to redis. My…
MikaelW
  • 1,145
  • 4
  • 11
  • 29
15
votes
5 answers

MYSQL UPDATE with IN and Subquery

Hi i have tables like this : table entry : id | total_comments _____________________ 1 | 0 2 | 0 3 | 0 4 | 0 table comments : id | eid | comment _____________________ 1 | 1 | comment sdfd 2 | 1 | testing…
Johal
  • 597
  • 1
  • 7
  • 23
15
votes
4 answers

Can you index subqueries?

I have a table and a query that looks like below. For a working example, see this SQL Fiddle. SELECT o.property_B, SUM(o.score1), w.score FROM o INNER JOIN ( SELECT o.property_B, SUM(o.score2) AS score FROM o GROUP BY property_B ) w ON…
physicalattraction
  • 6,485
  • 10
  • 63
  • 122