O'Reilly Databases

oreilly.comSafari Books Online.Conferences.

We've expanded our coverage and improved our search! Search for all things Database across O'Reilly!

Search Search Tips

advertisement
AddThis Social Bookmark Button

Print Subscribe to Databases Subscribe to Newsletters
aboutSQL

SQL Subqueries

07/26/2001

In 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.

Comment on this articleDo you have questions or comments for John Paul Ashenfelter about subqueries?
Post your comments

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.


Comments on this article

1 to 49 of 49
  1. SQL subquery help
    2009-05-28 13:16:59  w2kadmin [View]

  2. : Pending Delivery Note Details
    2009-04-05 22:19:33  shebus [View]

  3. Help with subquery please
    2008-04-16 08:45:26  Viraco [View]

  4. Help with subquery please
    2008-04-16 08:43:51  Viraco [View]

  5. how to get distinct values from second table on comparing with first table
    2008-04-02 23:40:27  senthil.N [View]

  6. Joins and pk, fk
    2008-01-11 02:27:30  JugalKishorem [View]

  7. Will a sub query help with LONG-Data?
    2007-07-30 20:10:08  dgreep [View]

  8. Types of Subqueries
    2007-05-31 21:28:21  DJ86 [View]

  9. using Left join and MAX and group by function getting wrong reslts
    2007-04-20 23:18:20  satyac46 [View]

  10. need answer..
    2007-02-17 02:53:52  rajii [View]

  11. Count the number of record first existing in table at a date
    2006-10-16 20:50:17  Devils [View]

  12. sub query help
    2006-08-25 14:39:28  fperez [View]

  13. i need total information
    2006-07-09 03:04:24  SyedNasurUllah [View]

  14. Subquery - how
    2006-06-07 06:37:45  Brickyard [View]

  15. transforming subqueries to joins
    2006-04-21 02:20:46  sinus [View]

  16. Subquery
    2006-04-01 05:21:25  rooman [View]

  17. accumulate a field
    2006-03-02 01:53:41  st.chen [View]

  18. nth subquery if the records has same salary for two or three employees
    2006-02-06 04:57:32  onlinestudyguide [View]

  19. nth subquery if the records has same salary for two or three employees
    2006-02-06 04:55:06  onlinestudyguide [View]

  20. How to sort a subquery?
    2006-01-26 13:06:12  cyberlogi [View]

  21. sql query
    2005-12-09 00:00:58  davaleswarapu [View]

  22. hi
    2005-12-05 21:02:47  sqlserver2000 [View]

  23. Moving selected information
    2005-10-10 14:04:59  Greg007 [View]

  24. subqueries and group by
    2005-09-16 10:21:39  LadyReader [View]

  25. help
    2005-09-13 21:47:18  sumeet_ [View]

  26. Help! Need to increase salary by 5%
    2005-03-22 07:24:39  cmrosiek [View]

  27. i want a previous value of the max value
    2005-01-31 20:33:08  raviambala [View]

  28. Subquery Question
    2005-01-27 10:44:48  jcc [View]

  29. Subqueries question - multiple conditions
    2005-01-26 01:24:57  S-P-A-R-K [View]

  30. A little SQL Subquery help, please?
    2004-12-14 22:02:03  LFaler [View]

  31. Alternate sql query for existing quesry
    2004-11-18 23:11:01  Samu [View]

  32. Do I need a subquery?
    2004-11-08 07:53:54  andy_mcghee [View]

  33. Subqueries
    2004-01-29 22:43:01  wildmaniac2004 [View]

  34. Sub Queries
    2004-01-27 11:31:22  leenmary [View]

  35. Subqueries
    2003-09-15 05:26:20  anonymous2 [View]

  36. number of rows returned by query
    2003-08-28 03:42:57  anonymous2 [View]

  37. SQL SUBQUERIES
    2003-07-29 15:59:25  anonymous2 [View]

  38. Subquery
    2003-06-21 03:17:00  anonymous2 [View]

  39. subqueries
    2003-05-15 11:32:27  anonymous2 [View]

  40. subqueries
    2003-04-27 06:31:41  anonymous2 [View]

  41. SubQueries
    2003-02-27 17:51:37  john1948 [View]

  42. multiple updates in a single query
    2002-11-14 00:57:59  anonymous2 [View]

  43. multiple updates in a single query
    2002-11-14 00:53:31  anonymous2 [View]

  44. subquery
    2002-08-05 07:54:46  jgconst [View]

  45. sort a query with two statements
    2002-07-08 06:25:24  frank.reckers [View]

  46. MySQL does not have subqueries
    2002-01-27 01:05:16  jaalto [View]

  47. sub-queries
    2001-12-05 09:12:06  avi_prabhu [View]

  48. mySQL help
    2001-11-07 03:10:30  adunkey [View]

  49. sql review
    2001-10-01 18:14:25  dragonstep [View]

1 to 49 of 49


Tagged Articles

Be the first to post this article to del.icio.us

Related to this Article

Data Jujitsu: The Art of Turning Data into Product Data Jujitsu: The Art of Turning Data into Product
November 2012
$0.00 USD

Designing Great Data Products Designing Great Data Products
March 2012
$0.00 USD

Sponsored Resources

  • Inside Lightroom
Advertisement
O'reilly

© 2013, O’Reilly Media, Inc.

(707) 827-7019 (800) 889-8969

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.

About O'Reilly

  • Academic Solutions
  • Jobs
  • Contacts
  • Corporate Information
  • Press Room
  • Privacy Policy
  • Terms of Service
  • Writing for O'Reilly

Community

  • Authors
  • Community & Featured Users
  • Forums
  • Membership
  • Newsletters
  • O'Reilly Answers
  • RSS Feeds
  • User Groups

Partner Sites

  • makezine.com
  • makerfaire.com
  • craftzine.com
  • igniteshow.com
  • PayPal Developer Zone
  • O'Reilly Insights on Forbes.com

Shop O'Reilly

  • Customer Service
  • Contact Us
  • Shipping Information
  • Ordering & Payment
  • The O'Reilly Guarantee