

Due to this linkage, a correlated subquery cannot be executed by itself as a separate statement.

> WHERE birth SELECT last_name, first_name, birth FROM president For example, SELECT last_name, first_name, birth FROM president They test whether the comparison value stands in particular relationship to all or some of the values returned by the subquery. The ALL and ANY operators are used in conjunction with a relative comparison operator to test the result of a column subquery.

IN and NOT IN actually are synonyms for = ANY and ALL, which are covered in the next section. In this case, use a row constructor to specify the comparison values to test against each column: mysql> SELECT last_name, first_name, city, state FROM president In other words, you can use them with table subqueries. IN and NOT IN also work for subqueries that return multiple columns. > WHERE student_id NOT IN (SELECT student_id FROM absence) > WHERE student_id IN (SELECT student_id FROM absence) The following statements use IN and NOT IN to find those students who have absences listed in the absence table, and those who have perfect attendance (no absences): mysql> SELECT * FROM student NOT IN is true for rows in the outer query that match no rows returned by the subquery. IN is true for rows in the outer query that match any row returned by the subquery. They test whether a comparison value is present in a set of values. The IN and NOT IN operators can be used when a subquery returns multiple rows to be evaluated in comparison to the outer query. You can also use ROW(city, state) notation, which is equivalent to (city, state). | last_name | first_name | city | state | > WHERE last_name = 'Adams' AND first_name = 'John') This statement returns rows for presidents who were born in the same city and state as John Adams: mysql> SELECT last_name, first_name, city, state FROM president If a subquery returns a single row, you can use a row constructor to compare a set of values (that is, a tuple) to the subquery result. Scalar subquery results can be evaluated using relative comparison operators such as = or, >, >=, (SELECT AVG(score) FROM score WHERE event_id = 5).Subquery results can be tested in different ways: A table subquery returns a table of one or more rows of one or more columns.A row subquery returns a single row of one or more values.A column subquery returns a single column of one or more values.A scalar subquery returns a single value.Subqueries can return different types of information: WHERE event_id IN (SELECT event_id FROM grade_event WHERE category = 'T') Here’s an example that looks up the IDs for grade event rows that correspond to tests ( 'T') and uses them to select scores for those tests: SELECT * FROM score Performing Multiple-Table Retrievals with SubqueriesĪ subquery is a SELECT statement written within parentheses and nested inside another statement.
