Chapter 9 · Course 2 c09-m02
How do you add or correct rows?
Your goal Add fictional rows, correct one row and remove a disposable row while keeping writes targeted and initial facts checkable.
The lesson, the vocabulary, the worked example and the mission are separate blocks. You can follow them in order or return to the one you need.
Video explanation
This English explanation has English subtitles. Its examples may use a separate practice dataset; use the data stated in the written mission for your answers.
Story · optional context
The story so far
You are Aster Motors’ new data recruit. Noctis 01 vanished after the crash that hurt Luca; Voss uses an authorization bearing your ID to demand your suspension. Mara Sol and Imani have a SQLite practice database separate from the originals. Its first schema allows two different rows to bear the same event key. You will insert them in the copy to show how a duplicate trace can appear, then correct a typo in another value without erasing the two rows.
You can start here. A table has columns and rows; in this copy, authorizations has a unique id, an event_key and a source-file name. SQL that changes rows is called DML. You will learn INSERT, UPDATE ... WHERE and DELETE ... WHERE, then read the final state. The full code below creates a fresh practice database; do not run it on a real evidence register.
Before the lesson
Purpose of this course
Add fictional rows, correct one row and remove a disposable row while keeping writes targeted and initial facts checkable.
Topics covered
Read INSERT INTO ... VALUES and match each value to a column.; Use UPDATE ... SET ... WHERE to correct a precise row.; Use DELETE FROM ... WHERE only for an identified disposable row.; Compare before and after and explain the danger of omitting WHERE.
What you will learn
- Read
INSERT INTO ... VALUESand match each value to a column. - Use
UPDATE ... SET ... WHEREto correct a precise row. - Use
DELETE FROM ... WHEREonly for an identified disposable row. - Compare before and after and explain the danger of omitting
WHERE.
PART 1 · THE LESSON
Understand step by step
Lesson · explanation
Read the practice copy before changing one row
A table is like a notebook divided into boxes. In authorizations, each row is an authorization recorded in the practice database. Columns say what each box holds. id identifies a row, event_key labels a reported event, and source_file names a cited source file. These three fields do not tell the entire case, but they let us track exactly what changes.
DML is the part of SQL that adds, changes, or removes rows in an existing table. INSERT adds, UPDATE changes, and DELETE removes. SELECT reads the state before or after a write. Think of a paper draft: you may add a line or correct a box, but you must know which line you are touching and what it said before.
In the story, Imani keeps the originals elsewhere. The full sample code builds a fresh disposable SQLite database to test a mechanism. This separation matters: removing a row from the practice copy does not erase an original record. A simulation can show what a schema allows; it does not automatically show that the same thing happened in the real system.
Before any write, draw a paper table with A1, A2, and TEMP. Add id, event_key, and source_file for each. Follow the commands in order and update the drawing. You will see each state instead of vaguely saying 'the file changed'. You can reason this through without running SQL.
Pause and think
What does SELECT do here, and what kind of database receives the writes?
See the explanation
SELECT reads the state for before-and-after comparison. The writes happen in a fresh practice copy, apart from the originals.
Lesson · explanation
The schema allows two rows for one event key
A schema describes a table's columns and rules. Here id TEXT PRIMARY KEY means every authorizations row needs a unique id. If A1 already exists, inserting another row with id = 'A1' breaks that rule. A primary key is like a unique card number in a filing cabinet.
event_key holds an event label, such as EXIT-7. It is required by NOT NULL, but this schema does not declare it unique. A1 and A2 can therefore have different IDs yet share event_key = 'EXIT-7'. Do not confuse 'each row has a unique ID' with 'each event appears only once'.
In the practice database, vehicles first holds NOCTIS-01. authorizations.vehicle_code is linked to it by a foreign key; that checks whether the mentioned vehicle code exists in this small database. It does not prove a physical car passed a gate or that HERO-ID names the person who pressed a button.
Imagine library cards numbered 101 and 102, both saying 'return of book X'. Their card numbers differ, while the described event is the same. We can make that situation in a filing system, but other documents are needed to know whether there were two returns or one copied card.
Pause and think
Why can A1 and A2 share EXIT-7 without breaking the stated uniqueness rule?
See the explanation
Their IDs are different. event_key has no UNIQUE rule in this schema.
Lesson · explanation
INSERT INTO ... VALUES matches values to columns
To add a row, INSERT INTO authorizations names the table. The parenthesized list names the columns: (id, vehicle_code, actor_id, event_key, attempt_no, source_file). VALUES then supplies six values in the same order. The first goes into id, the second into vehicle_code, and so on. Changing their positions can put a value in the wrong box.
A1 receives ('A1', 'NOCTIS-01', 'HERO-ID', 'EXIT-7', 1, 'gtae.csv'). gtae.csv is a deliberate typo in this copy, not a source name to invent for real evidence. A2 receives another id, attempt_no = 2, and source_file = 'mirror.csv', while keeping event_key = 'EXIT-7'.
A third INSERT adds TEMP with event_key = 'DRAFT' and source_file = 'scratch.csv'. TEMP is a practice draft. After these inserts, your paper table must have A1, A2, and TEMP. There are three rows in the copy, even though A1 and A2 refer to the same reported event key.
An insert does not verify the whole story. SQL accepts these two lines because the schema permits them. It cannot know whether Voss made a false trace or who used an ID. Keep the input values and table definition so Imani can repeat the test and understand why duplication is possible.
Pause and think
After the three authorizations inserts, which IDs exist and which event key do A1 and A2 share?
See the explanation
A1, A2, and TEMP exist. A1 and A2 both have event_key = 'EXIT-7'.
Lesson · explanation
UPDATE ... SET ... WHERE corrects one target box
Read UPDATE authorizations SET source_file = 'gate.csv' WHERE id = 'A1'; in pieces. UPDATE authorizations names the table to change. SET source_file = 'gate.csv' gives a new field value. WHERE id = 'A1' limits the action to rows with that ID. Because id is unique, one row is targeted in this copy.
Before this command, A1 has gtae.csv. Afterward it has gate.csv. A2 keeps mirror.csv, and TEMP keeps scratch.csv. It is like correcting one box on card 101 without rewriting cards 102 and 103. Read all three rows before and after to check that the command had the expected effect.
Without WHERE, UPDATE authorizations SET source_file = 'gate.csv'; changes that field on every row. A2 would lose mirror.csv, and TEMP would lose scratch.csv. The source distinctions would disappear. The computer cannot guess that you only meant A1: the condition expresses that intention.
Even a targeted correction needs a reason. The exercise states that gtae.csv is a known typo in the copy. In a real investigation, compare with the original before writing gate.csv. An unsupported correction may replace a visible mistake with a quiet invention.
Pause and think
Which row changes with WHERE id = 'A1', and what might happen without WHERE?
See the explanation
Only A1 changes from gtae.csv to gate.csv. Without WHERE, every row's source_file could change.
Lesson · explanation
DELETE FROM ... WHERE removes the draft, not the evidence
DELETE FROM authorizations WHERE id = 'TEMP'; removes rows whose ID is TEMP. In this practice copy, exactly one row matches. A1 and A2 remain. Think of removing a draft card from a test cabinet, though the SQL command acts on database rows, not physical paper.
Compare DELETE FROM authorizations;. With no filter, it removes every row in the table. The structure called authorizations would still exist, but its contents would be gone. A table existing does not mean its data survived. This is why Mara checks every WHERE before deletion.
TEMP is explicitly a disposable row made for this exercise. A1 and A2 must stay visible to show the possible duplication of EXIT-7. Deleting A2 because it is inconvenient would erase the very subject of the test. Removing a row from the original evidence register would conflict with preserving the case record.
Before DELETE, ask: which exact row is disposable, how will I identify it, and what must remain? Here the answer is TEMP only, found by its ID. After the simulated command, use SELECT to check that A1 and A2 still exist. A written condition helps only when its effect is verified.
Pause and think
What remains after DELETE FROM authorizations WHERE id = 'TEMP';?
See the explanation
A1 and A2 remain. Only TEMP leaves the practice copy.
Lesson · explanation
Read before and after instead of jumping to conclusions
Follow three snapshots. After INSERT: A1 / EXIT-7 / gtae.csv, A2 / EXIT-7 / mirror.csv, and TEMP / DRAFT / scratch.csv. After UPDATE, only A1's source becomes gate.csv. After DELETE, TEMP is absent from the copy; A1 and A2 still exist. Each state reveals one command's exact effect.
The final SELECT requests id, event_key, and source_file, sorted by id. It returns A1 / EXIT-7 / gate.csv, then A2 / EXIT-7 / mirror.csv. ORDER BY id makes the display readable. It does not prove A1 was created before A2 in a real system. In this exercise we know the insert order because it was supplied.
If you only saw the final state, you might miss the initial gtae.csv typo and forget TEMP. The lesson gives intermediate states for comparison. In real data work, keep a record of commands, an initial copy, and the source supporting a correction. Here paper reasoning is enough to understand why those records matter.
The final copy still has two EXIT-7 rows. That does not mean two real vehicle exits happened. It means this exercise schema and these inserts allow different rows with the same event key. Imani must inspect original files and system history to explain the real case.
Pause and think
What two rows does the final SELECT show, and what does their shared EXIT-7 not prove?
See the explanation
It shows A1 / EXIT-7 / gate.csv and A2 / EXIT-7 / mirror.csv. The shared key proves neither two real exits nor who made a duplicate.
Lesson · explanation
Know what the simulation proves and what it leaves open
The test demonstrates a technical possibility: with unique id but nonunique event_key, the practice database accepts A1 and A2 with EXIT-7. It also shows that A1 can be corrected without changing A2, and TEMP can be removed without losing the two useful lines. These results are checkable in the copy and sample code.
The test does not establish who wrote the real authorizations, whether their source files are genuine, or whether you used the ID shown. An ID in a row is a data value, not a camera filming the person at the keyboard. It might come from entry, copying, or another mechanism still unknown.
A sound explanation to Imani keeps three levels apart: 'the schema allows two rows', 'this simulation actually produces two rows', and 'the cause in the real system remains to be checked'. If Voss jumps from the simulation to blame, ask for originals and write history. The practice database cannot replace them.
Learning INSERT, UPDATE, and DELETE also means learning not to damage what you investigate. These commands change the draft data. Target them with WHERE, inspect their effect with SELECT, and preserve initial evidence. This method supports the investigation instead of creating another confusing trace.
Pause and think
Does the A1/A2 test prove the new recruit created the authorizations in the real register?
See the explanation
No. It shows only that duplication is technically possible in the copy; identifying a real author needs other evidence.
Visual guide
The copy’s state as commands run
- 1After
INSERT: A1, A2 and TEMP exist - 2After
UPDATE ... WHERE id='A1': only A1’s source changes - 3After
DELETE ... WHERE id='TEMP': A1 and A2 remain
The EXIT-7 duplication stays visible in the copy; no original was erased.
SQL · query or table structure
DML on a new disposable SQLite database
PRAGMA foreign_keys = ON;
CREATE TABLE vehicles (code TEXT PRIMARY KEY);
CREATE TABLE authorizations (
id TEXT PRIMARY KEY,
vehicle_code TEXT NOT NULL,
actor_id TEXT NOT NULL,
event_key TEXT NOT NULL,
attempt_no INTEGER NOT NULL,
source_file TEXT,
FOREIGN KEY (vehicle_code) REFERENCES vehicles(code)
);
INSERT INTO vehicles (code) VALUES ('NOCTIS-01');
INSERT INTO authorizations
(id, vehicle_code, actor_id, event_key, attempt_no, source_file)
VALUES ('A1', 'NOCTIS-01', 'HERO-ID', 'EXIT-7', 1, 'gtae.csv');
INSERT INTO authorizations
(id, vehicle_code, actor_id, event_key, attempt_no, source_file)
VALUES ('A2', 'NOCTIS-01', 'HERO-ID', 'EXIT-7', 2, 'mirror.csv');
INSERT INTO authorizations
(id, vehicle_code, actor_id, event_key, attempt_no, source_file)
VALUES ('TEMP', 'NOCTIS-01', 'TEST', 'DRAFT', 0, 'scratch.csv');
UPDATE authorizations SET source_file = 'gate.csv' WHERE id = 'A1';
DELETE FROM authorizations WHERE id = 'TEMP';
SELECT id, event_key, source_file FROM authorizations ORDER BY id;The beginning creates both tables in a fresh practice database. INSERT adds A1, A2 and TEMP. UPDATE corrects only A1’s source; DELETE removes only TEMP. The final SELECT shows the two preserved EXIT-7 rows.
PART 2 · WATCH IT WORK
A complete worked example
Follow each step, then the result
Worked example: track three writes
After insertion, the copy has A1 / EXIT-7 / gtae.csv, A2 / EXIT-7 / mirror.csv and TEMP / DRAFT / scratch.csv. You correct A1’s known typo and remove TEMP draft.
- Read
UPDATE ... WHERE id = 'A1': only A1 changes fromgtae.csvtogate.csv. A2 stays as it was. - Read
DELETE ... WHERE id = 'TEMP': only TEMP vanishes. The draft was not evidence. - Show
id,event_key,source_file: A1 / EXIT-7 / gate.csv and A2 / EXIT-7 / mirror.csv remain. - Count events: two rows still carry
EXIT-7. That follows from this exercise schema and inserts, not a conclusion about the real case.
Every write should say what it targets and leave a state that can be compared with the previous one.
How this helps with your missionMara's worked example traces three writes on a copy: INSERT creates A1, A2, and TEMP; UPDATE ... WHERE id = 'A1' changes only A1's source; DELETE ... WHERE id = 'TEMP' removes only the draft. In the mission, explain those same states to Imani, keep both EXIT-7 rows visible, and show why this possible mechanism does not identify a person without original records and system history.
PART 3 · YOUR TURN
Use the lesson to solve the mission
Story scene · practical task
Mission: reproduce the false trace without erasing originals
In the story, Voss arrives with two authorizations bearing your ID. Imani keeps the original register intact and gives you only a practice copy. She wants A1 and A2 with shared event key EXIT-7, then A1’s mistyped source corrected and draft TEMP removed. Mara watches every WHERE condition.
Your task
- Describe the effect of the three practice
INSERTcommands and why A1 and A2 may shareEXIT-7. - Write a command correcting A1’s
gtae.csvtogate.csvonly. - Write a command removing TEMP only and give the two rows remaining after the final read.
- Explain what
UPDATEorDELETEwithoutWHEREcould do and what the test cannot prove about you.
How to know you have succeeded
- A1, A2 and TEMP are added; A1 and A2 have different IDs and
event_keyis not unique. UPDATE authorizations SET source_file = 'gate.csv' WHERE id = 'A1';targets A1.DELETE FROM authorizations WHERE id = 'TEMP';leaves A1 and A2 withEXIT-7.- Without a filter many rows might change or vanish; simulation names no real author.
Try code or SQL and keep a local draft. The mission questions are checked separately below.
See the worked answer
- Each
INSERTmatches values to named columns. A1 and A2 have distinct IDs, so the primary key permits them despite their sharedevent_key. TEMP is a practice draft. - The targeted correction is
UPDATE authorizations SET source_file = 'gate.csv' WHERE id = 'A1';. A2 still hasmirror.csvafterward. - The targeted deletion is
DELETE FROM authorizations WHERE id = 'TEMP';. FinalSELECTshows A1 / EXIT-7 / gate.csv and A2 / EXIT-7 / mirror.csv. - Without
WHERE,UPDATEwould change every source andDELETEremove every table row. The test shows a possible duplication mechanism, not who triggered it.
You can produce and read a targeted change. Next you will undo a bad group of writes with a transaction and reject a second copy of one event.
Before you leave
Remember this
- DML changes rows:
INSERTadds,UPDATEchanges, andDELETEremoves;SELECTlets you inspect the state. - In
INSERT, values match the named columns in the same order. - A unique
iddoes not stop A1 and A2 sharingevent_key = 'EXIT-7'when that field has no uniqueness rule. WHEREtargets A1 for correction and TEMP for deletion; without it, every row may be affected.- A simulation on a copy demonstrates a technical possibility, not an author or facts from the original register.
Continue with the integrated lessons
After the lesson and its mission, work through the additional lessons below in order. Each workshop supplies its own fictional data: do not merge identifiers or times from separate exercises into the story timeline.
Part of the lesson · keep nearby
New words, explained
These are the names of ideas used in the lesson above. Return here whenever a word feels unfamiliar.
- DML
- The SQL part that adds, changes or removes rows in existing tables.
- INSERT
- A command adding a new row with supplied values.
- VALUES
- The list of values matched to columns named by
INSERT. - UPDATE
- A command modifying one or more columns of existing rows.
- SET
- The
UPDATEpart stating the new value. - DELETE
- A command removing rows that match its condition.
- WHERE
- A condition limiting rows targeted by
UPDATEorDELETE.
Approfondissements de ce cours
Télécharger le jeu de données de cet atelier. Sa préparation sur une base de test isolée est confiée à la personne qui administre l’atelier ; les lectures utilisent ensuite le compte et les paramètres qu’elle fournit.
Insérer une ou plusieurs lignes avec un contrat explicite
INSERT INTO lot VALUES (...) utilise implicitement l’ordre de toutes les colonnes de la table. Un changement de schéma ou deux valeurs texte inversées peut alors casser le chargement ou produire une ligne incorrecte. Préfère INSERT INTO lot (format_fichier, date_reception, nom_source) VALUES ('csv','2026-11-06 10:00:00','ventes.csv'); : l’ordre des valeurs correspond à celui de la liste explicite.
Les valeurs texte et dates littérales sont entre apostrophes, les nombres et le marqueur NULL ne le sont pas. 'NULL' est le texte de quatre lettres, pas une absence de valeur. Une colonne omise prend son défaut selon sa définition ; elle peut être refusée si une valeur obligatoire manque. Une colonne AUTO_INCREMENT est généralement omise de la liste, afin que le moteur la génère, plutôt que d’envoyer manuellement un nouvel identifiant.
Pour plusieurs lignes, sépare les tuples de valeurs par des virgules après VALUES. Tous les tuples partagent la même liste de colonnes et doivent avoir la même arité ; utilise NULL seulement là où il correspond réellement à une absence autorisée. Une insertion groupée réduit les échanges, mais choisis une taille raisonnable et une stratégie transactionnelle. Après exécution, vérifie le nombre de lignes et les éventuels avertissements.
MySQL propose aussi INSERT INTO lot SET format_fichier='csv', ... ; cette variante rapproche nom et valeur, mais elle est spécifique au dialecte et ne remplace pas VALUES pour l’insertion de plusieurs tuples. Il faut savoir la reconnaître dans du code existant. Pour un pipeline Python, écris plutôt une requête paramétrée et emploie l’API de traitement groupé du connecteur ; ne construis pas une ligne SQL par concaténation du contenu reçu.
Exemple appliqué aux données
INSERT INTO lot (format_fichier,date_reception,nom_source) VALUES
('csv','2026-11-06 10:00:00','ventes.csv'),
('json','2026-11-06 10:05:00','clients.json');
MySQL 8.4 dans un environnement de test autorisé ; exemple non exécuté sur un serveur MySQL pendant cette adaptation.
À toi de jouer
Pourquoi faut-il écrire une liste de colonnes dans un INSERT utilisé par un pipeline ?
Voir la correction expliquée
Elle rend l’association entre champs et valeurs explicite, permet d’omettre les colonnes générées ou à défaut et évite de dépendre de l’ordre physique du schéma. Elle ne dispense pas de valider les types et le contrat.
Références : Insertion.
Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 46–48. Consulter le PDF source et ses illustrations · Provenance. Licence Creative Commons 6 2.0 (libellé exact de la couverture ; modalités précises non résolues)
Modifier ou supprimer seulement les lignes voulues
DELETE FROM lot WHERE lot_id=21; supprime les lignes satisfaisant le filtre. UPDATE lot SET nom_source='ventes_corrigees.csv', commentaire='Nom confirmé' WHERE lot_id=21; modifie une ou plusieurs colonnes des lignes choisies. La liste après SET utilise des affectations séparées par des virgules ; le filtre choisit les lignes, pas les colonnes.
Sans WHERE, DELETE vise toutes les lignes et UPDATE modifie toute la table selon son expression. Avant l’écriture, exécute un SELECT avec le même prédicat et contrôle le périmètre, les clés et le nombre attendu. Pour une modification unitaire, une clé unique est plus sûre qu’un nom qui peut être partagé. Le fait d’avoir vu une seule ligne lors d’un essai ne prouve pas l’unicité future.
La source qualifie DELETE d’irréversible sans nuance. Avec un moteur transactionnel tel qu’InnoDB, une opération non validée peut être annulée dans une transaction adaptée ; après COMMIT ou en autocommit, un simple ROLLBACK n’annule pas rétrospectivement la modification. La transaction, l’isolation et les modifications concurrentes doivent être prises en compte. Une sauvegarde protège d’autres scénarios, mais ne remplace pas le contrôle du filtre.
Décide si supprimer physiquement correspond au besoin : la traçabilité d’une livraison peut exiger de marquer son état, de conserver le motif ou de transmettre une suppression aux systèmes dérivés. Les corrections doivent rester explicables. Après l’écriture, contrôle le résultat et le statut transactionnel ; ne confonds pas nombre de lignes trouvées, affectées ou effectivement changées selon l’API.
Exemple appliqué aux données
START TRANSACTION;
SELECT lot_id, nom_source FROM lot WHERE lot_id=21;
UPDATE lot SET commentaire='Contrôle effectué' WHERE lot_id=21;
SELECT lot_id, commentaire FROM lot WHERE lot_id=21;
ROLLBACK; -- atelier : annulation au lieu de validation
MySQL 8.4 dans un environnement de test autorisé ; exemple non exécuté sur un serveur MySQL pendant cette adaptation.
À toi de jouer
Deux lots portent le même nom. Comment corriger un seul lot ? Qu’apporte la transaction ?
Voir la correction expliquée
Identifier le lot par une clé unique après lecture de contrôle, appliquer le filtre sur cette clé, vérifier le résultat avant COMMIT dans une transaction adaptée. Une transaction ouverte peut permettre ROLLBACK ; elle ne corrige pas automatiquement un mauvais choix déjà validé.
Références : Modification · Suppression · Transactions.
Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 67–68. Consulter le PDF source et ses illustrations · Provenance. Licence Creative Commons 6 2.0 (libellé exact de la couverture ; modalités précises non résolues)
Écrire depuis d’autres tables avec un périmètre contrôlé
INSERT INTO livraison(colonnes...) SELECT expressions... FROM profil_flux WHERE ... insère directement les résultats d’une lecture. Chaque expression correspond par position à la colonne de destination ; nombre, ordre et types doivent convenir. Les expressions peuvent mélanger valeurs littérales et colonnes de référence. Le nom des alias de sortie ne réordonne pas automatiquement les valeurs à la destination.
Pour ajouter une livraison du profil clients sans mémoriser son identifiant, sélectionne son profil_id et son format_id par une clé fiable. Si le filtre renvoie deux profils, deux lignes peuvent être insérées ; s’il n’en renvoie aucun, rien n’est inséré. Ne présume pas le nombre de résultats. L’exemple du livre a une incohérence de sexe entre la constante insérée et le tableau affiché ; dans cette adaptation, le résultat doit être vérifié par requête et non recopié du tableau historique.
UPDATE peut utiliser une sous-requête dans WHERE pour retrouver le périmètre, et dans SET pour calculer une nouvelle valeur. Une sous-requête scalaire dans SET doit respecter sa cardinalité ; une absence peut produire NULL, incompatible avec certaines colonnes. Une recherche par nom non unique peut modifier plusieurs livraisons. Contrôle les clés et le nombre de lignes avant de lancer la correction.
MySQL impose des restrictions lorsque la table modifiée est lue dans une sous-requête de la même instruction, avec notamment l’erreur 1093 dans certaines formes. La formulation du livre « toujours impossible » est trop générale pour les versions actuelles : certaines tables dérivées matérialisées ou réécritures sont admises sous conditions. Ne contourne pas la restriction au hasard ; une jointure ou une étape de préparation explicite est souvent plus facile à vérifier.
UPDATE livraison l JOIN profil_flux p ON p.profil_id=l.profil_id SET l.nom=... WHERE ... utilise une jointure pour trouver le périmètre et éventuellement les valeurs de remplacement. Les jointures externes et plusieurs entrées sont possibles selon la syntaxe, mais vérifie l’unicité des correspondances : une source ambiguë n’est pas une bonne règle de correction. Ne recopie pas une description dans tous les noms sous prétexte qu’une jointure le permet.
Pour supprimer selon une table liée, DELETE l FROM livraison l JOIN format_ref f ON f.format_id=l.format_id WHERE ... précise la table cible après DELETE. Les entrées utilisées pour sélectionner ne sont pas toutes supprimées automatiquement. Une sous-requête dans WHERE peut aussi définir le filtre, avec les restrictions du dialecte. Les clés étrangères peuvent refuser la suppression ou provoquer des actions référentielles : compte les effets indirects.
Teste d’abord les lectures correspondantes et utilise une transaction adaptée pour les modifications de données de l’atelier. Une instruction complexe n’abolit ni la nécessité de contrôler les doublons ni celle d’enregistrer les motifs de correction. Après écriture, vérifie les lignes et le nombre obtenu avant validation ; les exemples ci-dessous se terminent par ROLLBACK pour conserver le jeu initial.
Exemple appliqué aux données
START TRANSACTION;
INSERT INTO livraison(livraison_id,format_id,profil_id,nom,date_reception)
SELECT 6,format_id,profil_id,'clients_j2','2026-11-02 10:00:00'
FROM profil_flux WHERE profil_id=3;
SELECT livraison_id,format_id,profil_id,nom FROM livraison WHERE livraison_id=6;
DELETE l FROM livraison AS l
JOIN format_ref AS f ON f.format_id=l.format_id
WHERE l.livraison_id=6 AND f.designation='json';
SELECT COUNT(*) FROM livraison WHERE livraison_id=6;
ROLLBACK;
Atelier sur les tables format_ref, profil_flux et livraison de la base de test.
À toi de jouer
Quelle différence existe entre une sous-requête scalaire dans SET et un SELECT utilisé pour INSERT ?
Voir la correction expliquée
La première attend au plus une ligne et une colonne pour une valeur ; le second peut produire plusieurs lignes à insérer. Dans les deux cas, cardinalité et types doivent être contrôlés.
Références : INSERT SELECT · Restrictions des sous-requêtes · DELETE.
Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 123–128. Consulter le PDF source et ses illustrations · Provenance. Licence Creative Commons 6 2.0 (libellé exact de la couverture ; modalités précises non résolues)
Préparer, stocker et maintenir une donnée fiable
La préparation met les données en forme pour le stockage et les traitements futurs. Appliquer des standards cohérents, nettoyer lorsque nécessaire et relier les enregistrements peut réduire doublons et incohérences. Anonymiser les données lorsque cela est nécessaire ; la préparation doit tenir compte des accès réellement nécessaires aux utilisateurs métier.
L’intégration dans les magasins de données doit préserver les valeurs et les relations utiles. Une préparation insuffisante, des flux mal intégrés ou des jointures incorrectes peuvent introduire inexactitudes et corruption. Des standards incompatibles entre sources rendent les rapprochements trompeurs ; documenter les conventions et le sens des clés avant de joindre.
Des métadonnées trop pauvres ou une documentation absente empêchent de comprendre les choix de préparation. Garder les règles de transformation, leur version et leurs limites permet de reproduire le traitement et de déterminer si une anomalie existait déjà ou a été créée par une opération.
Une donnée exacte aujourd’hui peut devenir périmée : certaines coordonnées changent, les systèmes évoluent et leurs formats divergent. Surveiller régulièrement la qualité des données qui changent, au lieu de considérer une importation réussie comme un résultat définitif. Une donnée sans responsable actif risque de perdre progressivement son utilité.
À toi de jouer
Deux sources donnent des codes client incompatibles. Peut-on joindre sur le nom ?
Voir la correction expliquée
Pas sans mesurer le risque de faux rapprochements. Définir un référentiel et une méthode documentée, isoler les ambiguïtés et vérifier cardinalités et taux de non-correspondance. Conserver les informations de provenance.
Références : Cadre officiel et guides associés.
Adapté de The Government Data Quality Framework, Government Data Quality Hub, gouvernement britannique, pages 15–16. Consulter le PDF source et ses illustrations · Provenance. Open Government Licence v3.0, © Crown copyright 2020 ; droits de tiers réservés lorsque signalés.