Sub topic 3
RDBMS Software and the SQL Language
This chapter assumes you know that a relational database stores data as tables of rows and columns. It also assumes you can read short code snippets. You don't need to have written SQL before. Here you will learn what the software around the data does, what SQL is, and why SQL code that works in one system sometimes fails in another.
Data model versus software
The relational model is a way of organizing data. It is an idea, not a program. A relational database management system (RDBMS) is the program that implements the idea. It stores the tables on disk, accepts requests, enforces rules, and returns results.
Common systems include PostgreSQL, MySQL, MariaDB, SQLite, Oracle Database, and Microsoft SQL Server. They all store data in tables, and they all understand SQL. They differ in architecture, features, licensing, and many small details.
An RDBMS does several jobs for your application:
- Storage: it writes rows to files in a format designed for fast reading and crash recovery.
- Query processing: it turns a request into an efficient plan for finding the data.
- Integrity: it rejects data that breaks the rules you declared, such as keys and constraints.
- Concurrency: it lets many users read and write at the same time without corrupting each other's work.
- Security: it controls which users may read or change which tables.
- Durability: it keeps committed data safe after a crash or power loss.
If you stored data in plain files, your application code would have to do all of this itself. The RDBMS does it once, in one place, for every program that connects.
Client and server
Most systems, including PostgreSQL, MySQL, Oracle, and SQL Server, run as a separate server process. Your application is a client. It opens a connection, sends SQL as text, and receives rows back.
SQLite is the main exception. It is a library that runs inside your application and reads a single file directly. There is no server process and no network connection. That makes it simple to set up, but it is less suited to many writers at once.
Inside a server, each request passes through several stages.
- The parser checks that the text is valid SQL and that the tables and columns exist.
- The planner (also called the optimizer) picks a strategy. For example, it decides whether to scan a whole table or use an index.
- The executor carries out the plan against the stored data.
- The server sends the result rows or an error message back to the client.
What SQL is
SQL (Structured Query Language) is the standard language for talking to relational databases. It was standardized by ANSI and ISO, and the standard has been revised many times since the 1980s.
SQL is declarative. You describe the result you want, not the steps to produce it. In a language like Python you would write a loop, test each item, and collect matches. In SQL you write this:
SELECT name
FROM customers
WHERE email LIKE '%@example.com'
ORDER BY name;The statement says nothing about how to find those rows. The planner chooses the method. If you later add an index, the same statement can run faster without any change to your code.
SQL is also set-based. A query takes tables in and produces a table out. You think about whole collections of rows, not one row at a time.
The main groups of statements
SQL statements fall into groups by purpose.
| Group | Name | Typical statements | Purpose |
|---|---|---|---|
| DDL | Data definition language | CREATE, ALTER, DROP | Define and change the schema |
| DML | Data manipulation language | INSERT, UPDATE, DELETE | Change the rows |
| DQL | Data query language | SELECT | Read rows |
| DCL | Data control language | GRANT, REVOKE | Manage permissions |
| TCL | Transaction control language | BEGIN, COMMIT, ROLLBACK | Group statements into units of work |
Some sources count SELECT as part of DML, so you will see both conventions. The split between DDL and DML matters in practice. DDL changes the structure, and DML changes the content.
A first complete session
This script runs unchanged in PostgreSQL, MySQL, and SQLite. It uses the customers table from the course examples.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
);
INSERT INTO customers (customer_id, name, email)
VALUES (1, 'Ada Lovelace', '[email protected]');
INSERT INTO customers (customer_id, name, email)
VALUES (2, 'Alan Turing', '[email protected]');
SELECT name, email
FROM customers
WHERE customer_id = 1;The first statement is DDL. It creates the table. The two INSERT statements are DML. The SELECT returns one row: Ada Lovelace and her email address.
Statements end with a semicolon. Keywords such as SELECT are not case-sensitive, so select works too. Most teams write keywords in uppercase and names in lowercase for readability.
Now try to break a rule:
INSERT INTO customers (customer_id, name, email)
VALUES (3, 'Ada Duplicate', '[email protected]');The RDBMS refuses this statement with an error about a violated UNIQUE constraint, and no row is added. The wording of the message differs between systems. This is the integrity job in action. The rule lives in the database, so every application that connects gets the same protection.
Dialects: where systems differ
The SQL standard is large, and no product implements all of it exactly. Each system adds its own extensions and handles some details differently. These variations are called dialects.
The core is portable. CREATE TABLE, INSERT, SELECT with WHERE, joins, and transactions look almost identical everywhere. Differences appear in the edges.
| Task | PostgreSQL | MySQL | SQLite | Column | Column | Column | Column |
|---|---|---|---|---|---|---|---|
| Auto-generated key | `GENERATED ALWAYS AS IDENTITY` | `AUTO_INCREMENT` | `INTEGER PRIMARY KEY` fills in a value automatically | ||||
| Join two strings | `a \ | \ | b` | `CONCAT(a, b)` | `a \ | \ | b` |
| Quote an identifier | `"name"` | `` `name` `` | `"name"` or `` `name` `` | ||||
| Show the query plan | `EXPLAIN` | `EXPLAIN` | `EXPLAIN QUERY PLAN` |
Two other differences cause real bugs:
- Case sensitivity of text comparison. In MySQL, the default collation (the rule for comparing and sorting text) usually treats
'Ada'and'ada'as equal. PostgreSQL and SQLite compare them as different by default. - Type strictness. PostgreSQL rejects a value that does not fit the column type. SQLite uses flexible typing and may store a value of a different type than the column declares.
Standard SQL versus portability in practice
Sticking strictly to the standard has costs. Vendor extensions often give better performance or shorter code. A common approach is to write standard SQL by default and use extensions only where they clearly help. Document each one so a future migration knows where to look.
Query-building libraries and object-relational mappers (ORMs) hide some dialect differences. They generate SQL for the target system from code in your own language. They cannot hide all of them, so you still need to read SQL and the error messages your database returns.
Common mistakes
- Treating SQL as procedural. Writing one query per row inside an application loop is slow. A single set-based statement is usually faster and clearer.
- Forgetting the WHERE clause on UPDATE or DELETE. Without it, the statement affects every row in the table.
- Using string-built SQL with user input. Concatenating user text into a query allows SQL injection. Use parameterized queries, which send the values separately from the SQL text.
- Assuming row order. A table has no built-in order. Without ORDER BY, the system may return rows in any order, and that order can change.
Summary of the roles
The relational model defines how data is organized. The RDBMS stores that data safely and enforces its rules. SQL is the shared language you use to define, change, and read it. The next chapters build on this foundation: tables and schemas first, then querying in more depth.
Exercise
A teammate writes DELETE FROM customers; to remove one customer and forgets the WHERE clause. Which SQL statement group is DELETE in, what happens, and which two features of an RDBMS could help recover or prevent the mistake?
Show answer
DELETE is DML, because it changes rows and not the schema. Without WHERE, it removes every row in the table. Running the statement inside a transaction lets you issue ROLLBACK before COMMIT to undo it. Permissions (GRANT and REVOKE) can also stop most users from running DELETE on the table at all.
Exercise
You move an application from SQLite to PostgreSQL. A search for the name 'ada' used to match the stored value 'Ada' and now returns nothing. What causes this, and what is one fix?
Show answer
The two systems compare text differently. In this case the earlier setup treated the values as equal, and PostgreSQL's default comparison is case-sensitive. One fix is to compare lowercased values, as in WHERE LOWER(name) = 'ada'. Another is to use a case-insensitive comparison operator such as PostgreSQL's ILIKE.