SQL chapters

Chapter 16 of 17

SQL Syntax Cheatsheet

Try this in our SQLite Compiler →

Everything in one place

Use this chapter as a quick reference once you've worked through the rest of the course. It collects every core construct of SQL into runnable, copy-pasteable snippets you can scan whenever you forget the exact syntax.

Hello world & variables

```sql
SELECT 'Hello, World!' AS greeting;

-- Most databases let you declare variables inside scripts: DECLARE @name VARCHAR(50) = 'Aman'; SELECT @name; ```

Data types & operators

```sql
CREATE TABLE users (
  id INT PRIMARY KEY,
  name VARCHAR(100),
  age INT,
  joined DATE,
  active BOOLEAN
);

SELECT * FROM users WHERE age >= 18 AND active = TRUE AND name LIKE 'A%'; ```

Conditionals & loops

```sql
SELECT name,
  CASE
    WHEN age >= 18 THEN 'Adult'
    ELSE 'Minor'
  END AS category
FROM users;

-- Pure SQL is set-based, not loop-based. -- Most work is done by applying a single statement to every matching row: UPDATE users SET active = FALSE WHERE last_login < '2024-01-01'; ```

Functions & arrays

```sql
CREATE FUNCTION full_name(first VARCHAR, last VARCHAR)
RETURNS VARCHAR AS $$
  SELECT first || ' ' || last;
$$ LANGUAGE SQL;

SELECT full_name('Aman', 'Singh');

-- Aggregate functions summarise many rows into one: SELECT COUNT(*), AVG(age), MAX(age) FROM users WHERE active = TRUE; ```

Strings & objects

```sql
SELECT UPPER(name), LENGTH(name), name || '@playlearn.io'
FROM users
WHERE name LIKE '%a%';

-- A table is the SQL equivalent of an object/record collection: INSERT INTO users (id, name, age, active) VALUES (1, 'Aman', 20, TRUE);

SELECT * FROM users WHERE id = 1; ```

Errors, modules & I/O

```sql
-- Wrap risky multi-statement work in a transaction:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;  -- or ROLLBACK on error

-- Views are reusable named queries: CREATE VIEW active_users AS SELECT id, name FROM users WHERE active = TRUE;

SELECT * FROM active_users;

-- Read: SELECT * FROM users WHERE age >= 18;

-- Write: INSERT INTO users (name, age) VALUES ('Aman', 20); UPDATE users SET age = 21 WHERE name = 'Aman'; DELETE FROM users WHERE active = FALSE; ```

How to use this page

Bookmark it. When you start a new project, open this cheatsheet alongside your editor and use it as a syntax lookup. Once a construct becomes second nature you'll stop needing the reference for it — and that's exactly when you know you've mastered that part of SQL.

Try it yourself

SQLite Compiler
Output
Code runs on the Play with Coding execution engine — your code is saved locally for next time.