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
1 answer

The difference in these two queries (EXISTS with NOT LIKE and NOT EXISTS with LIKE)

I have a really hard time to understand the difference between these two queries. The don't give the same output, just a slightly difference in the results. Isn't these two queries the same, but just inverted? You can see the difference in the last…
Sadjad Johansson
  • 320
  • 2
  • 13
2
votes
1 answer

Entity Framework LINQ - Subquery with Group By

I am trying to achieve a query which includes a subquery which itself includes grouping. I based my code from answers to this question The purpose of the code is to perform a simple de-duplication of the 'person' table based on the email address and…
ptutt
  • 1,338
  • 3
  • 18
  • 35
2
votes
1 answer

Performance considerations for SUB QUERY, LIMIT and ORDER BY when using MySQL

Objective: Select 10 users whose ongoing games is < 5. Approach 1: Do everything within MySQL Select users (LIMIT 10) and check n_ongoingGames for each user Approach 2: SQL + result-set analysis Get records for say 30 users. For each record, go to…
Kaya Toast
  • 5,267
  • 8
  • 35
  • 59
2
votes
2 answers

DataGridView cell search using a LINQ query

I'm still relatively new to LINQ, and have done more stumbling around than anything, but I have really liked what I have seen so far. So with that in mind, I have a VB.NET search routine, part of which is provided, below, that checks all Text cells…
Mike Loux
  • 706
  • 2
  • 11
  • 23
2
votes
1 answer

Insert sql statement with a subquery and sequence

I have an insert into statement and this statement will have a sub query where it gets all its information from. I just have one problem I have to use an primary key index which I created as a sequence. I just don't know how to insert a sequence…
Hendrien
  • 325
  • 1
  • 10
  • 20
2
votes
2 answers

sql server: looping through a subquery and limting result in main query corresponding to evry row in subquery

I am working on stackoverflow sqlquery portal. I want to have top 1000 tags with maximum post count. and for each tag need id of 60 post which have that tag as their tag. so i need to loop across all 100 tags and and get top 60 postid linked with…
Akhil Batra
  • 581
  • 4
  • 16
2
votes
2 answers

How to use a sub query as part of a stored procedure MySQL

I am trying to create a procedure (called a routine in phpMyAdmin) and currently have this query: BEGIN INSERT INTO `users` (`username`, `password`, `email`, `user_role_id`,` date_registered`) VALUES (_username, _password, _email, (SELECT `ID`…
Can O' Spam
  • 2,718
  • 4
  • 19
  • 45
2
votes
1 answer

mySQL select records based on difference to previously selected record

This is difficult to explain so please bear with me: I'm trying to construct a mySQL query that will select the first record but then will not select another record until a certain requirement of difference has been met by an integer column. e.g.,…
user622327
2
votes
4 answers

How to use the results of a select in another select in a union query?

I have a union query, where I want to use the results of the select in the "left side" of the union query, in the select statement on the "right side" of the union query. The query below works correctly (on postgres at least), but I am running…
StvnBrkdll
  • 3,924
  • 1
  • 24
  • 31
2
votes
2 answers

SQL - Sum of a subquery: What are I am doing wrong?

I am very new to SQL and doing my first steps since a few days. But know I have come to a dead spot. It would be very nice if you are willing to help me. These are the required tables: Table: Customer_Bonus Bonus_ID, Customer_ID, Amount 301, 100215,…
tho.mass
  • 23
  • 3
2
votes
3 answers

How to group by month of a date using a function in a select statement

I am having problems grouping by the month of a date when using a function. It was working before but the query was less complicated as I am now using a function that uses a rolling year from the current month. Here is my code. SELECT CASE WHEN…
Tom McDonough
  • 1,176
  • 15
  • 18
2
votes
1 answer

Hibernate joined table limit result

I've got two tables A and B. I execute LEFT OUTER JOIN on it and works fine. I tried to limit rows number by table A, so for me when I ask for 5 rows I want 5 rows from table A joined with no matter how many rows from table B. Just like: select *…
voncuver
  • 65
  • 6
2
votes
0 answers

Hibernate subselect fetching of association, how to pass parameters?

We have a class A that has two levels of nested associations as follows: @Entity @NamedQuery("select a from A JOIN FETCH b"); public class A { @OneToOne(cascade = CascadeType.ALL, optional = true) @JoinColumn(name = "XXX") private…
Paddy
  • 3,472
  • 5
  • 29
  • 48
2
votes
0 answers

MySQL - Select a column name from a column value

I have a SQL statement that seems to not work with what I'm trying to do. I'm trying to select a dynamic column name by selecting a column value as a column name. However I get no errors and no values at all from the sub-select statement. Here is my…
Daniel Harris
  • 1,805
  • 10
  • 45
  • 63
2
votes
2 answers

How to exclude some rows on inner / union queries

I have a problem with my SQL queries (I know I'm very bad at this task :( ) Using SLQ Server 2014, I've got a table that stores bank days containing the name of the day and a datetime. On the other hand there's a table with technicians that has…
bitsdisasters
  • 253
  • 5
  • 14