CSCI 343 SQL expressions

See the expressions page of the SQLite3 documentation for much more information.

For single values

C/Java vs SQL

Many C/Java operators work with SQL; however, there are some notable exceptions. Here are some things to watch out for.

And here are a few things that are different but can be avoided.

Functions

SQL has a number of core functions that can be applied to single values. The most common, by far, seems to be abs.

String matching

SQL uses the LIKE operator for string matches. With LIKE, the % matches zero or more characters and the _ matches one character By default, the string matching operator is not case sensitive. For example, 'SQL' LIKE 'S%' and 'SQL' LIKE 'S_L' and 'SQL' LIKE 'sql' are all true.

Some SQL implementations even support a Unix-style glob.

For tables

As you would expect for a relational database application language, there are many operators that work on tables.

Membership tests

SQL has a few set operators for testing a value against the result of a table returned from a SELECT.

Aggregate function

Aggregate functions are applied to values from a table to generate a single value. All of these ignore NULL values inside the table.

Modified comparison

The SQL standard provides modified comparisons that test a single value against all the values of a table. This is done by placing ALL or ANY after a comparison operators. Modified comparisons are not supported in sqlite3.

Literals

Testing

You can use the SELECT statement of SQL to test your expressions. Here are some examples.

SELECT 5 + 6 ;
SELECT 1 AND 0 ;
SELECT 1 OR 0 ;
SELECT 1 <> 0 ;
SELECT 1 = 0 ;
SELECT 1 == NULL ;
SELECT 0 == NULL ;
SELECT 1 IS NULL ;
SELECT 5 BETWEEN 3 AND 7 ;
SELECT 0 AND 1 + 5 ;
SELECT (0 AND 1) + 5 ;
SELECT ABS(-5) ;
SELECT 'SQL' LIKE 'S%' ;
SELECT 'SQL' LIKE 'S_L' ;
SELECT 'SQL' LIKE 'sql' ;
SELECT 'banananana' GLOB 'ba[^t]*' ;
SELECT CAST(5 as integer) ;
SELECT CAST('5' as integer) ;
SELECT CAST('x' as integer) ;
SELECT CAST('1x' as integer) ;
SELECT 'ok' ;
SELECT 070 ;
CREATE TABLE t(a INTEGER) ;
INSERT INTO t VALUES(2) ;
INSERT INTO t VALUES(3) ;
INSERT INTO t VALUES(5) ;
INSERT INTO t VALUES(7) ;
SELECT 5 IN t ;
SELECT 4 IN t ;
SELECT COUNT(a) FROM t ;
SELECT AVG(a) FROM t ;
SELECT MAX(a) FROM t;
SELECT 14 | 5 ;
SELECT 14 & 5 ;
SELECT 14 >> 2 ;