SQL Subqueries
07/26/2001In the last article, I alluded to SQL subqueries which we'll discuss in more detail this week.
Subqueries are extremely useful, particularly for web-based database applications where you need to take two queries and manually put them together to reach a desired result -- subqueries allow SQL to do all of the heavy lifting! Subqueries can also be used in many cases to replace a self-join (or vice-versa). A SQL join is usually quicker but, as we've discussed many times before, there is usually more than one way to perform any given SQL task.
A query in a query?
The subquery is fairly straightforward part of the SQL specification. In a nutshell, a subquery is a SQL SELECT statement that is placed in the predicate of any other SQL statement we've explored -- SELECT, INSERT, UPDATE, or DELETE. You're quite smart enough on your own to figure them out without my intervention, but we'll cover them here to make sure we've hit everything!
A subquery can be used in a number of scenarios:
SELECT/UPDATE/DELETE .... WHERE (SELECT ...)which can be used to filter data before an action is applied to the results of that filter;INSERT INTO.... SELECT ....which can be used to copy tables or portions of tables into a new table for further manipulation;- Another subquery which can then be nested again up to the limits of your database platform -- or your sanity and understanding.
|
|
You've probably found yourself at various points in SQL development mentally creating subqueries in your head -- things like finding all of your high-volume customers who are also the ones that pay on time or maybe updating information about all the employees that are also managers in the company. Every major RDBMS lets you do at least some level of subquerying to address that exact issue.
Using a subquery
Let's say we want to find the names of all of the managers in the Employees table. Starting with the following table
| Employees | ||
| EmployeeID | EmployeeName | ManagerID |
| 61 | Sue Smith | (null) |
| 62 | David Jones | 61 |
| 63 | Troy Parker | 61 |
| 64 | Claire Smith-Jones | 63 |
| 65 | Grover Rivers | 63 |
we want to first select all of the values for ManagerID and then associate them with a name. We can do that with the following set of queries
SELECT EmployeeName AS Employee
FROM Employees
WHERE EmployeeID IN (SELECT DISTINCT ManagerID FROM Employees)
The queries are addressed from the inside out, so the first step is to perform the statement
SELECT ManagerID FROM Employees
which returns the result set (61,63). This means the outer query becomes
SELECT EmployeeName AS Employee
FROM Employees
WHERE EmployeeID IN (61,63)
which then gives us the record set ("Sue Smith", "Troy Parker").
The only caveat with subqueries is that you must be aware of exactly what the query will return as far as fields, field types, and values. Our subquery in this example returns a single column of values which are valid values for the WHERE EmployeeID IN clause. If the subquery returned the employee name, for example, you'd get a data type mismatch because "Sue Smith" is a string and EmployeeID is a numeric field -- WHERE EmployeeID IN ('Sue Smith'....) makes no sense. This caveat is especially true when you are using a SELECT subquery inside of an INSERT INTO statement -- both the number of fields, their order, and the data types must match up or the INSERT will fail.
Next steps
This article on subqueries is the final article in our introduction to the core SQL statements for manipulating data. Later, we'll move into SQL that manipulates the database itself, but before we do that, I'll devote the next several columns to the world of set algebra and the SQL commands relating to the UNION and INTERSECTION statements. Until then, feel free to contact me with your comments and questions.
-
SQL subquery help
2009-05-28 13:16:59 w2kadmin [View]
-
: Pending Delivery Note Details
2009-04-05 22:19:33 shebus [View]
-
Help with subquery please
2008-04-16 08:45:26 Viraco [View]
-
Help with subquery please
2008-04-16 08:43:51 Viraco [View]
-
how to get distinct values from second table on comparing with first table
2008-04-02 23:40:27 senthil.N [View]
-
Joins and pk, fk
2008-01-11 02:27:30 JugalKishorem [View]
-
Will a sub query help with LONG-Data?
2007-07-30 20:10:08 dgreep [View]
-
Types of Subqueries
2007-05-31 21:28:21 DJ86 [View]
-
using Left join and MAX and group by function getting wrong reslts
2007-04-20 23:18:20 satyac46 [View]
-
need answer..
2007-02-17 02:53:52 rajii [View]
-
answer for this
2007-04-02 21:44:52 sethumeena [View]
-
Count the number of record first existing in table at a date
2006-10-16 20:50:17 Devils [View]
-
Count the number of record first existing in table at a date
2007-12-17 02:49:44 Aryanrules [View]
-
Count the number of record first existing in table at a date
2009-04-28 04:23:25 SCJPSandy [View]
-
Count the number of record first existing in table at a date
2007-01-22 08:13:14 nikberry [View]
-
Count the number of record first existing in table at a date
2007-01-22 08:15:02 nikberry [View]
-
Count the number of record first existing in table at a date
2006-12-13 05:39:38 jmtsnprn [View]
-
Count the number of record first existing in table at a date
2006-10-29 01:25:20 ramu82 [View]
-
sub query help
2006-08-25 14:39:28 fperez [View]
-
sub query help
2006-11-17 21:08:48 pfindley [View]
-
i need total information
2006-07-09 03:04:24 SyedNasurUllah [View]
-
i need total information
2006-07-12 15:35:04 Doza [View]
-
Subquery - how
2006-06-07 06:37:45 Brickyard [View]
-
transforming subqueries to joins
2006-04-21 02:20:46 sinus [View]
-
Subquery
2006-04-01 05:21:25 rooman [View]
-
accumulate a field
2006-03-02 01:53:41 st.chen [View]
-
accumulate a field
2006-04-05 21:30:05 paul21_7 [View]
-
nth subquery if the records has same salary for two or three employees
2006-02-06 04:57:32 onlinestudyguide [View]
-
nth subquery if the records has same salary for two or three employees
2006-06-21 01:05:15 JustQuery [View]
-
nth subquery if the records has same salary for two or three employees
2006-02-06 12:40:48 subquires [View]
-
nth subquery if the records has same salary for two or three employees
2006-02-06 04:55:06 onlinestudyguide [View]
-
nth subquery if the records has same salary for two or three employees
2007-07-05 15:00:00 Poon [View]
-
How to sort a subquery?
2006-01-26 13:06:12 cyberlogi [View]
-
sql query
2005-12-09 00:00:58 davaleswarapu [View]
-
hi
2005-12-05 21:02:47 sqlserver2000 [View]
-
Moving selected information
2005-10-10 14:04:59 Greg007 [View]
-
Moving selected information
2005-10-16 20:03:54 isabella57 [View]
-
subqueries and group by
2005-09-16 10:21:39 LadyReader [View]
-
subqueries and group by
2006-02-06 12:47:48 subquires [View]
-
help
2005-09-13 21:47:18 sumeet_ [View]
-
Help! Need to increase salary by 5%
2005-03-22 07:24:39 cmrosiek [View]
-
Help! Need to increase salary by 5%
2005-08-03 00:35:59 bhawana [View]
-
Help! Need to increase salary by 5%
2005-10-16 20:11:01 isabella57 [View]
-
i want a previous value of the max value
2005-01-31 20:33:08 raviambala [View]
-
i want a previous value of the max value
2006-08-30 05:36:13 pavan_bh [View]
-
i want a previous value of the max value
2005-10-27 23:35:55 jagadishprem [View]
-
i want a previous value of the max value
2005-03-29 03:41:22 Ansu [View]
-
Subquery Question
2005-01-27 10:44:48 jcc [View]
-
Subqueries question - multiple conditions
2005-01-26 01:24:57 S-P-A-R-K [View]
-
Subqueries question - multiple conditions
2006-12-10 21:24:50 chandu_sql [View]
-
Subqueries question - multiple conditions
2007-07-05 16:19:21 Poon [View]
-
Subqueries question - multiple conditions
2007-07-05 16:16:26 Poon [View]
-
Subqueries question - multiple conditions
2007-07-05 16:14:19 Poon [View]
-
Subqueries question - multiple conditions
2005-03-07 07:37:33 edsel99 [View]
-
A little SQL Subquery help, please?
2004-12-14 22:02:03 LFaler [View]
-
A little SQL Subquery help, please?
2004-12-21 12:34:42 msantoyo [View]
-
Alternate sql query for existing quesry
2004-11-18 23:11:01 Samu [View]
-
Alternate sql query for existing quesry
2004-12-17 04:34:18 VISHSQL [View]
-
Do I need a subquery?
2004-11-08 07:53:54 andy_mcghee [View]
-
Subqueries
2004-01-29 22:43:01 wildmaniac2004 [View]
-
Sub Queries
2004-01-27 11:31:22 leenmary [View]
-
Subqueries
2003-09-15 05:26:20 anonymous2 [View]
-
number of rows returned by query
2003-08-28 03:42:57 anonymous2 [View]
-
number of rows returned by query
2004-10-12 04:13:55 dev-1 [View]
-
number of rows returned by query
2008-11-17 03:53:11 amit78g [View]
-
SQL SUBQUERIES
2003-07-29 15:59:25 anonymous2 [View]
-
Subquery
2003-06-21 03:17:00 anonymous2 [View]
-
subqueries
2003-05-15 11:32:27 anonymous2 [View]
-
subqueries
2003-04-27 06:31:41 anonymous2 [View]
-
SubQueries
2003-02-27 17:51:37 john1948 [View]
-
SubQueries
2003-06-04 06:27:40 anonymous2 [View]
-
multiple updates in a single query
2002-11-14 00:57:59 anonymous2 [View]
-
excercises on sql
2003-04-04 01:53:16 anonymous2 [View]
-
multiple updates in a single query
2002-11-14 00:53:31 anonymous2 [View]
-
subquery
2002-08-05 07:54:46 jgconst [View]
-
sort a query with two statements
2002-07-08 06:25:24 frank.reckers [View]
-
MySQL does not have subqueries
2002-01-27 01:05:16 jaalto [View]
-
MySQL does not have subqueries
2003-04-14 11:13:26 anonymous2 [View]
-
sub-queries
2001-12-05 09:12:06 avi_prabhu [View]
-
mySQL help
2001-11-07 03:10:30 adunkey [View]
-
mySQL help
2001-11-24 14:26:17 the_newt [View]
-
sql review
2001-10-01 18:14:25 dragonstep [View]



