Skip to main content

VillageSQL is a drop-in replacement for MySQL with extensions.

All examples on this page work on VillageSQL. Install Now →
WHERE keeps the rows that satisfy a condition and drops the rest. Every lesson so far returned whole tables. This is the clause that turns a table into an answer. Open the client with mysql -u root -p sakila before you start.

How WHERE works

Replace COLUMN_LIST with the columns you want, TABLE_NAME with the table, and SEARCH_CONDITION with a test the server can apply to one row at a time. The server reads each row, evaluates the condition against that row’s values, and keeps the row when the result is true. A row that gives false, or gives NULL, is dropped. WHERE goes after FROM and before ORDER BY, and that is the order the result is defined in: filter, then sort what survived, then apply LIMIT. So a LIMIT 5 after a WHERE gives you 5 of the matching rows, not 5 rows of which some match. The server is free to reach that answer any way it likes, and EXPLAIN shows which way it picked.

Examples

1) Match one value

Sakila rates every film. This keeps the films rated G.
A string goes in single quotes. A number does not.

2) Compare a number

185 minutes is the longest film in the catalog and 10 films run that long, so the first 5 rows are all ties. Sorting by title as well breaks the tie, which is what makes the same 5 come back every time.

3) Filter on a column you did not select

The condition tests the row, not the result. rental_rate never appears in the output here, and the filter still works.

4) Everything except one value

<> is not equal. != means the same thing and either is fine.

WHERE cannot see a column alias

An alias names a column of the result. WHERE runs before the result exists, so naming an alias there fails.
Write the expression again in the condition instead.
ORDER BY is the clause that can use an alias, because it runs after the result is built. The ORDER BY lesson shows that.

Nothing matching is not an error

Empty set means the query ran and no row satisfied the condition. The server prints it in place of a table, so there are no column headings either. It is an answer.

Summary

  • Use WHERE to keep only the rows that satisfy a condition.
  • Put a string in single quotes and leave a number bare.
  • Expect the server to filter first, then sort, then apply LIMIT.
  • Test any column of the table, whether or not you selected it.
  • Repeat the expression in WHERE rather than naming an alias, which gives ERROR 1054.

See also

  • SELECT — the statement WHERE attaches to
  • Operators — the comparisons a condition is built from
  • AND, OR and NOT — combining several conditions
  • ORDER BY — sorting what survives the filter