360 likes | 1.18k Views
Subqueries. Subquery. A subquery is an additional method for handling multitable manipulations. It is a SELECT statement that nests inside the WHERE, HAVING, or SELECT of another SELECT an INSERT, UPDATE or DELETE statement another subquery. General Syntax.
E N D
Subquery A subquery is an additional method for handling multitable manipulations.It is a SELECT statement that nests inside • the WHERE, HAVING, or SELECT of another SELECT • an INSERT, UPDATE or DELETE statement • another subquery
General Syntax SELECT colname FROM tableWHERE (SELECT colnameFROM table WHERE condition)ORDER BY colname • subqueries return results from an inner query to an outer clause
Two Types of Subqueries • Noncorrelatedthe inner query is first evaluated and used in evaluating the outer query • Correlatedouter query provides values for the inner queries evaluation
3 types of results • Zero or more items (introduced with an IN or with a comparison operator modified by ANY or ALL) • single value (introduced with an unmodified comparison operator) • existence test (introduced with exists)
Noncorrelated SELECT pub_nameFROM publishersWHERE pub_id in (SELECT pub_id FROM titles WHERE type=‘business’) • Subquery executes once and returns a list of values with which the outer query uses to finish its execution and evaluation
Correlated SELECT pub_nameFROM publishers pWHERE type IN (SELECT type FROM titles WHERE pub_id = p.pub_id) • The outer query executes first. • The inner query executes for every ROW the outer query returns and completes the evaluation.
Joins or Subqueries? • When you are evaluating one table based on the aggregate analysis of another table - use a subquery • When you need to display and/or evaluate data from more than one table -use a join • Sometimes it is just a matter of preference
Subquery Rules • The SELECT list of an inner subquery introduced with a comparator or IN can only have 1 expression or column name. • Subqueries introduced with EXISTS almost always have a select list of *. • Subqueries cannot manipulate their results. Cannot use ORDER BY or INTO.
Comparators Commonly Used • IN, NOT IN • ANY, ALL • EXISTS, NOT EXISTS