SQL Basics

Create tables and write queries — SELECT, WHERE, ORDER BY, LIMIT, aggregates and GROUP BY/HAVING, INSERT/UPDATE/DELETE, NULL semantics and logical query order.

Beginner 3 min readLesson 2 of 14 Interview Q&A

SQL (Structured Query Language) is how you talk to relational databases: PostgreSQL, MySQL, SQLite, SQL Server, Oracle, and analytical engines like BigQuery, Snowflake and DuckDB. It's declarative: you describe the result and the database figures out how to compute it.

We'll use this schema throughout the SQL lessons:

SQL
CREATE TABLE employees (
    id         SERIAL PRIMARY KEY,
    name       TEXT NOT NULL,
    dept       TEXT,
    salary     NUMERIC(10, 2),
    manager_id INT REFERENCES employees(id),
    hired_on   DATE
);

SELECT: reading data

SQL
SELECT name, salary
FROM employees
WHERE dept = 'Engineering' AND salary > 100000
ORDER BY salary DESC
LIMIT 10;
ClauseDoes
SELECTWhich columns (or expressions) to return; * for all
FROMWhich table(s)
WHEREFilter rows
ORDER BYSort (ASC default, DESC)
LIMIT / OFFSETReturn only some rows (FETCH FIRST n ROWS in standard SQL, TOP in SQL Server)
DISTINCTRemove duplicate rows

Useful operators in WHERE:

SQL
WHERE salary BETWEEN 50000 AND 80000
WHERE dept IN ('Sales', 'Marketing')
WHERE name LIKE 'A%'            -- starts with A (ILIKE: case-insensitive in Postgres)
WHERE manager_id IS NULL        -- never "= NULL"!
WHERE hired_on >= DATE '2024-01-01'

NULL: the unknown value

NULL means "unknown" or "missing", and it follows three-valued logic: comparisons with NULL yield UNKNOWN, which WHERE treats as false.

ExpressionResult
NULL = NULLUNKNOWN (not true!)
NULL <> 5UNKNOWN
NULL AND FALSEFALSE
NULL OR TRUETRUE
salary + NULLNULL
SQL
SELECT * FROM employees WHERE dept <> 'Sales';
-- Rows with dept = NULL are NOT returned! Add: OR dept IS NULL

SELECT COALESCE(dept, 'Unassigned') FROM employees;   -- first non-null value

Aggregates and GROUP BY

SQL
SELECT dept,
       COUNT(*)            AS headcount,
       AVG(salary)         AS avg_salary,
       MAX(salary)         AS top_salary
FROM employees
WHERE hired_on >= '2020-01-01'
GROUP BY dept
HAVING COUNT(*) >= 5
ORDER BY avg_salary DESC;
  • COUNT(*) counts rows; COUNT(col) counts non-null values; COUNT(DISTINCT col) counts distinct ones.
  • Aggregates (SUM, AVG, MIN, MAX) ignore NULLs.
  • Every non-aggregated column in SELECT must appear in GROUP BY.
  • WHERE filters rows before grouping; HAVING filters groups after aggregation.

Logical order of evaluation

SQL is written in one order but evaluated (logically) in another, which explains many errors such as "column alias doesn't exist in WHERE":

  1. FROM / JOIN — build the working set of rows
  2. WHERE — filter rows
  3. GROUP BY — form groups
  4. HAVING — filter groups
  5. SELECT — compute output columns and aliases
  6. DISTINCT
  7. ORDER BY — can use aliases
  8. LIMIT / OFFSET

Modifying data

SQL
INSERT INTO employees (name, dept, salary, hired_on)
VALUES ('Ada', 'Engineering', 150000, '2024-03-01'),
       ('Alan', 'Research', 140000, '2024-04-15')
RETURNING id;                                   -- Postgres: get generated ids back

UPDATE employees
SET salary = salary * 1.05
WHERE dept = 'Engineering';

DELETE FROM employees WHERE hired_on < '2000-01-01';

-- Upsert: insert or update on conflict
INSERT INTO employees (id, name, salary) VALUES (7, 'Grace', 160000)
ON CONFLICT (id) DO UPDATE SET salary = EXCLUDED.salary;   -- MySQL: ON DUPLICATE KEY UPDATE

From application code: always parameterise

String sql = "SELECT id, name FROM employees WHERE dept = ? AND salary > ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setString(1, dept);
    ps.setBigDecimal(2, minSalary);
    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) System.out.println(rs.getLong("id") + " " + rs.getString("name"));
    }
}

DDL: changing structure

SQL
ALTER TABLE employees ADD COLUMN email TEXT;
ALTER TABLE employees ALTER COLUMN dept SET NOT NULL;
CREATE INDEX idx_employees_dept ON employees (dept);
DROP TABLE IF EXISTS temp_import;

In production, schema changes go through migration tools (Flyway, Liquibase, Alembic, Prisma Migrate) so every environment changes in the same versioned way. Large tables need care: some ALTERs lock or rewrite the whole table.

Key takeaways
  • SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY … LIMIT.
  • NULL is unknown: use IS NULL, COALESCE, and avoid NOT IN with nullable columns.
  • WHERE filters rows; HAVING filters groups.
  • Logical order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
  • Always use parameterised queries; test UPDATE/DELETE predicates first.
Interview questions
QWhat's the difference between WHERE and HAVING?easy

WHERE filters individual rows before grouping and can't use aggregates. HAVING filters groups after GROUP BY and can use aggregates, e.g. HAVING COUNT(*) > 5.

QFind the second-highest salary.medium

SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees); or, generally for the nth: SELECT DISTINCT salary FROM employees ORDER BY salary DESC OFFSET 1 LIMIT 1; or DENSE_RANK() in a window function.