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

Nested queries in DQL

I first was wondering if nested queries were allowed in DQL. I found that at least partially the are (see here). So I'm wondering if they can do what I need. The situation is the following: I have the table ProjectNotification where I have all the…
Sergio Negri
  • 2,023
  • 2
  • 16
  • 38
2
votes
1 answer

Do not include select columns in group by

Here are my tables(including only relevant columns) Table: carts address_id - integer Table: addresses name - varchar phone - varchar Table: orders order_number - integer (this is the foreign key for cart table) I want to fetch phone number of…
Mudassir Ali
  • 7,913
  • 4
  • 32
  • 60
2
votes
1 answer

What is the difference between subquery and a joined subquery?

What is the difference between these two mysql queries select t.id, (select count(c.id) from comment c where c.topic_id = t.id) as comments_count from topic; AND select t.id,comments.count from topic left join ( select count(c.id)…
Sumeet
  • 1,683
  • 20
  • 27
2
votes
1 answer

SQL find references with single occurrences

I am trying to find a pure SQL solution for the following problem: If I sell paint and paintbrushes, and keep a record of which colors are sold like this: select OrderNumber, Product, Product_Type, Qty from…
teebagz
  • 656
  • 1
  • 4
  • 26
2
votes
2 answers

How to insert a query into another query in C# using Microsoft Visual Studio?

Is it possible to insert a query into another query in C#? Currently I am connecting to an access database and when I insert the query into another query in SQL view on Microsoft Access, the data I want is shown. However when I insert the same code…
Lucy MLJ
  • 59
  • 1
  • 11
2
votes
3 answers

show duplicate values subquery mysql

I have a mySQL query with a subquery. this subquery: (SELECT r.tlf_reserva FROM eventos e INNER JOIN Reservas r INNER JOIN viajes v WHERE r.id_viaje=v.id_propia AND e.id=1) returns two values, but the query: SELECT nombre FROM…
2
votes
3 answers

Nested Join in Subquery and failing correlation

I have 3 tables sc_user, sc_cube, sc_cube_sent I wand to join to a user query ( sc_user) one distinct random message/cube ( from sc_cube ), that has not been sent to that user before ( sc_cube_sent), so each row in the result set has a disctinct…
XtraBytesLab
  • 626
  • 7
  • 11
2
votes
2 answers

IP address numbers in MySQL subquery

I have a problem with a subquery involving IPV4 addresses stored in MySQL (MySQL 5.0). The IP addresses are stored in two tables, both in network number format - e.g. the format output by MySQL's INET_ATON(). The first table ('events') contains lots…
Iain Collins
  • 6,774
  • 3
  • 43
  • 43
2
votes
1 answer

SQL-Server. Calculate formula with subquery in aggregate function

I need to calculate value of Quantity column where Name = A using this formula in SQL-Server: A(Quantity) = (B*B1 + C*C1 + D*D1) / SUM(B1 + C1 + D1) + E Sample data: Static Static Dynamic Name ID Quantity -- Here are more columns,…
2
votes
2 answers

Update only rows where cust_id is present in other table

I have a query that will present a list of customers to be anonomized: select cu_number into #_t from customer where cu_first_name is not null I want to update last_name to " 'Anonomized' + sequence " and try this: update customer set…
Andreasp
  • 45
  • 1
  • 8
2
votes
3 answers

SQL Reference Large Equation in Select Statement

I have a large equation in a select statement that I need to reference in a where statement I think it is eating up my efficiency, I do not want to reference it more than I need to. SELECT 'HeaderDetail' AS rowType, ... , [large CASE/WHEN statement]…
2
votes
2 answers

To find all the active users in a bucket of 15 days in SQL

I have two tables: users, user_source_history. In table users, all the users who have registered are saved. And, in table user_source_history, their activities are stored. These activities may include log in to the system, ordering something. So…
nirvair
  • 4,001
  • 10
  • 51
  • 85
2
votes
2 answers

The best way to return related data in a SQL statement

I have a question on the best method to get back to a piece of data that is in a related table on the other side of a many-to-many relationship table. My first method uses joins to get back to the data, but because there are multiple matching rows…
DarLom
  • 1,100
  • 2
  • 12
  • 30
2
votes
3 answers

Mysql nested match against not returning any results

I wanted to select sub sets with match against SELECT * FROM ( SELECT * FROM Movie WHERE MATCH(keywords) AGAINST('$mk') ) WHERE MATCH(genres) AGAINST('$mg') $mk may be…
kutlus
  • 23
  • 4
2
votes
1 answer

Laravel - named subquery using Query Builder

In MySQL subqueries documentation there's an exmaple of subquery: SELECT ... FROM (subquery) [AS] name ... Here's the raw query which I want to transform: select SUBQUERY_NAME.* from (select id, name from items) AS SUBQUERY_NAME Is there any way…
Limon Monte
  • 52,539
  • 45
  • 182
  • 213