❖ Expressions in SQL |
Expressions in SQL involve: objects, constants, operators
+=between123-53.141.0e-3truefalse'...'"..."\n'O''Brien'E'O\'Brien'$$O'Brien$$$tag$O'Brien$tag$❖ SQL Operators |
Comparison operators are defined on all types:
< > <= >= = <>
In PostgreSQL, !=<>==
Boolean operators ANDORNOT
Note ANDOR&&||
Most data types also have type-specific operations available
String comparison (e.g. str1 <
See PostgreSQL Documentation Chapter 8/9 for data types and operators
❖ SQL Operators (cont) |
SQL provides pattern matching for strings via LIKENOT LIKE
%.*_.name LIKE 'Ja%' |
name |
|
name LIKE '_i%' |
name |
|
name LIKE '%o%o%' |
name |
|
name LIKE '%ith' |
name |
|
name LIKE 'John' |
name |
PostgreSQL also supports case-insensitive matching: ILIKE
❖ SQL Operators (cont) |
PostgreSQL provides regexp-based pattern matching
via ~!~
Examples (using POSIX regular expressions):
name ~ '^Ja' |
name |
|
name ~ '^.i' |
name |
|
name ~ '.*o.*o.*' |
name |
|
name ~ 'ith$' |
name |
|
name ~ 'John' |
name |
Also provides case-insensitive matching
via ~*!~*
❖ SQL Operators (cont) |
Other operators/functions for string manipulation:
||lower()substring()Note that above operations are null-preserving (strict):
NULLNULL(a||' '||b)NULLabNULL❖ SQL Operators (cont) |
Arithmetic operations:
+ - * / abs ceil floor power sqrt sin etc.
Aggregations "summarize" a column of numbers in a relation:
count()sum()avg()min/max()count❖ The NULL |
Expressions containing NULLNULL
However, boolean expressions use three-valued logic:
| a | b | a AND |
a OR |
| TRUE | TRUE | TRUE | TRUE |
| TRUE | FALSE | FALSE | TRUE |
| TRUE | NULL | NULL | TRUE |
| FALSE | FALSE | FALSE | FALSE |
| FALSE | NULL | FALSE | NULL |
| NULL | NULL | NULL | NULL |
❖ The NULL |
Important consequence of NULL
These expressions do not work as (might be) expected:
x = NULL x <> NULL
Both return NULL
Can only test for NULL
x IS NULL x IS NOT NULL
❖ Conditional Expressions |
Other ways that SQL provides for dealing with NULL
coalesce(,,)
select coalesce(mark,'??') from Marks ...
nullif(,)
NULLcoalescenullif(mark,'??')❖ Conditional Expressions (cont) |
SQL also provides a generalised conditional expression:
CASE WHEN test1 THEN result1 WHEN test2 THEN result2 ... ELSE resultn END
E.g. case when mark>=85 then 'HD' ... else '??' end
Tests that yield NULLFALSE
If no ELSECASENULL
Produced: 22 Sep 2020