Database

MySQL Subquery Placement

MySQL Subquery Placement

In this tutorial, we will learn about MySQL Subquery Placement. There are various types of subqueries in MySQL. The subquery’s usage is best described from its location in the SQL statement where it is used.

  • Subqueries can be used in SELECT, INSERT, UPDATE, and DELETE statements and in the SELECT, FROM, WHERE, HAVING, and ORDER BY clauses of queries.
  • Subqueries can be used in conditions that utilize comparison and special-purpose operators: IN, NOT IN, ANY, EXISTS, and NOT EXISTS.
  • The usual arithmetic operators can appear on either side of a subquery:
    =, <>, <,>,<=, >=
  • A subquery may need to be run several times through the data in order to achieve the desired result.
    In some cases, a temporary table alias may be necessary.

A subquery can be placed in different parts of a MySQL query, such as the SELECT, FROM, and WHERE clauses. Depending on its placement, a subquery can return a scalar value, a single row, a single column, or an entire table (multiple rows and columns).

Chart

The chart shows the usage between the subquery table result types and the locations in a SELECT statement where each type is allowed. The tick mark shows that the particular type of subquery is allowed in the corresponding location of the SQL statement.

Subquery Placement Scalar Row Column Table
SELECT / Column ✓
FROM Clause ✓ ✓ ✓ ✓
WHERE Clause (=) ✓ ✓
WHERE Clause (<, >, <=, >=) ✓
WHERE Clause (IN, ALL, ANY, SOME) ✓
WHERE Clause (EXISTS) ✓ ✓ ✓ ✓

Types

  1. Scalar Subquery: Returns a single value (one row and one column).
  2. Row Subquery: Returns a single row containing multiple columns.
  3. Column Subquery: Returns multiple rows containing a single column.
  4. Table Subquery: Returns multiple rows and multiple columns.

Important MySQL Notes

  • SELECT expressions generally require a scalar subquery.
  • FROM accepts a derived table (a subquery returning a result set).
  • = can compare a scalar or row subquery, provided the number of columns matches.
  • Comparison operators such as < and > generally require a scalar subquery.
  • IN, ALL, ANY, and SOME accept single-column subqueries. Compatible row-value comparisons are also supported.
  • EXISTS checks whether the subquery returns at least one row. The number of columns returned does not matter.

Note: The exact requirements depend on the comparison expression and the number of columns returned by the subquery.

For example, it shows that only a scalar subquery is allowed in the column designation of a SELECT statement. However, all types of subquery table results are allowed in the FROM clause of a statement.

—

MySQL Tutorials

MySQL Tutorials on this website:

https://www.testingdocs.com/mysql-tutorials-for-beginners/