SQL — DDL and DML · SQL — DDL et DML
| English | Français |
|---|---|
| SQL/ˌes kjuː ˈel/ | SQL |
| Data Definition Language/ˈdeɪtə ˌdefɪˈnɪʃn ˈlæŋɡwɪdʒ/ | Language de Définition de Données (DDL) |
| Data Manipulation Language/ˈdeɪtə məˌnɪpjʊˈleɪʃn ˈlæŋɡwɪdʒ/ | Language de Manipulation de Données (DML) |
| INNER JOIN/ˈɪnə dʒɔɪn/ | INNER JOIN |
| aggregate functions/ˈæɡrɪɡeɪt ˈfʌŋkʃnz/ | fonctions agrégées |
The language your grandparents' programmers also used
- In 1974 two IBM researchers designed a query language for Codd's tables and called it SEQUEL: Structured English Query Language. The name was trimmed to SQL 结构化查询语言, and the language never went away.
- Fifty years later, every bank, airline, hospital and website you use runs on it. A student typing
SELECTtoday is writing the same statement a programmer wrote before her parents were born. - It has two halves, and the exam asks you to read either and to write both: the Data Definition Language 数据定义语言 that builds the structure, and the Data Manipulation Language 数据操纵语言 that fills, changes and questions the data.
- This lesson is the subset of SQL on the syllabus, statement by statement, with the marks each one carries.
Le langage que vos grands-parents programmeurs utilisaient aussi
- En 1974, deux chercheurs d'IBM ont conçu un langage de requêtes pour les tables de Codd et l'ont appelé SEQUEL : Structured English Query Language. Le nom a été abrégé en SQL 结构化查询语言, et le langage n'est jamais parti.
- Cinquante ans plus tard, chaque banque, compagnie aérienne, hôpital et site web que vous utilisez fonctionne dessus. Un étudiant tapant
SELECTaujourd'hui écrit la même instruction qu'un programmeur avant que ses parents ne naissent. - Il a deux moitiés, et l'examen vous demande de lire l'une ou l'autre et d'écrire les deux : le Data Definition Language 数据定义语言 qui construit la structure, et le Data Manipulation Language 数据操纵语言 qui remplit, modifie et interroge les données.
- Cette leçon est le sous-ensemble de SQL au programme, instruction par instruction, avec les points que chacune vaut.
DDL and DML
- The DBMS carries out all creation and modification of the database's structure through its DDL: creating a database, creating and altering tables, adding keys.
- It carries out all queries and maintenance of the data through its DML: selecting, inserting, updating and deleting rows.
- SQL is the industry standard for both. Sorting a statement into the right half is a common one-mark question:
CREATE TABLEis DDL,SELECTis DML.
Structure on one side, data on the other
DDL et DML
- Le SGBD effectue toutes les créations et modifications de la structure de la base de données via son DDL : création d'une base de données, création et modification de tables, ajout de clés.
- Il effectue toutes les requêtes et maintenance des données via son DML : sélection, insertion, mise à jour et suppression de lignes.
- SQL est la norme industrielle pour les deux. Classer une instruction dans la bonne moitié est une question fréquente d'un point :
CREATE TABLEest DDL,SELECTest DML.

