SQL
SQLite Helper
-- SQLite helper functions
.tables -- get table names
.schema -- get all tables' column names
.schema table_name -- get column names for special table.
.read script_name -- run a script
SELECT
SELECT *
SELECT column1[, column2, ...]
-- DISTINCT: Only return distinct results.
-- distinct rows means there is at least ONE difference selected
-- columns in those rows.
SELECT DISTINCT A, B
-- concat string & alias
SELECT TRIM(KEY_A) || '_' || LTRIM(KEY_B) AS KEY_AB
-- numeric calculating. operator: +, -, *, /
-- numeric function: ABS COS EXP PI SIN SQRT TAN
-- string function: LEFT RIGHT LOWER UPPER LTRIM RTRIM TRIM LENGHT
-- data function: DATAPART
SELECT NUM_KEY_A + NUM_KEY_B AS NKEY_AB
WHERE age > 40; -- number
-- number operators: =, >, <, >=, <=, <> or !=
WHERE name = 'Alice'; -- 'string'
WHERE condition1 AND/OR condition2;
WHERE NOT condition1;
WHERE condition1 AND (condition2 OR condition3);
WHERE
name LIKE 'a%'; -- all name begin with 'a'
name LIKE '%b'; -- all name end with b
name LIKE '%center%'; -- all name contain center
name LIKE '_pple' -- '_' for any single char
name LIKE '[Aa]pple' -- '[Aa]' for a or A
-- aggregate functions (COUNT, MAX, MIN, SUM, AVG)
-- and GROUP BY struct
SELECT COUNT(CustomerID), Country
-- or SELECT COUNT(DISTINCT CustomerID), Country
FROM Customers
WHERE CustomerID >= '50' AND CustomerID <= 60
GROUP BY Country
-- HAVING struct filter groups. just like WHERE struct.
HAVING COUNT(CustomerID) > 2;
SUB QUERY
SELECT key_a FROM table_a
WHERE key_b in (
SELECT key_b FROM table_b WHERE key_c == 'c'
);
SELECT key_a, (
SELECT COUNT(*) FROM table_b WHERE table_b.key_b == table_a.key_b
) as table_b_count
FROM table_a;
INNER JOIN
SELECT key_a, key_b
FROM table_a INNER JOIN table_b ON table_a.key_a = table_b.key_a
-- or --
SELECT key_a, key_b
FROM table_a, table_b
WHERE table_a.key_a = table_b.key_a
-- cartesian product between rows meeting WHERE conditions
-- in table_a and table_b.
UNION
-- In UNION struct the keys should be the same.
SELECT key_a, key_b FROM ... WHERE ...
UNION [ALL]
SELECT key_a, key_b FROM ... WHERE ...
INSERT INTO
-- use INSERT INTO to add lines to an exist table.
INSERT INTO tab_a(key_a, key_b, ...)
VALUES(val_a, val_b, ...);
INSERT INTO tab_a(key_a, key_b, ...)
SELECT key_a, key_b, ...
FROM tab_b;
-- key name is not important but
-- the data type must be compatible.
-- use SELECT INTO to create a new table.
SELECT key_a, key_b, ...
INTO tab_a_copy
FROM tab_a;
UPDATE / DELETE
UPDATE tab_a
SET key_a = val_a
WHERE conditions...;
-- without WHERE, UPDATE will set every line in the table.
DELETE FROM tab_a
WHERE conditions...;
-- remove lines. without WHERE, DELETE will clear the table.
CREATE TABLE / DROP TABLE
CREATE TABLE tab_a(
key_a type_a NULL DEFAULT val_a PRIMARY KEY,
-- or CONSTRAINT alter_name PRIMARY KEY (key_a, key_b)
key_b type_b NOT NULL DEFAULT val_b
)
-- remove table
DROP TABLE tab_a;
VIEW
CREATE VIEW view_a AS
SELECT key_a ...
...;
-- VIEW can be used like table