Back to the catalogue Courses

Relational databases: from business need to reliable queries

Design a coherent schema, write reliable SQL queries and evolve a database without losing data integrity.

MDJAD Intermediate 36 min read

Objectives and prerequisites

By the end of this course, you will be able to turn a business requirement into a coherent relational schema, write readable SQL queries and verify their results, then evolve a database without losing data integrity. The common thread is a small sales activity: customers place orders, each order contains product lines, and the team must report revenue, correct an address and archive old data.

Prerequisites: you can use a terminal, read a simple SQL statement and edit a text file. The examples use MariaDB 10.6, the version available at the project's host, with the InnoDB engine. Useful differences with PostgreSQL and MySQL are pointed out. Install a local laboratory database: never work on a production database to learn, and never drop a table without a verified backup.

Path: chapters 1 to 5 build the model and schema; chapters 6 to 9 cover reading and writing; chapters 10 to 12 cover transactions, indexes, permissions, backups and migrations. Expect about thirty-five minutes of reading and four to six hours of guided practice. Each chapter ends with a check you can reproduce, and the exercises run on a database you can destroy without consequences.

Convention: SQL blocks run in order on an empty database named boutique_lab. Names and amounts are fictional. Dates are stored in UTC and displayed in the application's time zone. Administrative commands are shown separately, because they do not belong to the same role as business queries.

1. Persistence, tables and the relational model

A relational database organises information into tables. A table has columns, each with a type, and rows that represent occurrences. A primary key identifies each row uniquely. A foreign key links a row in one table to a row in another. The relational model does not only say where to store data: it defines constraints that make certain states impossible.

Persistence means data survives the program stopping. A text file can persist, but it guarantees neither concurrent access, nor integrity, nor declarative queries. A relational database provides a query language, transactions, constraints and recovery mechanisms. These guarantees have a cost: you must design the schema, choose types, manage migrations and monitor performance.

A database is not a bag of data. The schema expresses business rules: an order belongs to a customer, an order line references a product, an amount cannot be negative, an email address may be unique. The closer these rules are to the data, the harder they are to bypass. A rule that exists only in the interface will sooner or later be bypassed by an import, a script or another application.