Structure d'un côté, données de l'autre
Which is part of the Data Definition Language (DDL)? · Lequel fait partie du Langage de Définition de Données (DDL) ?
DDL changes the structure (CREATE, ALTER, DROP). SELECT/INSERT/UPDATE/DELETE are DML (working with data). · La DDL modifie la structure (CREATE, ALTER, DROP). SELECT/INSERT/UPDATE/DELETE sont du DML (manipulation des données).
DDL defines the structure (e.g. CREATE TABLE), while DML works with the data inside it (SELECT, INSERT, UPDATE, DELETE). · La DDL définit la structure (ex. CREATE TABLE), tandis que le DML travaille avec les données qu'elle contient (SELECT, INSERT, UPDATE, DELETE).
Definition vs Manipulation: DDL shapes the tables; DML reads and changes the rows. · Définition vs Manipulation : La DDL façonne les tables ; le DML lit et modifie les lignes.
DDL: creating the structure
- Data types on the syllabus:
CHARACTER(a fixed number of characters),VARCHAR(n)(up to n characters),BOOLEAN,INTEGER,REAL,DATE,TIME. PRIMARY KEY (field)names the key;ALTER TABLE … ADDadds an attribute to an existing table.
DDL : créer la structure
CREATE DATABASE Shop;
CREATE TABLE CUSTOMER (
CustomerID INTEGER,
Name VARCHAR(50),
Town VARCHAR(30),
Joined DATE,
Active BOOLEAN,
PRIMARY KEY (CustomerID)
);
ALTER TABLE CUSTOMER ADD Email VARCHAR(100);
- Types de données au programme :
CHARACTER(un nombre fixe de caractères),VARCHAR(n)(jusqu'à n caractères),BOOLEAN,INTEGER,REAL,DATE,TIME. PRIMARY KEY (field)nomme la clé ;ALTER TABLE … ADDajoute un attribut à une table existante.
Match each item of data to the SQL data type for it. · Reliez chaque élément de donnée au type de données SQL correspondant.
Two states, variable-length text, a number with a fractional part, a calendar date. INTEGER is for whole counts and TIME for a time of day. · Deux états, texte de longueur variable, nombre à virgule, date calendaire. INTEGER sert aux comptes entiers et TIME à une heure de la journée.
Worked example: two tables with a foreign key
- Write the SQL to create an
ORDERStable withOrderIDas primary key,CustomerIDas a foreign key toCUSTOMER, and anOrderDate.
- The marks:
CREATE TABLEwith the name; each attribute with a suitable type; thePRIMARY KEY; theFOREIGN KEY … REFERENCESnaming the table and its field.
Exemple résolu : deux tables avec une clé étrangère
- Écrivez le SQL pour créer une table
ORDERSavecOrderIDcomme clé primaire,CustomerIDcomme clé étrangère versCUSTOMER, et unOrderDate.
CREATE TABLE ORDERS (
OrderID INTEGER,
CustomerID INTEGER,
OrderDate DATE,
PRIMARY KEY (OrderID),
FOREIGN KEY (CustomerID) REFERENCES CUSTOMER(CustomerID)
);
- Les points :
CREATE TABLEavec le nom ; chaque attribut avec un type approprié ; laPRIMARY KEY; laFOREIGN KEY … REFERENCESnommant la table et son champ.
DML: asking a question with SELECT
SELECTlists the fields to output (*for all),FROMnames the table,WHEREkeeps only the rows that meet a condition,ORDER BYsorts the result,ASCorDESC.- Strings go in single quotes; numbers do not. Comparisons:
=,<,>,<=,>=,<>; conditions join withAND,OR,NOT;LIKE 'A%'matches text starting with A;BETWEEN 10 AND 20gives a range.
Only the rows that pass the WHERE reach the result
DML : poser une question avec SELECT
SELECT Name, Town
FROM CUSTOMER
WHERE Town = 'London'
ORDER BY Name ASC;
SELECTliste les champs à afficher (*pour tous),FROMnomme la table,WHEREgarde uniquement les lignes répondant à une condition,ORDER BYtrie le résultat,ASCouDESC.- Les chaînes sont entre guillemets simples ; les nombres sans guillemets. Comparaisons :
=,<,>,<=,>=,<>; les conditions se joignent avecAND,OR,NOT;LIKE 'A%'correspond au texte commençant par A ;BETWEEN 10 AND 20donne une plage.

Seules les lignes passant le WHERE atteignent le résultat
Which SQL keyword retrieves data from a table? (one word) · Quel mot-clé SQL permet de récupérer des données depuis une table ? (un seul mot)
SELECT lists the fields to retrieve; FROM names the table. · SELECT liste les champs à récupérer ; FROM nomme la table.
The WHERE clause in a SELECT statement: · La clause WHERE dans une instruction SELECT :
WHERE filters rows by a condition; ORDER BY sorts; the SELECT list chooses columns. · WHERE filtre les lignes selon une condition ; ORDER BY trie ; la liste SELECT choisit les colonnes.
Worked example: write the query
- Write an SQL script to output the names and email addresses of all active customers in Manchester, in alphabetical order of name.
- One mark each: the right fields after
SELECT; the right table afterFROM; theWHEREwith both conditions and the string in single quotes;ORDER BY Name. Use the exact table and field names the question gives.
Exemple résolu : écrire la requête
- Écrivez un script SQL pour afficher les noms et adresses e-mail de tous les clients actifs à Manchester, par ordre alphabétique de nom.
SELECT Name, Email
FROM CUSTOMER
WHERE Town = 'Manchester' AND Active = TRUE
ORDER BY Name;
- Un point chacun : les bons champs après
SELECT; la bonne table aprèsFROM; laWHEREavec les deux conditions et la chaîne entre guillemets simples ;ORDER BY Name. Utilisez les noms exacts de table et de champ donnés par la question.
Put the clauses of a SELECT statement in the order they are written. · Placez les clauses d'une instruction SELECT dans l'ordre d'écriture.
Fields, table, filter, sort. ORDER BY is always last, and the statement ends with a semicolon. · Champs, table, filtre, tri. ORDER BY est toujours en dernier, et l'instruction se termine par un point-virgule.
Two tables: INNER JOIN
- An INNER JOIN 连接 combines the rows of two tables where the foreign key in one matches the primary key in the other, named in the
ONclause. - Prefix a field with its table when the same name appears in both. The syllabus asks for queries over at most two tables.
Deux tables : INNER JOIN
SELECT CUSTOMER.Name, ORDERS.OrderDate
FROM CUSTOMER INNER JOIN ORDERS
ON CUSTOMER.CustomerID = ORDERS.CustomerID
WHERE ORDERS.OrderDate >= '2024-01-01';
- Un INNER JOIN 连接 combine les lignes de deux tables où la clé étrangère dans l'une correspond à la clé primaire dans l'autre, nommé dans la clause
ON. - Préfixez un champ avec sa table si le même nom apparaît dans les deux. Le programme demande des requêtes sur au maximum deux tables.
Stitch two tables with INNER JOIN · Assembler deux tables avec INNER JOIN
A join matches rows where the foreign key equals the primary key — here Orders.CustomerID = Customer.CustomerID — and combines each matching pair into one wider row. · Un joint associe les lignes où la clé étrangère correspond à la clé primaire — ici Orders.CustomerID = Customer.CustomerID — et combine chaque paire correspondante en une ligne plus large.
An INNER JOIN is used to: · Un INNER JOIN est utilisé pour :
A JOIN combines two tables on a relationship (usually a foreign key matching a primary key). · Un JOIN combine deux tables sur une relation (généralement une clé étrangère correspondant à une clé primaire).
Aggregates and GROUP BY
- Aggregate functions 聚合函数 summarise many rows into one value:
COUNTthe rows,SUMa total,AVGa mean. GROUP BYmakes one summary row per value of a field: the number of orders per customer. Without it, an aggregate summarises the whole table.
Fonctions agrégées et GROUP BY
SELECT CustomerID, COUNT(*) AS NumOrders
FROM ORDERS
GROUP BY CustomerID;
SELECT AVG(Price) FROM PRODUCT;
SELECT SUM(Quantity) FROM ORDER_LINE WHERE OrderID = 1042;
- Les fonctions agrégées 聚合函数 résument plusieurs lignes en une valeur :
COUNTles lignes,SUMun total,AVGune moyenne. GROUP BYcrée une ligne de résumé par valeur d'un champ : le nombre de commandes par client. Sans cela, une agrégation résume toute la table.
What does COUNT(*) return? · Que renvoie COUNT(*) ?
COUNT() counts rows; SUM/AVG/MIN/MAX are the other aggregate functions. · COUNT() compte les lignes ; SUM/AVG/MIN/MAX sont les autres fonctions agrégées.
To output the number of orders placed by each customer, the query needs: select all · tout that apply. · Pour afficher le nombre de commandes passées par chaque client, la requête nécessite : sélectionnez tous ceux qui s'appliquent.
Count the rows, one group per customer, from the orders table. Sorting is optional. · Comptez les lignes, un groupe par client, depuis la table des commandes. Le tri est optionnel.
Changing the data: INSERT, UPDATE, DELETE
INSERT INTO … VALUESadds a row: list the fields, then the values in the same order.UPDATE … SET … WHEREchanges matching rows.DELETE FROM … WHEREremoves them.- Always give
UPDATEandDELETEaWHEREclause, or the change hits every row in the table.
Modifier les données : INSERT, UPDATE, DELETE
INSERT INTO CUSTOMER (CustomerID, Name, Town, Joined, Active)
VALUES (101, 'Ada Lovelace', 'London', '2024-03-01', TRUE);
UPDATE CUSTOMER SET Town = 'Bristol' WHERE CustomerID = 101;
DELETE FROM CUSTOMER WHERE CustomerID = 101;
INSERT INTO … VALUESajoute une ligne : listez les champs, puis les valeurs dans le même ordre.UPDATE … SET … WHEREchange les lignes correspondantes.DELETE FROM … WHEREles supprime.- Donnez toujours à
UPDATEetDELETEune clauseWHERE, sinon le changement touche toutes les lignes de la table.
What happens if you run UPDATE or DELETE without a WHERE clause? · Que se passe-t-il si vous exécutez UPDATE ou DELETE sans clause WHERE ?
With no WHERE, the operation affects all rows — a common and dangerous mistake. · Sans WHERE, l'opération affecte toutes les lignes — une erreur fréquente et dangereuse.
Match each DML statement to what it does. · Reliez chaque instruction DML à son action.
SELECT reads; INSERT adds; UPDATE changes; DELETE removes — the four core DML verbs. · SELECT lit ; INSERT ajoute ; UPDATE modifie ; DELETE supprime — les quatre verbes fondamentaux du DML.
Worked example: read the statement
- State what this script outputs. The names of every customer who placed an order on 1 May 2024, one row per such order, in reverse alphabetical order.
- Read it in execution order: join the tables on the customer ID, keep the rows for that date, output the name, sort descending. A customer with two orders that day appears twice.
Exemple résolu : lire l'instruction
SELECT Name
FROM CUSTOMER INNER JOIN ORDERS
ON CUSTOMER.CustomerID = ORDERS.CustomerID
WHERE OrderDate = '2024-05-01'
ORDER BY Name DESC;
- Indiquez ce que ce script produit. Les noms de tous les clients ayant passé une commande le 1 mai 2024, une ligne par telle commande, par ordre alphabétique inverse.
- Lisez-le dans l'ordre d'exécution : joignez les tables sur l'ID client, gardez les lignes pour cette date, affichez le nom, triez descendant. Un client avec deux commandes ce jour-là apparaît deux fois.
Marks that slip away
- Strings in single quotes, numbers bare:
Town = 'London',CustomerID = 101. ORDER BYcomes afterWHERE; a join needs itsONclause; every statement ends with a semicolon.COUNT(*)counts rows, not distinct values; the per-group question needsGROUP BY.CREATE,ALTERandPRIMARY KEYare DDL;SELECT,INSERT,UPDATE,DELETEare DML. Use the exact names the question gives.
Pièges qui font perdre des points
- Les chaînes entre guillemets simples, les nombres nus :
Town = 'London',CustomerID = 101. ORDER BYvient aprèsWHERE; un JOIN a besoin de sa clauseON; chaque instruction se termine par un point-virgule.COUNT(*)compte les lignes, pas les valeurs distinctes ; la question par groupe nécessiteGROUP BY.CREATE,ALTERetPRIMARY KEYsont DDL ;SELECT,INSERT,UPDATE,DELETEsont DML. Utilisez les noms exacts donnés par la question.
You've got it
- DDL creates and changes the structure:
CREATE DATABASE,CREATE TABLEwith typed attributes,PRIMARY KEY,FOREIGN KEY … REFERENCES,ALTER TABLE … ADD· DML works with the data - types:
CHARACTER,VARCHAR(n),BOOLEAN,INTEGER,REAL,DATE,TIME SELECT fields FROM table WHERE condition ORDER BY field;INNER JOIN … ONfor two tables;COUNT,SUM,AVGwithGROUP BYfor one row per groupINSERT INTO … VALUES,UPDATE … SET … WHERE,DELETE FROM … WHERE: never an update or delete withoutWHERE
Vous avez compris
- DDL crée et modifie la structure :
CREATE DATABASE,CREATE TABLEavec des attributs typés,PRIMARY KEY,FOREIGN KEY … REFERENCES,ALTER TABLE … ADD· DML travaille avec les données - types :
CHARACTER,VARCHAR(n),BOOLEAN,INTEGER,REAL,DATE,TIME SELECT fields FROM table WHERE condition ORDER BY field;INNER JOIN … ONpour deux tables ;COUNT,SUM,AVGavecGROUP BYpour une ligne par groupeINSERT INTO … VALUES,UPDATE … SET … WHERE,DELETE FROM … WHERE: jamais de mise à jour ou de suppression sansWHERE