Back to Cheatsheets

sql

Table of Contents

1. TABLE

2. BASICS

3. AGGREGATES

4. JOINS

TABLE

STATEMENT: A command, ends with ;

CLAUSE: a task of command

PARAMETER: list of columns/data types/values passed as an argument to a clause

KEYS

CREATE TABLE

CREATE TABLE name (
    id INTEGER PRIMARY KEY
    name TEXT DEFAULT 'text'    
);

INSERT INTO

INSERT INTO table (id, name, age)
VALUES (1, 'name', 22);

ALTER

ALTER TABLE table
ADD COLUMN name TEXT;

UPDATE

UPDATE
SET COLUMN = 'name'
WHERE column2 = #;

DELETE FROM

DELETE FROM table
WHERE column IS NULL;

CONSTRAINTS

BASICS

SELECT

SELECT DISTINCT name AS 'new name'
FROM table

WHERE

SELECT * 
FROM table
WHERE name ='name'

(Return all rows the name ‘name’)

LIKE

SELECT * 
FROM table
WHERE name LIKE '%man%'

(Return all names containing ‘man’)

BETWEEN

SELECT * 
FROM table
WHERE name BETWEEN 'A' AND 'C';

(Return: All names starting with A and B)

ORDER BY

SELECT name, age
FROM table
ORDER BY age;

CASE

SELECT name,
    CASE
        WHEN rating > 1 THEN 'text
        ELSE 'text2'
    END AS 'name2
FROM table;

STRFRAME

strframe(format, column)

REPLACE

REPLACE(column, from_string, to_string)

CAST

CAST(int1 AS REAL) / int2

AGGREGATES

AGGREGATES: calcs on multiples rows of tables

SELECT COUNT(*)
FROM table;

GROUP BY

SELECT name
FROM table
GROUP BY name;

HAVING

SELECT name, age
FROM table
GROUP BY age
HAVING age > 2;

JOINS

INNER JOIN

SELECT * 
FROM table1
JOIN table2 ON table1.id = table2.id;

LEFT JOIN

SELECT *
FROM table1
LEFT JOIN table2 ON table1.id = table2.id;

CROSS JOIN

SELECT name, COUNT(*)
FROM table 1
CROSS JOIN table2
WHERE start <= month AND end >= month
GROUP BY month;

(Return number of subscribers for each month)

UNION

SELECT *
FROM table1
UNION
SELECT *
FROM table2

INTERSECT

SELECT name
FROM table1
INTERSECT
SELECT name
FROM table2

EXCEPT

SELECT name
FROM table1
EXCEPT
SELECT name
FROM table2

WITH

WITH previous_results AS (
        SELECT *
        FROM table1
        WHERE......
)
SELECT *
FROM previous_results
JOIN table2 ON table2.id = previous_results.id;

ANALYSIS

MACHINE LEARNING