Almost every app, website and report gets its data from a database, and SQL is how people and programs talk to one.
Picture a shop that keeps its customers, products and orders in a spreadsheet. That works until there are a million orders, several staff edit the file at once, and someone needs 'every order from London last March' within a second. A database is software built for exactly that: it stores large amounts of data, lets many people read and change it at the same time, and doesn't lose anything if the power fails.
SQL (say 'ess-cue-ell' or 'sequel') is the language you use to talk to a database. You write a short instruction in something close to English, and the database carries it out. For example, SELECT name FROM customers; asks for the name of every customer.
Each complete instruction is called a statement, and it ends with a semicolon ;. A statement that asks a question and gets data back is a query. Other statements add, change or delete data, or create new places to store it.
In the examples, lines starting with two dashes -- are comments: notes for the human reader that the database ignores. We use them to show what each query returns.
A database usually runs as a server: a program, often on another computer, that waits for instructions and answers them. You talk to it through a client, an app where you type SQL and see the results. PostgreSQL comes with a simple text client called psql; apps such as pgAdmin and DBeaver do the same job with windows and buttons.
Many database products understand SQL. The best known are PostgreSQL, MySQL, SQLite, Microsoft's SQL Server and Oracle. The core of the language is an international standard and works the same everywhere, but each product adds extras and differs in small details. So each speaks its own dialect of SQL.
These lessons use PostgreSQL, which is free and follows the standard closely, and point out where the others differ.
Example
-- A query: ask the database for data
SELECT name, city FROM customers;
-- name | city
-- Ana | Yerevan
-- Ben | London
-- ...
-- Other statements change data; each ends with a semicolon
UPDATE customers SET city = 'Paris' WHERE name = 'Ana';
-- In psql you type a statement after the prompt and press Enter:
-- shop=> SELECT 2 + 3;
-- ?column?
-- 5Remember
- A database stores shared data safely and answers questions about it quickly
- SQL is the language for talking to it: one instruction is a statement, a question is a query
- Many products speak SQL in slightly different dialects; these lessons use PostgreSQL
Watch out for
- Expecting SQL copied from a MySQL or SQL Server tutorial to run unchanged in PostgreSQL: the core works, but some details differ.