Brainbotox · Lessons · Exams

SQL Fundamentals for Beginners: SELECT, JOIN and GROUP BY

by lazizanie · Programming · Data & AI · SQL · English

Learn SQL from zero: relational databases, SELECT and WHERE, aggregates and GROUP BY, joins, INSERT, UPDATE, DELETE, and creating tables with constraints, with quizzes.

Study this lesson with its quizzes on Brainbotox →

What is SQL? Relational databases, tables and keys

SQL (Structured Query Language) is the standard language for reading and changing data stored in a relational database, where data is organised in tables made of rows and columns.

Tables, rows and columns

idnamecity
1AdaLondon
2BobParis

This is a table customers. Each row is one customer. Each column has a name and a data type.

Keys

A primary key is a column (or set of columns) that identifies each row uniquely and is never NULL. A foreign key is a column that refers to the primary key of another table, linking the two.

An orders table with a column customer_id pointing to customers.id says which customer placed each order.

Database systems

SQL runs on a relational database management system (RDBMS): PostgreSQL, MySQL, SQL Server, Oracle, SQLite. The core language is the same everywhere; each system adds its own extensions.

The families of SQL statements

FamilyStatementsPurpose
Query (DQL)SELECTRead data
Manipulation (DML)INSERT, UPDATE, DELETEChange rows
Definition (DDL)CREATE, ALTER, DROPChange the structure
Control (DCL)GRANT, REVOKEPermissions
Transactions (TCL)COMMIT, ROLLBACKConfirm or cancel changes

A first query

SELECT name, city
FROM customers
WHERE city = 'Paris';
  • SQL is declarative: you describe the result you want, and the database decides how to get it.
  • Keywords are not case-sensitive. Text values go in single quotes.
  • A statement ends with a semicolon.

Check yourself

  1. What is a primary key?
  2. What does a foreign key do?
  3. Which statement reads data?
  4. Which family do CREATE, ALTER and DROP belong to?
  5. How are text values written in standard SQL?
  6. SQL is declarative: you state what result you want, not how to compute it.

Take the quiz on Brainbotox

SQL SELECT, WHERE and ORDER BY

SELECT chooses the columns to return, WHERE filters the rows, and ORDER BY sorts the result.

Choosing columns

SELECT * FROM products;                       -- every column
SELECT name, price FROM products;             -- chosen columns
SELECT name, price * 1.2 AS price_with_tax FROM products;   -- computed, with an alias
SELECT DISTINCT category FROM products;       -- no duplicates
Avoid SELECT * in application code: list the columns you need.

Filtering with WHERE

OperatorExample
=, <>, <, >, <=, >=price >= 10
AND, OR, NOTprice > 10 AND stock > 0
INcategory IN ('book', 'game')
BETWEENprice BETWEEN 10 AND 20 (both ends included)
LIKEname LIKE 'A%' (% any text, _ one character)
IS NULLdiscount IS NULL
AND is evaluated before OR. Use parentheses: WHERE (a = 1 OR b = 2) AND c = 3.
A missing value is NULL. Test it with IS NULL or IS NOT NULL. discount = NULL never matches anything.

Sorting and limiting

SELECT name, price
FROM products
WHERE stock > 0
ORDER BY price DESC, name ASC
LIMIT 10;
  • ASC (ascending) is the default; DESC is descending.
  • Without ORDER BY, the order of rows is not guaranteed.
  • Limiting rows depends on the system: LIMIT 10 (PostgreSQL, MySQL, SQLite), TOP 10 (SQL Server), FETCH FIRST 10 ROWS ONLY (standard).

Check yourself

  1. Which clause filters rows?
  2. How do you test whether a column has no value?
  3. What does LIKE 'A%' match?
  4. What does SELECT DISTINCT do?
  5. Without ORDER BY, a database always returns rows in insertion order.
  6. Is price BETWEEN 10 AND 20 true for a price of 20?

Take the quiz on Brainbotox

SQL aggregate functions, GROUP BY and HAVING

An aggregate function computes one value from many rows, and GROUP BY splits the rows into groups so that the aggregate is computed once per group.

The aggregate functions

FunctionReturns
COUNT(*)The number of rows
COUNT(column)The number of rows where the column is not NULL
SUM, AVGTotal and average
MIN, MAXSmallest and largest value
SELECT COUNT(*) AS orders, SUM(total) AS revenue, AVG(total) AS average
FROM orders;

Aggregates ignore NULL values, except COUNT(*).

GROUP BY

SELECT customer_id, COUNT(*) AS orders, SUM(total) AS revenue
FROM orders
GROUP BY customer_id;
Every column in the SELECT list must either appear in GROUP BY or be inside an aggregate function.

HAVING

SELECT customer_id, SUM(total) AS revenue
FROM orders
WHERE status = 'paid'            -- filters rows, before grouping
GROUP BY customer_id
HAVING SUM(total) > 1000         -- filters groups, after grouping
ORDER BY revenue DESC;
WHERE cannot contain an aggregate: WHERE SUM(total) > 1000 is an error. Use HAVING.

The logical order of a query

  1. FROM (and joins)
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT
  6. ORDER BY
  7. LIMIT

This order explains why an alias defined in SELECT can be used in ORDER BY but not in WHERE.

Check yourself

  1. What is the difference between COUNT(*) and COUNT(email)?
  2. Which clause filters groups after aggregation?
  3. In a GROUP BY query, which columns may appear in SELECT?
  4. Which is evaluated first in the logical order?
  5. WHERE SUM(total) > 1000 is valid SQL.
  6. What does AVG do with NULL values?

