Subquery Syntax

The syntax of a subquery is the same as that of a normal SELECT statement (see Chapters 4 through 7), except for the following differences:

  • You can nest a subquery in a SELECT, FROM, WHERE, or HAVING clause or in another subquery.

  • Always enclose a subquery in parentheses.

  • Don’t terminate a subquery with a semicolon. (You still must terminate the statement that contains the subquery with a semicolon.)

  • Don’t put an ORDER BY clause in a subquery. (A subquery returns an intermediate result that you never see, so sorting a subquery makes no sense.)

  • A subquery comprises a single SELECT statement. (You can’t use, say, a UNION of multiple SELECT statements as a subquery.)

  • A subquery can use columns in the tables listed in its own FROM clause ...

Get SQL: Visual QuickStart Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.