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

How many times const subquery in select is executed?

I have query: SELECT id, (SELECT `name` from `config` WHERE id = 1) AS 'config' FROM customers How many times is the subquery executed? Does MySql cache this subquery constant or does it execute it for every row?
Konstantin Vahrushev
  • 1,110
  • 2
  • 11
  • 20
2
votes
2 answers

Mysql where (in) statement of another table without joins

I have 2 tables, A and B, both have the same data expect for that the table B also has a 'include' column. I want to select all a.code and a.user_id entries in table a expect if the same combination of A.user_id + A.code exists in table B where…
2
votes
2 answers

mySQL Error 1064 in subquery

I know it may be silly but I've spent 2 hours looking for the error and my deadline is running short. Can you help? Here's the code create view Children as select avg(chAvg) as Avg_Children from (select…
HappyCane
  • 363
  • 1
  • 2
  • 10
2
votes
1 answer

MySQL Query, Subquery optimization, SELECT, JOIN

I have one table with some data and I want select newest data for each type... Table: +----+------+------+---------------------+ | ID | data | type | date | +----+------+------+---------------------+ | 1 | just | 2 | 2010-08-07…
davispuh
  • 1,419
  • 3
  • 18
  • 30
2
votes
2 answers

Error in this subquery

This query: left join (select tSpent, Customerid from (select SUM(spent) as tSpent, Customerid, RN = ROW_NUMBER() OVER (PARTITION BY Customerid ORDER BY Customerid DESC) from Customer_Sales WHERE Customerid is not null) …
Patrick Schomburg
  • 2,494
  • 1
  • 18
  • 46
2
votes
3 answers

Keeping result of MySQL function (that gets used in WHERE) in my query results

I have got a MySQL function on my database, that calculates the levenshtein distance between two strings. levenstein("str1","str2"), returns INT I have a table filled with strings, and I would like my query to return the most relevant rows to the…
Dimitris Sfounis
  • 2,400
  • 4
  • 31
  • 46
2
votes
2 answers

How to output using recursive (parents -> children -> grandchildren)

CREATE TABLE PERSON ( persID INT IDENTITY(1,1) PRIMARY KEY, persFName VARCHAR(30) NOT NULL, persLName VARCHAR(30) NOT NULL, persDOB DATE, motherID INT FOREIGN KEY REFERENCES person(persID), fatherID INT…
Calisto
  • 323
  • 7
  • 19
2
votes
1 answer

How to eliminate outer reference from subquery

I have a query as: SELECT DISTINCT A2P.p_year [Year], A2P.aid [CoAuthor] FROM sub_aminer_author2paper A2P WHERE pid IN ( SELECT A2P.pid FROM sub_aminer_author2paper A2P JOIN sub_aminer_paper P ON…
maliks
  • 1,102
  • 3
  • 18
  • 42
2
votes
1 answer

SQL query - db2/400 iseries

My SQL group statement results in the below table. From this table, I need to subtract Qty with Code ='S' from Qty with code ='B' when Price and Date are matching. For example, in the below table I need the value to be stored in a work variable. 1)…
Peck
  • 43
  • 6
2
votes
0 answers

group() query, finalise clause, Can I show a sub-querying example?

Sub querying in mongoDB is non-sense. But what is this guy doing here? Summarizing: he queries the links collection; looking at the finalize clause, he queries the users collection. I can't do that, keep getting an error msg: uncaught exception:…
desmogix
  • 217
  • 2
  • 8
2
votes
3 answers

SQL Server query syntax (sub queries, brackets and CASE WHEN)

I have an issue with a query I am trying to run below. I've covered and closed all brackets but SQL Server still highlights Incorrect syntax near ')'. at the last bracket just by AS REV SELECT spot.spotid, rev.revenue FROM …
Shaye
  • 179
  • 13
2
votes
2 answers

SQL Server : Finding Max Value in Result Set

I have this code and I am having a hard time understanding why it is not working. I have searched for the solution, which is actually how my code ended up the way it is, but it just isn't working right... Any help would be appreciated. What I am…
2
votes
1 answer

Can all Relational Alegbra queries be done in SQL?

I'm currently taking a Databases course in college. We are taught that to write a query in SQL, you have to do the whole query in one statement (that is, one long line that ends in a semicolon). That is, we are taught that there is no way to…
silph
  • 316
  • 2
  • 9
2
votes
3 answers

SQL SELECT DISTINCT Subquery Error: 1241

I am working on a long query that includes a SELECT DISTINCT and subquery. It is partially working, but not when put together. I am getting a Error: 1241 - Operand should contain 1 column(s) and I cannot see why. Any help would be greatly…
Abigail Hardin
  • 167
  • 2
  • 13
2
votes
2 answers

Unknown column in where clause after server change

I have a somewhat hellish query (legacy database) that yields me a "column not found" error. It looks like this (VERY simplified): select somecolumn as name, ... ..., (select sum(someothercolumn) from table where somecolumn = name) from table where…
Eduardo Z.
  • 633
  • 3
  • 10
  • 32