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

MySQL Subquery related to LEFT JOINS

I was given the task of extracting customer information from a database and I am stuck on the last part! I hope my explanation is sufficient to describe my problem and attempts. Goal: Return one row per customer with their all phone number The…
Nathan_Sharktek
  • 407
  • 1
  • 5
  • 21
2
votes
1 answer

How to count two separate columns in the same table and sum them into a new column

I have two tables: playernames and matches. SELECT * FROM playernames; id | name ----+------------------ 38 | Abe Lincoln 39 | Richard Nixon 40 | Ronald Reagan (3 rows) SELECT * FROM matches; match_id | winner | loser…
Luke Sheppard
  • 275
  • 1
  • 2
  • 13
2
votes
2 answers

linq subquery child collection to string

i am trying to figure out how to write a linq query that will return a child collections "name" property as a string. I have a BO that has a "options" property where the options are the "name" property of each option in an "order" object. I would…
bill
  • 905
  • 5
  • 10
  • 21
2
votes
2 answers

SQL Date Range from current year

I need to make a function in SQL on SSMS to get sums of columns pertaining to a certain date range (From 9-1 of a year until 8-31 of the next year). the issue is that each year this date range will change. I know how to code in SQL: Create View…
Davidp04
  • 145
  • 1
  • 7
  • 17
2
votes
2 answers

How to improve LIMIT clause in MySQL subquery?

I have two tables : posts with 10k rows and comments and I need to select all comments for particular numbers of posts in other words implement the pagination by posts table and get all comments thereof. For that purpose I have the next…
Speise
  • 789
  • 1
  • 12
  • 28
2
votes
1 answer

Nested Join vs Nested Subquery

In this scenario, all Contractors place an order for various Stock Items on a daily basis. This data is stored in the ContractorOrder table. When the Stock is received, the values are recorded and saved in the ContractorStock table. It is not…
ilitirit
  • 16,016
  • 18
  • 72
  • 111
2
votes
2 answers

Alternate to ORDER BY subquery

From the database at http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_orderby2, for example (Click "Run SQL"), I want to list the customer who has the largest CustomerID that is greater than 80 first among a list of all customers from…
zylstra
  • 740
  • 1
  • 8
  • 22
2
votes
4 answers

Querying the Result set of a Previous Query

I have a query for example Query1 = Select Name from table where some Criteria. Now this query returns a result set of course, what I want is to query the result set of this query, for example I only want the unique Names from the above query select…
Abdullah Malikyar
  • 231
  • 1
  • 4
  • 19
2
votes
1 answer

Mysql subquery locking

If I have a query like: UPDATE table_x SET a = 1 WHERE id = ? AND ( SELECT SUM(a) < 100 FROM table_x ) And hundreds of this query could be made at exactly the same time I need to be certain that a never gets to more than 100 Do I need to…
Jonny White
  • 875
  • 10
  • 21
2
votes
1 answer

Is there a more efficient way to execute this nested SQL query?

I am writing a query to fill a select box on a user form and it works fine but when I look at the SQL, I feel like there should be a better, more efficient way to write it. Notice the two nested SELECTs below are from the same table. I am wondering…
2
votes
4 answers

Retrieving only rows for which a join has a dependancy

I am creating a testing system where users are allowed to re-test until they have passed. I would like to get a list, for a given UserID, of tests which are assigned to them which they have scored less than passing (100% for this example) on. I…
Hobadee
  • 189
  • 1
  • 10
2
votes
1 answer

Count with a subselect yielding double the amount

I'm new to SQL. Problem: Say if I were to count the amount that is contained in the alias table of "x" COUNT(x.xValue) to be 217. Now when I add the sub-query "y" and then do the count again, I have the COUNT(x.xValue) to suddenly square its self…
NiceNAS
  • 85
  • 1
  • 6
2
votes
2 answers

Order by subquery

I have the following oracle SQL code, but I can't understand what is the purpose of ordering by a subquery. Anyone can explain it clearly to me ? SELECT employee_id, last_name FROM employees e ORDER BY ( SELECT department_name …
ashur
  • 4,177
  • 14
  • 53
  • 85
2
votes
1 answer

Select max date in a group where max date is less than current date

I'm trying to execute a mysql query on this table data that would return the latest date that is less than the current date grouped by the booking number. Example of the table data: bookingnumber | booking_date | ------------------------------ 11 …
jboo
  • 21
  • 1
  • 1
  • 3
2
votes
1 answer

Firebase Nested Query

I am new to firebase and have read through the docs, but can't seem to find a away to get a list of all Ladders with populated User data. I don't really want to duplicate the user data in every ladder they are a member of. Here is my data…
1 2 3
99
100