-- A minimal table, with a primary key and a constraint
CREATE TABLE customers (
    id          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    name        VARCHAR(120) NOT NULL,
    email       VARCHAR(190) NOT NULL,
    created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uq_customers_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

The engine matters. InnoDB supports transactions, foreign keys and row locking; MyISAM does not. On MariaDB 10.6, InnoDB is the default and should remain the choice for application data. The utf8mb4 character set covers full Unicode, including emojis and some Comorian characters; MySQL's historical utf8 alias covers only three bytes.

A technical identifier, or surrogate key, is often an auto-incremented integer or a UUID. A natural key, such as a customer code, can also serve if it is genuinely stable and unique. Both approaches have consequences: an integer is compact and fast, a UUID simplifies distributed generation but uses more space and fragments indexes. Choose deliberately, document the choice and do not change the key without a planned migration.

The table is not the only useful structure. Views present a query as a virtual table, indexes speed up certain reads, constraints protect integrity and transactions group operations. A successful relational model is not about multiplying tables: it is about placing each fact in the right place, with the constraints that prevent inconsistency.

Finally, distinguish the conceptual model from the physical schema. The conceptual model describes entities and relationships in business language; the physical schema specifies types, indexes, engines and names. The two must remain aligned, but they are not the same. Good modelling is discussed with the business before being translated into CREATE TABLE.

The schema also has an owner. Decide who may modify it, who approves a migration and who responds during an incident. A schema changed by several people without review ends up with forgotten columns, contradictory constraints and inconsistent types. Document naming conventions, units (amounts before or after tax, dates in UTC or local time) and deletion rules. These decisions look administrative, but they prevent ambiguities that queries cannot resolve on their own.

Views help expose a stable reading surface without duplicating data. A view can hide complex joins, restrict columns for a reporting role, or present a simplified name for a legacy table. It does not store data and does not replace access control: a user with access to the underlying tables can bypass it. Use views for clarity and controlled interfaces, and grant privileges on the view only when the database supports it safely. Document which views are part of the public contract.

Keep a data dictionary alongside the schema: table purpose, column meaning, unit, nullability, allowed values and owner. An entity-relationship diagram helps new team members, but it ages quickly if it is drawn once and never updated. Generate what you can from information_schema, then annotate the business meaning that the database cannot express. The dictionary is also the place to record deprecated columns and the migration that will remove them.

2. From business need to schema

Start from the questions the application must answer: which customers ordered this month, what is an order's total, which product sells best, which order is still unpaid. These questions reveal the necessary entities and relationships. An entity is an identifiable business object: customer, order, product, payment. A relationship links two entities: a customer places several orders, an order contains several products.

Cardinalities describe how many occurrences may participate in a relationship. A customer may place zero, one or several orders; an order belongs to exactly one customer. A product may appear in several order lines; an order line references exactly one product. These seemingly simple sentences determine foreign keys, uniqueness constraints and deletion rules.

A customer may have several addresses, and an order must keep the address used at purchase time. If the order is linked only to the customer's current address, a later change alters history. You must therefore copy the necessary information into the order, or create an immutable address version. This choice illustrates an important rule: history and current state do not always share the same structure.

Customer 1 ─── 0..N Order
Order 1 ─── 1..N OrderLine
Product 1 ─── 0..N OrderLine
Order 1 ─── 0..N Payment

Business rules:
- an order has exactly one customer;
- an order line has exactly one order and one product;
- the unit price is copied into the line when the order is placed;
- a validated order cannot be deleted, only cancelled.

Price is a good example of data to version. The product has a current price, but the order line must keep the price applied. Otherwise a price increase would retroactively change revenue. The line therefore contains unit_price, quantity and possibly a discount. The line total is calculated, or stored if the calculation rules are complex and must be frozen.

Many-to-many associations are not stored directly in a table without thought. An order contains several products, and a product appears in several orders: the order_lines table carries the relationship and the attributes specific to it, such as quantity and price. This join table is not a technical detail; it is a business entity in its own right.

Before writing the schema, describe the rules and exceptions. What happens if a customer is deleted? If a product is removed from the catalogue? If an order is validated then cancelled? The answers determine foreign key actions, status columns and constraints. A schema that ignores these questions forces the application to handle inconsistent cases for years.

Finally, validate the model with concrete examples, including edge cases: a customer with no orders, an order with no payment, a product never sold, a cancelled order. If the model cannot represent a legitimate case, an entity or relationship is missing. If it allows a forbidden case, a constraint is missing. This review costs less than later data corrections.

A business glossary prevents misunderstandings. "Order" may mean a basket in progress, a validated order or an invoice; "customer" may mean a person, a household or a company. The schema must choose one meaning and stick to it. Synonyms used by the business can be documented as aliases, but they must not create two tables for the same fact. When a term is ambiguous, ask before creating the column, not after importing the data.

Multi-valued attributes deserve a dedicated table. A customer may have several phone numbers, several contacts or several addresses; storing them in a comma-separated column makes searching, updating and validation difficult. A phones table with a foreign key to customers allows indexing, constraints and clean deletion. The same rule applies to tags, roles and preferences. A list in a column is sometimes acceptable for a purely documentary field, never for data that must be queried.

Distinguish optional from mandatory relationships. A customer may exist without an order, but an order cannot exist without a customer; the foreign key on orders.customer_id is therefore NOT NULL. A payment may be optional at first, so the relationship from order to payment is optional. These choices affect the application: a mandatory relationship requires a valid parent before insertion, while an optional one allows a temporary incomplete state that must be handled explicitly.

3. Types, keys and constraints

A column's type defines accepted values and space used. INT suits small integers, BIGINT identifiers likely to grow, DECIMAL(10,2) exact amounts, VARCHAR(n) variable-length strings, DATE and DATETIME dates. FLOAT and DOUBLE are approximate: do not use them for amounts.

The choice of VARCHAR length is not neutral. Too short a length truncates or rejects legitimate data; an excessive length hides the real need and may affect indexes. Account for encoding: with utf8mb4, an index on a long column can exceed the size limit. Measure real needs and allow a reasonable margin.

CREATE TABLE products (
    id            BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    reference     VARCHAR(40) NOT NULL,
    label         VARCHAR(160) NOT NULL,
    price_excl_tax DECIMAL(10,2) NOT NULL,
    active        BOOLEAN NOT NULL DEFAULT TRUE,
    created_at    DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uq_products_reference (reference),
    CONSTRAINT chk_products_price CHECK (price_excl_tax >= 0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

A primary key must be unique, non-null and stable. It may be simple or composite. A foreign key must reference a primary or unique key of the target table, and its type must match. Uniqueness can be enforced by a UNIQUE constraint; note that SQL allows several NULL values in a unique column, because NULL is not equal to NULL.

NOT NULL, CHECK, UNIQUE and FOREIGN KEY constraints express rules. A CHECK constraint is verified on write; MariaDB has enforced it since version 10.2, but older versions ignored it. Always verify your version's behaviour. A disabled or unenforced constraint gives a false sense of security.

Referential actions determine what happens on deletion or update. RESTRICT prevents the operation, CASCADE propagates it, SET NULL sets the key to NULL. CASCADE is convenient but dangerous: deleting a customer may delete their orders and payments without confirmation. Prefer a logical deletion, a deleted_at column, or deactivation, and reserve CASCADE for dependencies genuinely owned.

Unique indexes play a special role: they guarantee uniqueness and speed up lookup. A UNIQUE index on email prevents two accounts from using the same address, but comparison depends on collation. A case-insensitive collation treats A@example.com and a@example.com as equal; a case-sensitive collation distinguishes them. Choose according to the business rule, not by accident.

Finally, document constraints that cannot be expressed in SQL, such as "a validated order cannot be modified" or "a payment cannot exceed the total". They will be enforced by the application or by triggers, with tests. An honest schema states its limits instead of suggesting the database guarantees everything.

Dates deserve an explicit convention. DATETIME stores no time zone; TIMESTAMP converts according to the session time zone and has a narrower range. For a business event, store an instant in UTC and display it in the user's time zone. For a civil date, such as a birth date or a deadline, use DATE and avoid any time zone conversion. Mixing the two in one column produces errors that appear only at a daylight-saving change or during travel.

Name your constraints. A generated name such as orders_chk_1 is hard to recognise in an error or a migration. Explicit names, such as chk_orders_total_non_negative, make failures understandable and allow a migration to drop or alter the right constraint. Keep a naming convention for primary keys, foreign keys, unique keys and checks. The few seconds spent naming a constraint save hours when a production error mentions it.

4. Normalisation and anomalies

Normalisation organises columns to avoid repetition and inconsistency. First normal form requires atomic values: no list of products in a single column, no comma-separated phone numbers. Second normal form requires every non-key column to depend on the whole primary key, not only part of it. Third normal form requires a non-key column not to depend on another non-key column.

A classic counter-example is an orders table containing the customer name, address and product name. If a customer changes address, every order must be updated; if an order contains several products, customer information is repeated. These repetitions create update, insertion and deletion anomalies. Decomposition into customers, orders and lines removes them.

Unnormalised table:
order(id, customer_name, customer_address, product_name, product_price, quantity)

Anomalies:
- update: changing the customer's address requires modifying several rows;
- insertion: impossible to add a customer without an order;
- deletion: deleting the last order erases customer information.

Decomposition:
customers(id, name, address)
orders(id, customer_id, date)
products(id, name, price)
order_lines(order_id, product_id, quantity, unit_price)

Normalisation is not an end in itself. Controlled denormalisation can help performance or freeze history, but it must be justified and maintained. Storing an order total avoids recalculation on every read; you must then guarantee consistency through a transaction or verified recalculation. Denormalised data without an update mechanism becomes a competing, contradictory source of truth.

Third normal form does not forbid all redundancy. A postal code and a city may be separate or grouped according to use. A historical price in an order line is deliberate redundancy, because it represents a past fact. The question is not "is there repetition?" but "can this repetition diverge from reality?". If so, a synchronisation rule is needed.

Normalisation also helps name things. A table should represent one kind of fact. If a table mixes customers and suppliers, or orders and invoices, columns become conditional and constraints weak. Two tables with an explicit relationship are often better than a polymorphic table that is hard to constrain. The model must remain understandable to someone discovering the project.

Finally, normalisation is verified with questions: what happens if I delete this row? Can I represent a customer without an order? Can I have the same product twice in an order? The answer reveals dependencies and missing constraints. A normalised schema is not only "cleaner": it makes anomalies impossible or expensive to produce.

Normalisation does not remove the need to think about historical data. A price, an address or a status may change over time; if only the current value is kept, the ability to explain a past decision is lost. History tables, version columns and audit logs meet this need, but they increase volume and complexity. Choose the facts that must be frozen — applied price, delivery address, accepted terms — and let the others evolve in current tables.

Beyond third normal form, fourth normal form addresses independent multi-valued dependencies. If a table stores both a customer's phone numbers and their delivery preferences, the two lists are independent and combining them multiplies rows. Splitting them into separate tables removes the artificial relationship. Most business schemas stop at third normal form, but recognising this pattern prevents subtle duplication when several lists are attached to the same entity.

5. Creating the schema and sample data

Create the database, tables and constraints in a versioned script. A script executable from an empty database lets you reproduce the environment, train someone and test a migration. Avoid untracked manual changes: they make environments differ and incidents hard to reproduce.

CREATE DATABASE boutique_lab CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE boutique_lab;

CREATE TABLE customers (
    id      BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    name    VARCHAR(120) NOT NULL,
    email   VARCHAR(190) NOT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uq_customers_email (email)
) ENGINE=InnoDB;

CREATE TABLE orders (
    id          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    customer_id BIGINT UNSIGNED NOT NULL,
    status      VARCHAR(20) NOT NULL DEFAULT 'draft',
    created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_orders_customer (customer_id),
    CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (id)
) ENGINE=InnoDB;

CREATE TABLE products (
    id        BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    reference VARCHAR(40) NOT NULL,
    label     VARCHAR(160) NOT NULL,
    price_excl_tax DECIMAL(10,2) NOT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uq_products_reference (reference),
    CONSTRAINT chk_products_price CHECK (price_excl_tax >= 0)
) ENGINE=InnoDB;

CREATE TABLE order_lines (
    order_id     BIGINT UNSIGNED NOT NULL,
    product_id   BIGINT UNSIGNED NOT NULL,
    quantity     INT UNSIGNED NOT NULL,
    unit_price   DECIMAL(10,2) NOT NULL,
    PRIMARY KEY (order_id, product_id),
    CONSTRAINT fk_lines_order FOREIGN KEY (order_id) REFERENCES orders (id),
    CONSTRAINT fk_lines_product FOREIGN KEY (product_id) REFERENCES products (id),
    CONSTRAINT chk_lines_quantity CHECK (quantity > 0)
) ENGINE=InnoDB;

The script must be idempotent or accompanied by a reset script. For a laboratory, DROP DATABASE IF EXISTS then CREATE DATABASE is acceptable; in production, never. Sample data must be reproducible and realistic: a few customers, several orders, active and inactive products, an order without payment. It serves to verify joins and aggregates, not to impress.

INSERT INTO customers (name, email) VALUES
('Amina Said', 'amina@example.test'),
('Youssouf Ali', 'youssouf@example.test'),
('Naila Madi', 'naila@example.test');

INSERT INTO products (reference, label, price_excl_tax) VALUES
('PENCIL-01', 'Graphite pencil', 1.20),
('NOTE-A5', 'A5 notebook, 96 pages', 3.50),
('LAMP-LED', 'LED desk lamp', 24.90);

INSERT INTO orders (customer_id, status) VALUES
(1, 'validated'), (1, 'draft'), (2, 'validated');

INSERT INTO order_lines (order_id, product_id, quantity, unit_price) VALUES
(1, 1, 10, 1.20), (1, 2, 4, 3.50),
(2, 3, 1, 24.90),
(3, 2, 2, 3.50), (3, 3, 1, 24.90);

Sample data must remain small but cover edge cases: a customer with no order, an order with no line, a product never sold, a quantity of one, a zero amount if the rule allows it. Without these cases, queries look correct on an overly uniform set. Also add accented characters and an emoji to verify encoding.

Version the creation script and a separate data script. The first describes structure, the second demonstration content. In production, the demonstration data script must never run. Migrations are versioned and applied in a controlled way; we return to them in chapter 12.

Verify the schema with SHOW CREATE TABLE and constraints with information_schema. A schema may look correct in the script and differ from the real database after a manual change. Compare, correct and document. Reproducibility is the basis of trust: if you cannot recreate the database, you cannot guarantee what it contains.

Separate environments. The laboratory can be reset at will; staging should resemble production in engine version, encoding and constraints; production never receives demonstration data. A creation script run in a different environment may succeed while producing different behaviour, for example if the SQL mode is more permissive. Compare server version, character set, collation and security settings before concluding that a test is representative.

Version the dataset with the schema, but in a separate file. Explicit identifiers make tests reproducible; auto-increments may differ after several runs. If you use fixed identifiers, check that sequences are reset or that later inserts do not collide. For automated tests, create a dedicated database, apply the schema, load data, run assertions, then destroy the database. A test depending on a shared database eventually becomes flaky and hides regressions.

Seeding must be idempotent if it runs more than once. Use explicit identifiers with INSERT ... ON DUPLICATE KEY UPDATE, or delete and recreate the laboratory database each time. A seed that inserts duplicates silently makes tests unreliable. Record the seed version and the date, and verify row counts after loading. In production, demonstration seeds are forbidden; reference data, such as countries or statuses, may be seeded through a controlled migration instead.

6. SELECT, filters, ordering and NULL

SELECT reads columns and rows. WHERE filters rows, ORDER BY sorts them, LIMIT caps their number. A readable query names columns explicitly rather than using *, especially in application code: an added column must not silently change the result. Ordering must be stable: add a unique key as the final criterion to avoid an unpredictable order between executions.

SELECT id, name, email
FROM customers
WHERE email LIKE '%@example.test'
ORDER BY name ASC, id ASC
LIMIT 20;

NULL means "unknown value", not zero or an empty string. Any comparison with NULL yields UNKNOWN, and WHERE keeps only rows for which the condition is true. Use IS NULL and IS NOT NULL. An expression such as price <> 10 excludes rows where price is NULL, which often surprises.

Three-valued logic explains apparently strange results. NULL = NULL is not true; NULL <> 5 is not true either. NOT (NULL = 5) remains unknown. To count non-null values, use COUNT(column); COUNT(*) counts all rows. To replace a missing value for display, COALESCE is more portable than engine-specific functions.

The IN, BETWEEN, LIKE and EXISTS operators have precise behaviour. BETWEEN includes bounds; on a DATETIME, BETWEEN '2026-01-01' AND '2026-01-31' often excludes the end of the day. Prefer >= and < with an exclusive bound. LIKE with a leading wildcard %abc cannot use a classic index and may become slow on a large table.

Naive pagination with LIMIT 20 OFFSET 100000 becomes expensive, because the engine scans skipped rows. For large volumes, use cursor pagination, for example WHERE (created_at, id) < (:date, :id) ORDER BY created_at DESC, id DESC LIMIT 20, with a suitable index. Page-number pagination remains acceptable for small sets, but must be measured.

Finally, do not mix filtering and presentation. WHERE decides which rows exist in the result; ordering and formatting decide how they are presented. A query that formats dates or concatenates names in the database is harder to test and reuse. Let the database filter and join, and the application format according to language and time zone.

Collations influence comparisons and sorts. A case- and accent-insensitive collation may suit a name search, but not a technical identifier. In French, accent and ligature ordering depends on the chosen collation; in Swahili, extended Latin characters must be correctly supported. Test with real data: "é", "e", "É", "ç" and typographic apostrophes. A sort that looks correct on the ASCII alphabet may be wrong for users' names.

DISTINCT and GROUP BY answer different needs. DISTINCT deduplicates result rows; GROUP BY groups for aggregate calculation. Using DISTINCT to fix a join that produces duplicates often hides a model or condition error. Prefer understanding why duplicates appear, then fix the query or join. DISTINCT can also be costly, because the engine must sort or hash to remove repetitions.

CASE expressions make conditional logic readable inside a query. A CASE WHEN status = 'validated' THEN total ELSE 0 END avoids repeating a complex expression and keeps the rule visible. Prefer CASE to nested IF functions, which are engine-specific and harder to port. Remember that CASE returns a single type: mixing numbers and strings may trigger an implicit conversion that changes the result or prevents index use.

7. Inner and outer joins

A join combines rows from two tables according to a condition. INNER JOIN keeps only rows with a match on both sides. LEFT JOIN keeps all rows from the left table, even without a match, and fills right-hand columns with NULL. RIGHT JOIN does the reverse; FULL OUTER JOIN is not directly available in MariaDB and is simulated with UNION.

-- Orders with their customer, including orders with no valid customer (abnormal)
SELECT o.id AS order_id, c.name AS customer, o.status, o.created_at
FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
ORDER BY o.created_at DESC, o.id DESC;

-- Customers without orders
SELECT c.id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL
ORDER BY c.name;

A filter on the right table often turns a LEFT JOIN into an INNER JOIN without the author noticing. If you write WHERE o.status = 'validated' after a LEFT JOIN orders, rows without an order have status NULL and are eliminated. To keep customers without orders while filtering orders, place the condition in the ON clause or use an explicit subquery.

Duplicates appear when one left row matches several right rows. Joining orders and order lines produces one row per line; if you then count COUNT(*), you count rows, not orders. Use COUNT(DISTINCT o.id) or aggregate lines first in a subquery. An oversized result is often a sign of a misunderstood join, not an engine problem.

Multiple joins must be read in dependency order. A join on a table without a join index can cause a full scan and high response times. Check foreign keys and indexes, then read the execution plan. A LEFT JOIN is not inherently slower than an INNER JOIN, but it may produce more rows and prevent some optimisations.

Explicit joins with ON are preferable to implicit joins in WHERE. They separate the join condition from the filter, make the query readable and avoid accidental Cartesian products. If you forget the condition, you get every possible combination: on two tables of a thousand rows, a million results. The engine does not guess your intention.

A join can also verify integrity. A query that finds orders.customer_id with no matching customer reveals orphan data, normally impossible with a foreign key. These checks are useful after an import, a restore or a migration. They are part of data quality monitoring, not only debugging.

Hierarchies are modelled with a foreign key to the same table, for example categories.parent_id. This self-join is simple, but a recursive query is needed to traverse all levels. MariaDB 10.6 supports recursive CTEs with WITH RECURSIVE. Beware cycles: a category that becomes its own ancestor can make the query loop. Add an application constraint or a check preventing cycles, and test the accepted maximum depth.

Join algorithms explain some plans. Nested loop scans one table and looks up matches in the other; it is efficient with an index and a small set. Hash join builds a hash table to match large sets without an index. Sort-merge sorts both sides then scans them. The engine chooses according to statistics and estimated cost. Understanding these choices helps interpret EXPLAIN, but does not replace measurement on representative data.

An anti-join finds rows with no match. The LEFT JOIN ... WHERE right.id IS NULL pattern is common, but NOT EXISTS is often clearer and handles NULL more predictably than NOT IN. For "customers without a validated order", write NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.status = 'validated'). Test the query with a customer who has only draft orders, because that is exactly where a careless condition gives the wrong answer.

8. Aggregates, GROUP BY, HAVING and subqueries

Aggregates summarise several rows: COUNT, SUM, AVG, MIN, MAX. Without GROUP BY, the query returns a single row for the whole set. With GROUP BY, it returns one row per group. Every column in SELECT must be aggregated or present in GROUP BY; otherwise the result depends on an arbitrary row in the group.

SELECT o.id, o.status, COUNT(l.product_id) AS line_count,
       SUM(l.quantity * l.unit_price) AS total
FROM orders o
LEFT JOIN order_lines l ON l.order_id = o.id
GROUP BY o.id, o.status
HAVING total > 0
ORDER BY total DESC, o.id;

WHERE filters before grouping; HAVING filters after. A condition on an aggregate, such as SUM(...) > 100, goes in HAVING. A row condition, such as status = 'validated', goes in WHERE to reduce work before aggregation. Using HAVING for everything is correct but often less efficient and less clear.

Aggregate functions ignore NULL, except COUNT(*). SUM over an empty set returns NULL, not zero; use COALESCE(SUM(...), 0) if display requires it. AVG divides by the number of non-null values, which can distort an average when values are missing. Document the calculation rule and test with incomplete data.

Subqueries may be scalar, inline or correlated. A scalar subquery returns a single value; a subquery in FROM produces a derived table; a correlated subquery references the outer query and may be costly. EXISTS is often more readable than IN with NULL, because NOT IN (SELECT ...) returns an empty result if the subquery contains a NULL.

-- Customers with at least one validated order
SELECT c.id, c.name
FROM customers c
WHERE EXISTS (
    SELECT 1 FROM orders o
    WHERE o.customer_id = c.id AND o.status = 'validated'
)
ORDER BY c.name;

-- Best-selling product by quantity
SELECT p.id, p.label, SUM(l.quantity) AS quantity_sold
FROM products p
JOIN order_lines l ON l.product_id = p.id
GROUP BY p.id, p.label
ORDER BY quantity_sold DESC, p.id
LIMIT 1;

CTEs, or WITH, improve readability of complex queries. MariaDB 10.6 supports them. A CTE can be reused in the main query and helps decompose into steps. It is not automatically faster: depending on engine and version, it may be materialised or merged. Read the plan rather than assuming.

For rankings, ROW_NUMBER, RANK and DENSE_RANK avoid complicated subqueries. They answer "the latest order per customer" or "the second best-selling product". These window functions are available in MariaDB 10.2 and later. Check the target version before using them in an application hosted on an older server.

A concrete example: to rank each customer's orders by date, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) assigns a rank without prior grouping. To keep only the most recent, wrap the query in a CTE and filter on rank = 1. This is more readable than several correlated subqueries and often more efficient. Still measure the plan, because window functions can consume a lot of memory on large sets.

HAVING can combine several aggregate conditions, such as SUM(quantity) >= 10 AND COUNT(*) > 2. Keep the predicates aligned with the business question and name the aliases clearly. Some engines allow filtering on a SELECT alias in HAVING, but portability varies; repeat the expression or use a CTE when clarity matters. Test with groups that have exactly the threshold value, since boundary cases reveal off-by-one errors.

9. INSERT, UPDATE, DELETE and verified scope

INSERT adds rows, UPDATE modifies them, DELETE removes them. A write must specify its scope: which rows, under which condition, with which prior check. An UPDATE without WHERE modifies every row; a DELETE without WHERE empties the table. These mistakes are famous because they still happen.

-- Verify scope before writing
SELECT id, status FROM orders WHERE customer_id = 1 AND status = 'draft';

-- Limited, verifiable update
UPDATE orders
SET status = 'cancelled'
WHERE customer_id = 1 AND status = 'draft';

-- Logical deletion preferable to physical deletion
UPDATE customers SET deleted_at = CURRENT_TIMESTAMP WHERE id = 3;

In production, run the corresponding SELECT first, inside a transaction, and verify the row count. Use LIMIT for bulk updates, in batches, to avoid long locking. Back up affected rows or enable an audit log. A physical DELETE should be reserved for data whose deletion is planned and authorised.

Bulk inserts must handle duplicates. INSERT ... ON DUPLICATE KEY UPDATE updates if a unique key exists; INSERT IGNORE ignores the error but may mask other problems. Prefer an explicit intention: "insert or update" is not the same as "ignore errors". Test behaviour with existing data and multiple constraints.

Transactions are not reserved for complex operations. An UPDATE changing several tables must be atomic: either everything succeeds or nothing is applied. For example, cancelling an order and releasing stock must happen in the same transaction. Otherwise, a failure between the two leaves an inconsistent state.

Beware triggers. They can automate total updates or logging, but they make behaviour less visible and harder to debug. If you use them, document them, test them and avoid chains that trigger each other. Complex business logic is often clearer in the application, with explicit transactions.

Finally, verify the actual effect of the write: affected row count, re-read content, constraints respected. An UPDATE returning zero rows may be normal or reveal an overly strict filter. An INSERT that succeeds may have ignored part of the data because of a permissive SQL mode. Do not rely solely on the success message.

Bulk operations must be designed as production operations. Plan a log of what changed, a way to replay or undo, and a post-execution check. For an import, validate the file before writing, count accepted and rejected rows, and keep rejects in a separate file. An import that fails halfway leaves the database partially changed; a single transaction can prevent that, but may also lock too long. Split into batches with a documented restart point.

Logical deletion is not a universal solution. It keeps the row and its personal data, which may conflict with an erasure request or a retention period. It also complicates queries, because every read must filter deleted_at IS NULL. If you use it, plan a real purge after the legal period, an index on the deletion column and a view that centralises the filter. For data subject to an erasure obligation, irreversible anonymisation may be preferable to logical deletion.

MariaDB 10.5 and later support INSERT ... RETURNING and DELETE ... RETURNING for some statements, which lets the application receive generated identifiers or deleted rows without a second query. Check exact support for your version and storage engine before relying on it. When it is unavailable, use LAST_INSERT_ID() immediately after the insert on the same connection, and never assume it is safe across pooled connections.

10. Transactions, ACID and concurrency

A transaction groups operations into a unit: START TRANSACTION, then COMMIT to validate or ROLLBACK to cancel. ACID summarises four properties: atomicity, consistency, isolation and durability. Atomicity guarantees all or nothing; consistency that constraints remain respected; isolation that concurrent transactions do not see each other incoherently; durability that validated data survives a failure.

START TRANSACTION;

UPDATE products SET price_excl_tax = 25.50 WHERE id = 3;
INSERT INTO order_lines (order_id, product_id, quantity, unit_price)
VALUES (2, 3, 1, 25.50);

-- Verify before committing
SELECT * FROM order_lines WHERE order_id = 2;
COMMIT;
-- On error: ROLLBACK;

The isolation level determines visible anomalies. READ UNCOMMITTED allows reading unvalidated data; READ COMMITTED reads only validated data; REPEATABLE READ guarantees that repeated reads in a transaction see the same snapshot; SERIALIZABLE reinforces isolation at the cost of more locks. InnoDB uses REPEATABLE READ by default.

Classic anomalies are dirty read, non-repeatable read and phantom read. A dirty read reads data another transaction has not yet validated. A non-repeatable read sees the same row change between two reads. A phantom read sees rows matching a condition appear or disappear. The isolation level does not remove every case; concurrent access must also be designed.

To update a row safely, use an explicit lock: SELECT ... FOR UPDATE inside a transaction. Two transactions that read then write without a lock can lose an update. The lock must be taken in the right order to avoid deadlocks. A deadlock occurs when two transactions wait for each other; the engine cancels one, and the application must retry.

Transactions must be short. A transaction waiting for a user response or an external network call holds locks and blocks others. Prepare data before opening the transaction, perform writes, commit quickly. For long processes, split into batches with restart points rather than one giant transaction.

Concurrency is not only a database problem. Two browsers may modify the same order; two scripts may import the same file. A version column or a conditional update, such as UPDATE ... WHERE version = :version, detects a conflict. The application then decides to display a message, merge or reload. This optimistic check complements transactions.

Plan for deadlock recovery. A deadlock is not necessarily a bug: it can occur when two transactions access the same rows in a different order. The engine cancels one transaction with a specific error; the application must wait a short random delay and retry, within a reasonable limit. Retrying immediately in a loop worsens contention. Log the event, fix the access order if the schema allows, and test behaviour under load.

Isolation levels are verified with two explicit sessions. Open two connections to the same server, start a transaction in each, then observe what the second sees before and after the first commits. Repeat with READ COMMITTED and REPEATABLE READ. This manual test is more instructive than a theoretical table: it shows the real behaviour of your version, engine and settings. Record the results, because a configuration change may alter the expected guarantees.

Savepoints allow partial rollback inside a transaction: SAVEPOINT before_lines, then ROLLBACK TO SAVEPOINT before_lines preserves earlier work. They are useful for optional steps, such as trying to apply a discount and continuing without it if a constraint fails. Do not use them to hide errors that should abort the whole transaction. Release savepoints you no longer need and keep the transaction short.

For web applications, keep the transaction inside one request and one database connection. Do not open a transaction, call an external payment API, wait for a user, then commit: the locks and the connection remain occupied, and a timeout can leave the transaction open. Perform external calls before or after the transaction, and design an explicit compensation step if the external action succeeds but the database commit fails. This is a business decision, not only a technical one.

11. Indexes and execution plans

An index speeds up finding a subset of rows, at the cost of space and write time. The B-tree index is the most common: it supports equality, ranges and sorting. An index on (customer_id, created_at) can serve a customer search and a date sort for that customer. Column order matters: a composite index does not efficiently serve a query filtering only on the second column.

CREATE INDEX idx_orders_customer_date ON orders (customer_id, created_at);
CREATE INDEX idx_lines_product ON order_lines (product_id);

EXPLAIN SELECT id, status, created_at
FROM orders
WHERE customer_id = 1
ORDER BY created_at DESC
LIMIT 10;

EXPLAIN shows the chosen plan: tables, access type, index used, estimated rows, filters. EXPLAIN ANALYZE, available in MariaDB 10.6, executes the query and compares estimates with actual measurements. type=ALL indicates a full scan; type=ref or range indicates indexed access. Estimates are not truths: statistics may be stale.

Indexes have a cost. Every INSERT, UPDATE or DELETE must update the relevant indexes. Too many indexes slow writes and consume space. An unused index is debt: check its usage with engine statistics and remove it after analysis. Do not create an index on every column "just in case".

Covering indexes contain every column needed by the query, avoiding table reads. For example, an index on (customer_id, status, created_at) can cover a query selecting these columns. The gain depends on the engine and column width. An overly wide covering index may cost more than it returns.

Poorly written queries limit index use. A function applied to a column, such as WHERE YEAR(created_at) = 2026, may prevent use of an index on created_at; prefer a date range. A LIKE '%word%' cannot use a classic B-tree index. Implicit type conversion can also make an index unusable.

Measure before and after. Optimisation without measurement can degrade response time or move the problem. Use representative data, not only three demonstration rows. Record the query, plan, observed time and volume. An index added for a rare query may slow all writes; an index removed to save space may make a critical page slow.

Index selectivity indicates its ability to distinguish values. An index on a boolean column with two values hardly helps filter half the rows; an index on an identifier is highly selective. A composite index should be designed from real queries: equality first, then range, then sort. Engine statistics evolve with data; a good plan on a small set may become bad on a million rows. Replay measurements after a significant import.

Prefix indexes index only the first characters of a long column, which saves space but reduces selectivity and cannot serve an exact lookup beyond the prefix. They are a compromise for VARCHAR(255) or text columns, not a default. For email or reference lookups, index the full column when the engine allows it. Check index size, cardinality and the actual queries before choosing a prefix length.

12. Permissions, backups, migrations and synthesis

An application account must not be a database administrator. Grant only the necessary rights: SELECT, INSERT, UPDATE, DELETE on the relevant database, and possibly EXECUTE on procedures. DROP, ALTER and GRANT belong to a separate migration or administration account. Least privilege limits the damage of an injection or a bug.

CREATE USER 'app_shop'@'localhost' IDENTIFIED BY 'strong-password';
GRANT SELECT, INSERT, UPDATE, DELETE ON boutique_lab.* TO 'app_shop'@'localhost';
FLUSH PRIVILEGES;

-- Separate migration account, used only at deployment
CREATE USER 'migr_shop'@'localhost' IDENTIFIED BY 'another-strong-password';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES
ON boutique_lab.* TO 'migr_shop'@'localhost';

Backups must be encrypted, stored off the primary server and tested. With MariaDB, mariadb-dump produces a logical SQL export; mariadb-backup produces a physical backup for large volumes. A logical backup is portable but slow to restore; a physical backup is fast but depends on version and architecture. Choose according to volume and recovery objective.

# Compressed logical backup (laboratory)
mariadb-dump --single-transaction --routines --triggers \
  --default-character-set=utf8mb4 boutique_lab | gzip > boutique_lab.sql.gz

# Verify restoration into a separate database
gunzip -c boutique_lab.sql.gz | mariadb boutique_lab_restore
mariadb -e "SELECT COUNT(*) FROM boutique_lab_restore.orders;"

A migration evolves the schema in a versioned way. It must be reversible or accompanied by a tested rollback procedure on a copy. Adding a column is usually simple; making it mandatory on a large table requires a multi-step strategy: add nullable, backfill in batches, then add the constraint. Renaming or dropping a column requires checking every usage before breaking the existing system.

Before a migration, back up and verify restoration. During the migration, monitor locks and execution time. After, verify schema, constraints and data. A migration that succeeds technically may have lost values through truncation or converted dates incorrectly. Compare samples before and after.

The common thread synthesis: the customers-orders-lines schema answers business questions, preserves price history and controls integrity. Queries use explicit joins, aggregates and readable subqueries. Writes are limited and transactional. Indexes are justified by measurements. Backups are tested, and migrations are versioned.

To go further, explore materialised views if your engine provides them, replication, partitioning and archiving strategies. But do not introduce them without measured need. A simple, well-constrained and backed-up database is better than a complex architecture whose guarantees nobody understands. Database quality is judged by the confidence you can have in its data, the reproducibility of its schema and its ability to restore them.

Monitor a few simple indicators: disk space, active connections, slow queries, cache hit rate, replication lag, age of the last backup, result of the last restoration. A disk-space alert prevents an outage; a backup-age alert prevents discovering too late that it stopped running. For critical systems, point-in-time recovery, or PITR, combines a base backup and binary logs. This procedure must be tested, because it depends on a complete chain of files and commands.

Encrypt backups containing personal data and protect the keys separately from the backup media. An encrypted backup whose key is lost is useless, while an unencrypted backup on a shared disk is a data breach waiting to happen. Define who can restore, where the key is stored, and how access is audited. Test decryption during the restoration drill, not only during the backup job.

Schedule restoration drills, not just backups. A quarterly exercise restores a copy into an isolated environment, runs consistency checks and records the duration. It reveals missing files, wrong credentials, incompatible versions and undocumented steps. Assign an owner and a date, and treat a failed drill as an incident with a corrective action. A backup that has never been restored is only a hope, and a recovery plan that has never been rehearsed is only a document that gives false confidence to the whole team and to the people who depend on the service. Test it under realistic conditions at least every year.

Exercise 1 — Model the need

A bookshop sells books to customers. A customer may place several orders; an order contains several books, with a quantity and an applied price. A book may have several authors, and an author may write several books. A customer may have several addresses, but an order must keep the delivery address used. Propose entities, relationships and cardinalities.

Solution

Entities: customers, addresses, orders, books, authors, order_lines, and a books_authors join table. A customer has several addresses; an order references the customer and copies the delivery address or references an immutable address version. An order line references the order and the book, with quantity and unit price. The books-authors relationship is many-to-many, carried by a join table. Deletion rules must preserve order history.

Exercise 2 — Types and constraints

Write the CREATE TABLE for order_lines with a composite primary key, a strictly positive quantity, a non-negative price and foreign keys. Explain the choice of DECIMAL rather than FLOAT.

Solution

The primary key (order_id, product_id) prevents two lines for the same product in one order. quantity INT UNSIGNED NOT NULL with CHECK (quantity > 0) forbids zero. unit_price DECIMAL(10,2) NOT NULL with CHECK (unit_price >= 0) keeps two exact decimals. FLOAT stores a binary approximation and can produce totals wrong by a cent. Foreign keys reference the primary keys of target tables.

Exercise 3 — Normalise

The table orders(id, customer_name, customer_email, product_name, product_price, quantity) is problematic. Describe three anomalies and propose a third-normal-form decomposition.

Solution

Anomalies: updating the address is repeated across rows; a customer cannot be inserted without an order; deleting the last order erases the customer. Decomposition: customers(id, name, email), products(id, name, price), orders(id, customer_id, date), order_lines(order_id, product_id, quantity, unit_price). The unit price is kept in the line for history.

Exercise 4 — Joins and customers without orders

Write a query listing every customer with their order count, including those with none. Explain why an INNER JOIN does not fit and how to avoid the filter-in-WHERE trap.

Solution

Use customers c LEFT JOIN orders o ON o.customer_id = c.id, then COUNT(o.id) and GROUP BY c.id, c.name. INNER JOIN removes customers without orders. If you add WHERE o.status = 'validated', you also remove rows where o is NULL; place the condition in ON or use a subquery. COUNT(o.id) returns zero for customers without orders, unlike COUNT(*), which counts the NULL row produced by the LEFT JOIN.

Exercise 5 — Aggregates and subqueries

Calculate revenue per customer for validated orders, sorted highest to lowest. Add the number of distinct orders. Explain how to avoid counting an order twice because of lines.

Solution

Filter WHERE o.status = 'validated', join lines, then SUM(l.quantity * l.unit_price). Use COUNT(DISTINCT o.id) for orders, because the join multiplies rows. Group by c.id, c.name. If a customer has no validated order, a LEFT JOIN with COALESCE(SUM(...), 0) displays zero, depending on the need.

Exercise 6 — Transaction and index

Write a transaction that cancels a draft order and returns quantities to stock. Add a useful index for finding a customer's orders by date. Explain the risk of an UPDATE without WHERE and the value of a version check.

Solution

Open START TRANSACTION, verify status with SELECT ... FOR UPDATE, update stock lines, change status, then COMMIT. On anomaly, ROLLBACK. The (customer_id, created_at) index serves lookup and sorting. An UPDATE without WHERE modifies every row; a WHERE version = :version check detects a concurrent modification and allows a response.

Capstone — schema, queries and operations

Take the shop and deliver a complete dossier: commented SQL schema, reproducible dataset, ten business queries (revenue, average basket, unsold products, inactive customers, orders without payment), three transactional writes, two indexes justified by a plan, a tested backup and restore procedure, and a migration adding a column without breaking the existing system.

Grid: the schema meets at least third normal form or justifies denormalisation; constraints cover business rules; queries are readable and tested on edge cases; writes are limited and transactional; indexes are measured; restoration is proven; the migration is reversible or documented. Record commands, results, limits, date, engine version and security settings used. A dossier without proof of restoration is not complete.

Common errors and diagnostic method

Using FLOAT for money, forgetting WHERE in an UPDATE, confusing NULL with zero, joining without a condition or filtering after a LEFT JOIN are classic mistakes. Adding an index without measuring, dropping a column without checking usages, or running a migration without a backup are others. A schema without foreign keys may look simpler, but it lets orphan data in.

Method: reproduce the problem on a small dataset, isolate the query, read the plan, check types and NULL, then fix the cause. Compare expected and actual results row by row. For a write, verify scope with a SELECT first, use a transaction and check the row count. Record the correction and the non-regression test.

Self-assessment

You should now be able to explain the difference between a primary key, a foreign key and a unique index; decompose a need into entities and relationships; justify a type and a constraint; recognise a normalisation anomaly; write an outer join without losing unmatched rows; distinguish WHERE and HAVING; explain a transaction and an isolation level; read an execution plan; describe a safe backup and migration.

Self-assessment: I can model a simple case without a redundant table; I can explain why NOT IN with NULL traps; I can measure the effect of an index; I can restore a backup into a separate database; I can write a migration that does not block a large table. To progress, study execution plans, replication, archiving strategies and historical data modelling.

References