SQL Fundamentals for Beginners: SELECT, JOIN and GROUP BY
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
| id | name | city |
|---|---|---|
| 1 | Ada | London |
| 2 | Bob | Paris |
This is a table customers. Each row is one customer. Each column has a name and a data type.
Keys
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
| Family | Statements | Purpose |
|---|---|---|
| Query (DQL) | SELECT | Read data |
| Manipulation (DML) | INSERT, UPDATE, DELETE | Change rows |
| Definition (DDL) | CREATE, ALTER, DROP | Change the structure |
| Control (DCL) | GRANT, REVOKE | Permissions |
| Transactions (TCL) | COMMIT, ROLLBACK | Confirm 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
- What is a primary key?
- What does a foreign key do?
- Which statement reads data?
- Which family do CREATE, ALTER and DROP belong to?
- How are text values written in standard SQL?
- SQL is declarative: you state what result you want, not how to compute it.
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
SELECT * in application code: list the columns you need.Filtering with WHERE
| Operator | Example |
|---|---|
=, <>, <, >, <=, >= | price >= 10 |
AND, OR, NOT | price > 10 AND stock > 0 |
IN | category IN ('book', 'game') |
BETWEEN | price BETWEEN 10 AND 20 (both ends included) |
LIKE | name LIKE 'A%' (% any text, _ one character) |
IS NULL | discount IS NULL |
AND is evaluated before OR. Use parentheses: WHERE (a = 1 OR b = 2) AND c = 3.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;DESCis 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
- Which clause filters rows?
- How do you test whether a column has no value?
- What does LIKE 'A%' match?
- What does SELECT DISTINCT do?
- Without ORDER BY, a database always returns rows in insertion order.
- Is price BETWEEN 10 AND 20 true for a price of 20?
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
| Function | Returns |
|---|---|
COUNT(*) | The number of rows |
COUNT(column) | The number of rows where the column is not NULL |
SUM, AVG | Total and average |
MIN, MAX | Smallest 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;
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
FROM(and joins)WHEREGROUP BYHAVINGSELECTORDER BYLIMIT
This order explains why an alias defined in SELECT can be used in ORDER BY but not in WHERE.
Check yourself
- What is the difference between COUNT(*) and COUNT(email)?
- Which clause filters groups after aggregation?
- In a GROUP BY query, which columns may appear in SELECT?
- Which is evaluated first in the logical order?
- WHERE SUM(total) > 1000 is valid SQL.
- What does AVG do with NULL values?
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
| Join | Returns |
|---|---|
INNER JOIN | Only rows with a match in both tables |
LEFT JOIN | All rows of the left table; NULLs where the right table has no match |
RIGHT JOIN | All rows of the right table; NULLs where the left has no match |
FULL JOIN | All rows of both tables |
CROSS JOIN | Every 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;
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;
Check yourself
- Which join returns only rows that have a match in both tables?
- In customers LEFT JOIN orders, what appears for a customer with no orders?
- How do you find customers with no orders using a LEFT JOIN?
- A CROSS JOIN of a 10-row table and a 20-row table returns how many rows?
- What is c in FROM customers AS c?
- Filtering the right table's columns in WHERE can make a LEFT JOIN behave like an INNER JOIN.
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';
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.| DELETE | TRUNCATE | DROP | |
|---|---|---|---|
| Removes | Chosen rows | All rows, quickly | The table itself |
| WHERE | Yes | No | No |
| Structure kept | Yes | Yes | No |
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
COMMIT, other sessions do not see the changes.Many tools run in autocommit mode, where each statement is its own transaction.
Check yourself
- What happens when you run UPDATE products SET price = 0; with no WHERE?
- Which statement removes the table itself?
- What does ROLLBACK do?
- Why wrap a money transfer in a transaction?
- What value does an omitted column receive in an INSERT?
- TRUNCATE TABLE accepts a WHERE clause.
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
| Type | Holds |
|---|---|
INTEGER, BIGINT | Whole numbers |
DECIMAL(10, 2) | Exact decimals: 10 digits, 2 after the point. Use for money |
VARCHAR(n), TEXT | Text |
DATE, TIMESTAMP | Dates and date-times |
BOOLEAN | True or false |
Constraints
| Constraint | Rule |
|---|---|
PRIMARY KEY | Unique and not NULL; one per table |
FOREIGN KEY / REFERENCES | The value must exist in the referenced table |
NOT NULL | A value is required |
UNIQUE | No duplicates |
CHECK | A condition that must hold |
DEFAULT | The 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
- Which type is appropriate for money amounts?
- What does a FOREIGN KEY constraint enforce?
- What is the result of NULL = NULL?
- What does COALESCE(a, b) return?
- Which constraint rejects duplicate values but allows the column not to be the key?
- Which statement adds a column to an existing table?