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

How to Compute for ABCIndicator in T-SQL

I have a table of sales data for example: SELECT ItemCode, ItemDesc, TotalYearlySales, ShareOfBusiness, ABCIndicator FROM Sales WHERE Yir = Year(getdate()) AND Manth = Month(getdate()) ORDER BY TotalYearlySales DESC The ShareOfBusiness is computed…
stormwild
  • 2,855
  • 2
  • 31
  • 38
2
votes
3 answers

Oracle Order by not working for Subquery from DUAL

Hi all when I executed this query somehow its throwing the following error - ORA-00907: missing right parenthesis. But if you remove the order by 1 from SELECT 2 FROM DUAL order by 1 its working. Did I miss something out here or its ORACLE…
JuneDC
  • 31
  • 2
2
votes
1 answer

jooq - execute string as subquery

I have a query, represented by a string: final String q = "select 1 union select 2 union select 3"; This string comes from an external source (configuration), hence it is a string. In the real scenario, the query is ofcourse more meaningful. I…
Jef Jedrison
  • 283
  • 4
  • 11
2
votes
2 answers

having condition on result of a subquery in mysql

i am trying to run a query like this SELECT a, b , c, (SELECT INNULL(x,y)) as mycol WHERE mycol < 400 ; BUt it gives the error #1054 - Unknown column 'mycol' in 'where clause' What would be the right way to do this? Thanks.
naiquevin
  • 7,588
  • 12
  • 53
  • 62
2
votes
1 answer

ActiveRecord deep nested query and computed column

Here are the associations, Publication : has_many exchange_rates, books and authors Book belongs_to author, exchange_rate Author belongs_to exchange_rate I am trying to write a query to find books with one extra computed_column. This is the query I…
Sourabh Upadhyay
  • 1,034
  • 11
  • 31
2
votes
3 answers

MySQL multiple dependent subqueries, painfully slow

I have a working query that retrieves the data that I need, but unfortunately it is painfully slow (runs over 3 minutes). I have indexes in place, but I think the problem is the multiple dependent subqueries. I've been trying to rewrite the query…
matt80
  • 23
  • 3
2
votes
3 answers

Replace comparison to scalar subquery by inner join or left/right join

I need to write this query using inner joins or right/left joins but I don't know how to start: select * from radicados where asignado = (select estudianteid from estudiantes where usuario = (select usuarioid from usuarios where nombre…
Luis Contreras
  • 777
  • 9
  • 23
2
votes
3 answers

MySQL Query add limit in SubQuery

Here is my table test with values: Price ---------- 300 600 900 1000 1800 2000 I want to query such that when I search for 300 ,I should get 4 records 300,600,900,1000. If I search for 900, I can get 600,900,1000,1800. i.e. Two records <=900 and…
MaNn
  • 745
  • 4
  • 11
  • 22
2
votes
2 answers

SQLite sqlite3_step() hangs with big database

I'm writing a small Objective-C library that works with an embedded SQLite database. The SQLite version I'm using is 3.7.13 (checked with SELECT sqlite_version()) My query is: SELECT ROUND(AVG(difference), 5) as distance FROM ( SELECT ( …
Vik
  • 1,897
  • 12
  • 18
2
votes
3 answers

Transact-SQL Count using a subselect statement filtering on a variable from top select

I'm trying to include account of records associated with a particular user in the same row as other information about the user. Something like: select au.UserName as UsersName, Count( select sg.Id from sg where sg.Username =…
PLan
  • 133
  • 7
2
votes
3 answers

Mysql very slow subquery optimizing

I am building a sql query with a large set of data but query is too slow I've got 3 tables; movies, movie_categories, skipped_movies The movies table is normalized and I am trying to query a movie based on a category while excluding ids from…
gblblgl
  • 137
  • 2
  • 12
2
votes
2 answers

Assigning SELECT Results in Nested sql SELECT Statement to variables - PHP

In PHP-MySQL, I am using a nested select statement as follows: SELECT object_id FROM form_entry WHERE id=(SELECT entry_id FROM form_entry_values WHERE value='32711178-888' AND field_id = (SELECT id FROM form_field WHERE name='dealer')) Each SELECT…
JoshuaJeanThree
  • 1,382
  • 2
  • 22
  • 41
2
votes
1 answer

DELETE with SELECT sub-query gets stuck

The following delete statement causing mysql to stuck: DELETE FROM domains WHERE id IN (SELECT domain_id FROM domains_groups WHERE group_id = 9); While this statement, which does the same, works: DELETE FROM domains WHERE id IN (select id from…
Alon Dor
  • 111
  • 10
2
votes
0 answers

What is the difference between IN and EXISTS

I am reading tutorials and practice webs and I don't see the difference between IN and EXISTS And one more question: when should I put the subquery in the SELECT section, in the FROM section, in the WHERE section, in the HAVING section?
Asaf Shazar
  • 1,065
  • 1
  • 11
  • 33
2
votes
1 answer

Understanding why this MySQL outer select slows down the query

I have a Companies table and a Zipcodes table and I want to get the samllest subset of companyIDs before I apply additional processing. So often I put that in an inner select, grabbing the companyIDs on some WHERE condition and then go some…
Augie Gardner
  • 2,749
  • 3
  • 25
  • 36
1 2 3
99
100