SQL WHERE
Internal
TODO
TO PROCESS: https://learning.oreilly.com/library/view/learning-sql-3rd/9781492057604/ch04.html
Overview
The WHERE
clause is the mechanism for filtering out unwanted data from the result set. The WHERE
clause can be used with SELECT
, UPDATE
and DELETE
, but not with INSERT
. The WHERE
clause may contain an arbitrary number of filter conditions separated by AND
, OR
and NOT
operators. The filter conditions may be optionally grouped together with parentheses.
[...] WHERE <filter_condition> AND|OR <filter_condition> ...
SELECT * FROM person WHERE person.name = 'Alice' AND (person.eye_color = 'blue' OR person.eye_color = 'black');
Using Parentheses
If the WHERE
clause includes three or more conditions combined with AND
, OR
or NOT
, you should use parentheses to make your intent clear.
Filter Conditions
A condition is made up of one or more expressions, combined with one or more operators. An expression can be any of the following:
- A number
- A column in a table or a view
- A string literal
- A built-in function such as
CONCAT()
- A subquery
- A list of expressions such as
('A', 'B', 'C')
The operators used within conditions include:
- Comparison operators:
=
,!=
,<
,>
,<>
,LIKE
,IN
,BETWEEN
. - Arithmetic operators:
+
,-
,/
,*
Equality Conditions
Inequality Conditions
Range Conditions
The BETWEEN Operator
String Ranges
TO PROCESS: https://learning.oreilly.com/library/view/learning-sql-3rd/9781492057604/ch04.html#:-:text=String%20ranges
Membership Conditions
Using Subqueries
Matching Conditions
Using Regular Expressions
NULL in Conditions
Also see:
SQL Conditional Logic
SQL has syntax that provides IF/ELSE conditional logic, except that it does not use the IF
keyword but CASE
. These expressions can be used in the SELECT
WHERE
clause, but also with conditional INSERT
, UPDATE
and DELETE
.
CASE
CASE
provides an IF/ELSE conditional logic that can be used in WHERE
clauses.
Refactor based on https://learning.oreilly.com/library/view/learning-sql-3rd/9781492057604/ch11.html
CASE <expression>
WHEN <result_1> THEN <expression>
WHEN <result_1> THEN <expression>
...
ELSE <expression>
END
A simple IF/ELSE:
CASE <expression_that_evaluates_to_true_or_false> WHEN TRUE THEN <if_expression>
ELSE <else_expression>
END
Usage example:
CASE array_length(person.skills, 1) > 0 WHEN TRUE THEN ('skill_we_search_for' = ANY(person.skills))
ELSE 'key_we_search_for' = ANY(general.skills)
END
TO PROCESS: https://www.geeksforgeeks.org/sql-conditional-expressions/