Take the quiz on Brainbotox

SQL joins: INNER, LEFT, RIGHT and FULL

A join combines rows from two tables using a condition, usually that a foreign key equals a primary key.

INNER JOIN

SELECT c.name, o.id, o.total
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id;

Only customers that have orders appear, once per order. c and o are table aliases.

The join types

JoinReturns
INNER JOINOnly rows with a match in both tables
LEFT JOINAll rows of the left table; NULLs where the right table has no match
RIGHT JOINAll rows of the right table; NULLs where the left has no match
FULL JOINAll rows of both tables
CROSS JOINEvery combination of rows (rows of A times rows of B)

LEFT JOIN in practice

-- every customer, with the number of orders (0 if none)
SELECT c.name, COUNT(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name;
-- customers who have never ordered
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;
A condition on the right table placed in WHERE (for example WHERE o.status = 'paid') removes the NULL rows and turns a LEFT JOIN into an INNER JOIN. Put it in the ON clause to keep unmatched rows.

Joining several tables

SELECT c.name, p.name AS product, i.quantity
FROM customers c
JOIN orders o      ON o.customer_id = c.id
JOIN order_items i ON i.order_id = o.id
JOIN products p    ON p.id = i.product_id;
Forgetting the join condition produces a cross join: 1,000 rows joined to 1,000 rows give 1,000,000 rows.

Check yourself

  1. Which join returns only rows that have a match in both tables?
  2. In customers LEFT JOIN orders, what appears for a customer with no orders?
  3. How do you find customers with no orders using a LEFT JOIN?
  4. A CROSS JOIN of a 10-row table and a 20-row table returns how many rows?
  5. What is c in FROM customers AS c?
  6. Filtering the right table's columns in WHERE can make a LEFT JOIN behave like an INNER JOIN.

Take the quiz on Brainbotox

SQL INSERT, UPDATE, DELETE and transactions

INSERT adds rows, UPDATE changes existing rows, DELETE removes rows, and a transaction groups several changes so that they all succeed or all fail.

INSERT

INSERT INTO customers (name, city)
VALUES ('Ada', 'London');
INSERT INTO customers (name, city)
VALUES ('Bob', 'Paris'), ('Eve', 'Rome');     -- several rows
INSERT INTO archive (id, name)
SELECT id, name FROM customers WHERE city = 'Rome';

Always list the columns. Columns you leave out receive their default value or NULL.

UPDATE

UPDATE products
SET price = price * 1.1, updated_at = CURRENT_TIMESTAMP
WHERE category = 'book';

DELETE

DELETE FROM orders
WHERE status = 'cancelled';
An UPDATE or DELETE without WHERE affects every row of the table. Run the same condition as a SELECT first to see which rows will be touched.
DELETETRUNCATEDROP
RemovesChosen rowsAll rows, quicklyThe table itself
WHEREYesNoNo
Structure keptYesYesNo

Transactions

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;        -- make both changes permanent
-- or ROLLBACK; to cancel both
A transaction is atomic: money never leaves one account without arriving in the other. Until COMMIT, other sessions do not see the changes.

Many tools run in autocommit mode, where each statement is its own transaction.

Check yourself

  1. What happens when you run UPDATE products SET price = 0; with no WHERE?
  2. Which statement removes the table itself?
  3. What does ROLLBACK do?
  4. Why wrap a money transfer in a transaction?
  5. What value does an omitted column receive in an INSERT?
  6. TRUNCATE TABLE accepts a WHERE clause.

Take the quiz on Brainbotox

SQL CREATE TABLE, data types, constraints and NULL

CREATE TABLE defines a table's columns, their data types, and constraints: rules that the database enforces on every row.

Creating tables

CREATE TABLE customers (
    id         INTEGER PRIMARY KEY,
    email      VARCHAR(255) NOT NULL UNIQUE,
    name       VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE orders (
    id          INTEGER PRIMARY KEY,
    customer_id INTEGER NOT NULL REFERENCES customers(id),
    total       DECIMAL(10, 2) NOT NULL CHECK (total >= 0),
    status      VARCHAR(20) DEFAULT 'new'
);

Common data types

TypeHolds
INTEGER, BIGINTWhole numbers
DECIMAL(10, 2)Exact decimals: 10 digits, 2 after the point. Use for money
VARCHAR(n), TEXTText
DATE, TIMESTAMPDates and date-times
BOOLEANTrue or false

Constraints

ConstraintRule
PRIMARY KEYUnique and not NULL; one per table
FOREIGN KEY / REFERENCESThe value must exist in the referenced table
NOT NULLA value is required
UNIQUENo duplicates
CHECKA condition that must hold
DEFAULTThe value used when none is given

Changing the structure

ALTER TABLE customers ADD COLUMN phone VARCHAR(30);
ALTER TABLE customers DROP COLUMN phone;
DROP TABLE orders;

NULL and three-valued logic

NULL means "unknown" or "missing". Any comparison with NULL gives unknown, not true or false, and WHERE keeps only rows where the condition is true.
SELECT NULL = NULL;                 -- unknown, not true
SELECT COALESCE(phone, 'none') FROM customers;   -- first non-NULL value
SELECT 10 + NULL;                   -- NULL

Check yourself

  1. Which type is appropriate for money amounts?
  2. What does a FOREIGN KEY constraint enforce?
  3. What is the result of NULL = NULL?
  4. What does COALESCE(a, b) return?
  5. Which constraint rejects duplicate values but allows the column not to be the key?
  6. Which statement adds a column to an existing table?

Take the quiz on Brainbotox