WHERE only returns rows that match a condition
The WHERE keyword lets you filter the rows returned from your query to only those where the specified condition is true. For example, get only rows where the year column has the value 2022 like SELECT "title", "author" FROM "longlist" WHERE "year" = 2022;.
There’s a bunch of operators you can use in the condition
=for equal, likeWHERE "year" = 2022year is 2022!=(or<>) for not equal, likeWHERE "year" != 2022year is anything but 2022.- You could achieve the same with
WHERE NOT "year" = 2022 LIKEdoes fuzzy string matching, for exampleWHERE "title" like 'The%'-%matches any string of characters,_matches a single character. This finds only titles that start with words that start withThe.LIKEis case-insensitive in some DBMSs, but case-sensitive in PostgreSQL - useILIKEfor case-insensitive comparison.- Range operators
<,>,<=and>=when the data in your column can be compared like that (numbers, dates etc). There’s alsoBETWEEN ... AND ...for inclusive range.
You can combine conditions using logical operators.
ORlikeWHERE "year" = 2022 or "year" = 2023ANDlikeWHERE "year" = 2022 AND "format" = 'paperback'- show precedence using
(), likeWHERE ("year" = 2022 OR "year" = 2023) AND "format" = 'paperback' ISandIS NOTare used with NULL , likeWHERE "translator" IS NULLto find books with no translator.
Use HAVING instead of WHERE to specify a condition on the result of a GROUP BY rather than a single row.