Chapter 12 · Course 2 c12-m02
What information was true that day?
Your goal Link each event to the registry version valid at the event time and spot labels with no matching version.
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 has been missing since the crash that injured Luca, and Voss uses an authorization bearing your name to accuse you. Mara Sol, your data lead, removed a revision that had been wrongly counted as a third road event. Imani still sees another inconsistency: the report called the vehicle recorded as R2 at 21:25 the “Noctis prototype.” The registry for label NOCTIS-01 changed at 20:00. If R2 is linked to the older record, the report describes the wrong vehicle.
You can read this lesson without earlier story knowledge. A fact table says what happened: here a passage with a time and a label. A dimension table provides context: here which physical asset the registry associated with that label during a given period. You will link each fact to the version valid at its time in a fictional copy. That registry association is a clue to check against physical evidence; it does not settle the case by itself.
Before the lesson
Purpose of this course
Link each event to the registry version valid at the event time and spot labels with no matching version.
Topics covered
Distinguish road fact, vehicle dimension, and displayed label.; Read valid_from and valid_to as a [start, end) interval.; Build a time-aware join with the fact time inside the ON condition.; Compare a fixed-label report with a temporal join and state the evidence limit.
What you will learn
- Distinguish road fact, vehicle dimension, and displayed label.
- Read valid_from and valid_to as a [start, end) interval.
- Build a time-aware join with the fact time inside the ON condition.
- Compare a fixed-label report with a temporal join and state the evidence limit.
PART 1 · THE LESSON
Understand step by step
Lesson · explanation
A label does not always name the same object
You are Aster Motors' new data recruit. Luca was injured in a crash, and Noctis 01 is missing. Voss uses an authorization bearing your name to accuse you. He now shows a screenshot claiming the prototype was on the road at 21:25. Imani asks you to check that statement before it spreads. NOCTIS-01 appears in the data, but a displayed name does not by itself prove which physical object was there.
Think of a school locker labeled 12. On Monday it holds Ana's coat; on Friday it holds Sam's. Reading only the number 12 cannot tell you whose coat was inside on Wednesday. You need a dated record. In the same way, the Aster Motors registry linked the label NOCTIS-01 to different assets at different times.
Before 20:00 UTC, the registry linked NOCTIS-01 to PROTOTYPE-01. From 20:00 UTC onward, another entry linked it to SHELL-02, a test shell resembling the prototype. The first report used a fixed entry saying that the label always named the prototype. That shortcut turned a reused label into a permanent physical identity.
This lesson studies a fictional registry copy and does not change the original. The join will show what this copy says for each time. It will not alone prove that the shell or prototype was physically on the road. Imani must compare the registry with photos, witnesses and material traces. Distinguish a source's description from the physical reality.
Pause and think
Does the text NOCTIS-01 in an event prove that PROTOTYPE-01 was on the road?
See the explanation
No. The label's association changed at 20:00 UTC; check the time and registry version, then seek independent physical evidence.
Lesson · explanation
Separate an event fact from its description
A fact table stores events. In road_events, each row has event_id, event_at and vehicle_label. R1 is a reported passage at 19:30 UTC with label NOCTIS-01. R2 is a reported passage at 21:25 UTC with the same label. These rows state what a source recorded; they do not yet identify the corresponding physical asset.
A dimension table provides context. label_history holds the label, an asset in physical_asset, and validity limits valid_from and valid_to. Imagine dated display lists beside museum tickets. A ticket tells you which exhibit case was visited; the dated list tells you which object carried that case number on a particular day.
The shared vehicle_label field finds candidate entries in both tables. Yet joining on the label alone would pair R1 and R2 with both registry versions. Each event could appear twice in the output. One might then mistake four joined rows for four road passages, although there are only two facts. Time must select the valid description.
The fixed report is a counterexample: it reads NOCTIS-01 and automatically substitutes PROTOTYPE-01 without checking 19:30 or 21:25. That produces a simple answer, but it is wrong for R2 according to the registry copy. Ask the more precise question: which asset did this source associate with the label at the instant of the passage?
Pause and think
Which table holds R2, and which table describes the asset linked to its label?
See the explanation
road_events holds the R2 fact; label_history describes the association valid at R2's time.
Lesson · explanation
Read a period with an included start and excluded end
The first entry applies from April 1, 2026 at 00:00 UTC inclusive until April 12 at 20:00 UTC exclusive. This is sometimes written [start, end). The left bracket includes the start; the right parenthesis excludes the end. The second entry begins precisely at 20:00 UTC. Both entries touch at a boundary without claiming the same instant.
Picture two teams handing over a relay at 20:00. Team A is responsible immediately before 20:00; Team B takes over at 20:00. No instant belongs to both teams when the periods are built correctly. A passage exactly at 20:00 therefore takes the new SHELL-02 entry, not the older PROTOTYPE-01 entry.
R1 at 19:30 is half an hour before the boundary, so the first period links it to PROTOTYPE-01. R2 at 21:25 is an hour and twenty-five minutes after the boundary, so the second links it to SHELL-02. Both events carry the same label. Their event times change which registry description applies.
The second entry's valid_to is NULL here. It means no end has yet been recorded in this exercise. It is not midnight and does not prove the entry will remain valid forever. A later registry update could close it. Open-ended describes the present state of this copy, not the future of the asset.
Pause and think
Which entry applies at exactly 20:00 UTC?
See the explanation
The new SHELL-02 entry; the older one ends at 20:00 exclusive, and the new one begins at 20:00 inclusive.
Lesson · explanation
Add event time to the join condition
A join pairs rows from two tables when conditions hold. The first condition is e.vehicle_label = h.vehicle_label: the fact and registry entry use the same label. That is not enough because NOCTIS-01 has two entries. We must also test whether e.event_at, the fact time, lies inside the valid period of each candidate entry.
The start condition is e.event_at >= h.valid_from. It accepts an event at the first instant of the period. The end condition is e.event_at < h.valid_to when an end exists. It rejects an event at the instant the period stops. Together they implement the [start, end) rule you saw in the 20:00 relay example.
For an open end, SQL uses (h.valid_to IS NULL OR e.event_at < h.valid_to). IS NULL allows the SHELL-02 entry whose end is not recorded. Do not write h.valid_to = NULL: SQL checks a missing value with IS NULL. Parentheses keep the open-end or before-end alternatives together as one logical test.
Apply all three checks to R2. Its label matches both entries; 21:25 is not earlier than the old entry's 20:00 end; 21:25 is after the new entry's 20:00 start and that entry remains open. Exactly one entry matches: SHELL-02. Without the time checks you would not get that unique answer.
Pause and think
Which time comparisons belong with the label equality in the join?
See the explanation
e.event_at >= h.valid_from and (h.valid_to IS NULL OR e.event_at < h.valid_to).
Lesson · explanation
Keep facts with no match by using LEFT JOIN
LEFT JOIN starts with all facts in road_events and looks for a matching entry in label_history for each one. If it finds none, the fact remains visible and the joined entry's columns are NULL. Imagine laying out every museum ticket, even if the display catalog cannot explain a case number on one ticket.
A row without physical_asset does not mean no car existed. It means this registry copy supplies no valid association for that event's label and time. Perhaps a period was missed, a label is wrong or the registry is incomplete. Keeping the row lets Imani request a check instead of letting the gap disappear.
The time tests belong inside ON, beside the label equality. Moving them into WHERE after a LEFT JOIN can remove an unmatched fact, because the h values on that row are missing. The output would look tidy, showing only successfully linked facts. That would hide the very gap Imani needs to see.
Suppose R3 occurs at 18:00 with an unknown label. With the conditions in ON, R3 remains in the output with physical_asset = NULL. If a WHERE filter requires its time to fall between bounds on h, R3 may be removed. This counterexample shows why the position of a condition changes whether missing context stays visible.
Pause and think
Under LEFT JOIN, what does physical_asset = NULL mean for a retained fact?
See the explanation
No valid registry entry matched that fact; it does not prove that no physical vehicle existed.
Lesson · explanation
Spot overlapping validity periods
A temporal join should normally find at most one valid entry per event and label. If two registry periods overlap, one fact may match both. For example, imagine the prototype entry ended at 22:00 while the shell entry began at 20:00. R2 at 21:25 would have two competing descriptions, and the query would show two R2 rows.
Those two result rows would not prove two road passages. They would be one fact paired with two conflicting registry descriptions. Counting joined rows as events would double the passage by mistake. It resembles two catalogs claiming to describe the same numbered museum case at the same time. Resolve the catalog contradiction before making claims about the object.
Check registry windows for overlap when one label is meant to have one asset at a time. Check gaps too. If one period ended at 19:00 and the next began at 20:00, an hour would have no entry; LEFT JOIN would preserve events from that hour with NULL. Both checks protect the meaning of the output.
In the supplied copy, the old entry ends exactly when the new one begins, at 20:00 UTC. R1 has one match and R2 has one different match. That is a property of these small exercise data. In an investigation, inspect the full original history rather than assuming that every date is as tidy as this example.
Pause and think
If an overlap makes R2 appear twice after the join, are two passages proven?
See the explanation
No. One R2 fact matched two competing entries; the registry overlap needs investigation.
Lesson · explanation
Read times without confusing text and time
The lesson's small program writes all times in the same UTC format, such as 2026-04-12T21:25:00Z. The Z marks UTC. Because every string uses the same form and zone, comparing text works for this demonstration. This teaching choice also lets the SQL example run in SQLite.
Real systems may receive times from several time zones, in different formats or with different precision. Comparing such strings alphabetically may produce the wrong time order. Use an appropriate timestamp type, normalize instants and state the UTC convention before joining. Otherwise a badly converted R2 time could be assigned to the wrong validity period.
Imagine two clocks, one set to UTC and the other to a local zone. They can show different numbers for the same instant. Looking only at the displayed digits might make one event seem earlier than another when it was not. A time value needs its zone, much as a measurement needs its unit.
For this mission, both facts and both registry entries already use the same UTC convention. You may compare 19:30, 20:00 and 21:25 directly in the practice copy. Do not extend this convenience to unknown files. Before publishing a time-based conclusion, Imani needs to check that the original timestamps followed the stated convention and were not reformatted without a trace.
Pause and think
Why can text timestamps be compared in this copy but need more care in production?
See the explanation
All exercise timestamps share one canonical UTC format; mixed zones or formats could make text order differ from real time order.
Lesson · explanation
Explain the result and its limits to Imani
Mara places the two registry cards before you. R1 at 19:30 UTC belongs to the period linking NOCTIS-01 to PROTOTYPE-01. R2 at 21:25 UTC belongs to the period linking the same label to SHELL-02. The boundary is 20:00. This corrects Voss's fixed report, which attached the old prototype description to R2.
State your conclusion with its source: in this registry copy, R2's label links to SHELL-02 at 21:25. Do not write that the table physically proves a shell was driven, or that Voss falsified the report. The join reveals a checkable mismatch between the screenshot and the registry version valid at the recorded passage time.
Keep the two road_events rows, both label_history versions, the exact query and its result. Then request the original registry history, photos, witness accounts or material records. If a fact lacks a registry match, leave it visible with NULL and flag the gap. If two periods overlap, flag the competing descriptions rather than counting two passages.
This gives Imani an immediate answer before the old description becomes an apparently certain accusation. The urgency belongs to the story; the exercise has no real timer. The next lesson will show how to preserve old versions when the registry changes. Here you have already learned the essential question: which description was valid at the exact time of the fact?
Pause and think
Which sentence about R2 stays within what the join proves?
See the explanation
According to this registry copy, NOCTIS-01 links to SHELL-02 at 21:25 for R2; the physical object still needs independent corroboration.
Visual guide
The registry changes the label's asset
- 1Before 20:00 UTC: NOCTIS-01 → PROTOTYPE-01
- 2At 20:00 UTC: registry version changes
- 3After 20:00 UTC: NOCTIS-01 → SHELL-02; R2 is at 21:25
Joining R2 to the old prototype entry would ignore the event time.
SQL · query or table structure
Join the fact to its valid version
CREATE TABLE road_events (
event_id TEXT PRIMARY KEY,
event_at TEXT NOT NULL,
vehicle_label TEXT NOT NULL
);
CREATE TABLE label_history (
vehicle_label TEXT NOT NULL,
physical_asset TEXT NOT NULL,
valid_from TEXT NOT NULL,
valid_to TEXT
);
INSERT INTO road_events VALUES
('R1', '2026-04-12T19:30:00Z', 'NOCTIS-01'),
('R2', '2026-04-12T21:25:00Z', 'NOCTIS-01');
INSERT INTO label_history VALUES
('NOCTIS-01', 'PROTOTYPE-01', '2026-04-01T00:00:00Z', '2026-04-12T20:00:00Z'),
('NOCTIS-01', 'SHELL-02', '2026-04-12T20:00:00Z', NULL);
SELECT e.event_id, e.event_at, h.physical_asset
FROM road_events AS e
LEFT JOIN label_history AS h
ON e.vehicle_label = h.vehicle_label
AND e.event_at >= h.valid_from
AND (h.valid_to IS NULL OR e.event_at < h.valid_to)
ORDER BY e.event_id;The SQL creates two events and two label versions. All times use the same canonical UTC text form so this exercise also runs in SQLite. The temporal join yields R1 / PROTOTYPE-01 and R2 / SHELL-02. A fact with no matching entry would remain under LEFT JOIN with NULL physical_asset.
PART 2 · WATCH IT WORK
A complete worked example
Follow each step, then the result
Worked example: the 21:25 passage
The prototype entry stops applying at 20:00 UTC. The shell entry begins at 20:00 UTC. R2 has time 21:25 UTC and label NOCTIS-01.
- Match R2's label to the two candidate NOCTIS-01 entries.
- Compare 21:25 with the prototype end: 21:25 is not before 20:00, so that entry does not apply.
- Compare 21:25 with the shell start: it is after 20:00 and the end is open, so SHELL-02 applies.
- Write “according to this registry, R2 was associated with SHELL-02” rather than claiming this table alone proves physical identity.
An event time selects its descriptive version; the evidence remains limited to the source's reliability.
How this helps with your missionTo answer Imani, match each fact to the NOCTIS-01 entry valid at its time: R1 at 19:30 links to PROTOTYPE-01, while R2 at 21:25 links to SHELL-02 after the 20:00 UTC boundary. Put label equality and [start, end) checks in a LEFT JOIN ON condition so unmatched facts remain visible. Present the result as a registry association to corroborate independently.
PART 3 · YOUR TURN
Use the lesson to solve the mission
Story scene · practical task
Mission: the vehicle changes in the report
Voss displays a report screenshot claiming the prototype was on the road during the crash. Mara lays two label records on the table, separated at 20:00 UTC. Imani gives you R1 at 19:30 and R2 at 21:25; both say NOCTIS-01. Explain clearly why attaching the older record to R2 is misleading before the screenshot spreads further. The urgency is part of the story; the exercise has no timer.
Your task
- Assign R1 and R2 to their correct registry periods.
- Write the two time comparisons needed for a temporal join.
- Explain how LEFT JOIN and time conditions in ON expose events without a registry match.
- State an accurate conclusion about R2 and a check still needed.
How to know you have succeeded
- R1 matches PROTOTYPE-01 and R2 matches SHELL-02 in the copy.
- event_at >= valid_from and event_at < valid_to, except for NULL end.
- An unmatched fact remains with NULL for the joined asset.
- The source links R2 to a shell; the physical object still needs corroboration.
Try code or SQL and keep a local draft. The mission questions are checked separately below.
See the worked answer
- R1 at 19:30 is before the boundary and receives PROTOTYPE-01. R2 at 21:25 is after it and receives SHELL-02.
- Write e.event_at >= h.valid_from AND (h.valid_to IS NULL OR e.event_at < h.valid_to), together with e.vehicle_label = h.vehicle_label.
- LEFT JOIN retains all road_events rows. When no period matches, the h side is NULL. Equivalent conditions in WHERE could remove that row and hide a missing registry period.
- Say: “in this registry copy, the R2 label links to SHELL-02 at 21:25.” Inspect the original history and seek independent physical evidence before asserting what drove.
You have linked each passage to the description valid at its time. Next you will keep those older descriptions when the registry changes.
Before you leave
Remember this
- A fact records a passage and time; a dimension describes the asset linked to its label during a period.
- The
[start, end)period includesvalid_fromand excludesvalid_to; aNULLend is open here. - A temporal join adds
event_at >= valid_fromandevent_at < valid_towhen an end exists. LEFT JOINwith tests inONkeeps an unmatched fact visible withphysical_asset = NULL.- R1 at 19:30 links to PROTOTYPE-01; R2 at 21:25 links to SHELL-02 in this copy.
- A registry may have gaps or contradictions; this join alone does not prove which object really drove.
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.
- Fact
- Record of a measurable event, such as R2 at 21:25.
- Dimension
- Description adding context to a fact; here the asset linked to a label.
- Join
- Pairing rows from two tables according to a condition.
- Temporal join
- Join that also checks that the event time falls inside the description's valid period.
- Label
- Displayed name in data; it can be reused and need not uniquely identify a physical item.
- valid_from
- First instant when a registry version applies.
- valid_to
- First instant when it stops applying; NULL means open-ended in this exercise.
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.
Choisir et observer la date de référence d’un traitement
Le rappel des types DATE, TIME, DATETIME, TIMESTAMP et YEAR reprend les notions de la leçon sur les types ; leurs bornes et conversions sont celles de la version actuelle, pas toutes les simplifications de 2012. L’affichage 'AAAA-MM-JJ' ne signifie pas que le stockage physique est une chaîne. Les dumps réimprimés aux pages192–194 sont l’état d’atelier déjà développé, transposé ici au registre de livraisons.
CURDATE() et CURRENT_DATE donnent la date courante ; CURTIME() et CURRENT_TIME l’heure. Plusieurs formes SQL autorisent aussi l’absence de parenthèses. La valeur est interprétée dans le contexte temporel de la session ; ne la mélange pas à un fichier fourni dans un autre fuseau sans conversion et convention explicites.
NOW(), CURRENT_TIMESTAMP(), LOCALTIME et LOCALTIMESTAMP expriment des formes de date et heure courantes dans MySQL. Les appellations ne les rendent pas interchangeables avec des types identiquement nommés dans tous les autres SGBD. Pour un pipeline, décide si la date logique de traitement est fournie comme paramètre ou tirée de l’horloge au moment de l’exécution.
SYSDATE() peut lire le moment effectif de son appel, tandis que NOW() est normalement fixé au début de l’instruction. Le PDF les présentait presque comme synonymes ; une instruction longue peut rendre la différence visible et des paramètres du serveur influent sur certains comportements. Il faut éviter de multiplier des lectures de l’horloge quand toutes les lignes d’un lot doivent partager la même référence.
Insérer NOW() dans une colonne DATE ou TIME peut produire une conversion qui retire la partie non représentable : le jour est conservé pour DATE, l’heure pour TIME. Cette perte est voulue seulement si le modèle le prévoit. Une table de test comportant les trois types permet de constater la différence sans confondre le résultat d’affichage et le type.
UNIX_TIMESTAMP() sans argument produit un epoch en secondes. Un nombre d’epoch n’est pas mauvais par nature, contrairement au jugement absolu du livre : il peut être nécessaire dans un contrat d’échange, à condition de définir origine, unité, plage et précision. Pour les opérations calendaires relationnelles, un type temporel approprié facilite souvent les requêtes et validations.
Exemple appliqué aux données
SET time_zone='+00:00';
SELECT CURDATE(),CURRENT_DATE,CURTIME(),CURRENT_TIME,NOW(),SYSDATE(),LOCALTIME,LOCALTIMESTAMP,UNIX_TIMESTAMP();
CREATE TEMPORARY TABLE observation_temps (jour DATE,heure TIME,instant_local DATETIME);
INSERT INTO observation_temps VALUES(NOW(),NOW(),NOW());
SELECT * FROM observation_temps;
Dates d’exemple fixes pour des résultats reproductibles ; le fuseau de session fait partie du contrat.
À toi de jouer
Pourquoi fournir une date logique à un traitement rejoué plutôt que lire systématiquement NOW() ?
Voir la correction expliquée
Un rejeu d’une ancienne période doit utiliser le même périmètre logique ; l’horloge actuelle changerait les filtres et pourrait produire un autre résultat. Conserver séparément date logique et date effective d’exécution.
Références : Fonctions temporelles MySQL 8.4.
Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 192–197. 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)
Extraire, formater et interpréter les dates
Le format de présentation n’impose pas de stocker une date métier comme une chaîne libre. DATE(date_reception) extrait la date civile et TIME l’heure ; HOUR, MINUTE et SECOND extraient les éléments de l’heure. DAY ou DAYOFMONTH donne le jour du mois et DAYOFYEAR son numéro dans l’année. Les valeurs invalides ou incomplètes demandent un traitement explicite, pas une confiance automatique dans une conversion.
DAYOFWEEK numérote normalement dimanche1 à samedi7 ; WEEKDAY numérote lundi0 à dimanche6. DAYNAME donne un nom de jour. MONTH donne le numéro de mois, MONTHNAME son libellé et YEAR l’année. SET SESSION lc_time_names='fr_FR' change les noms produits pour la session ; il ne change pas le fuseau ni les valeurs conservées.
WEEK, WEEKOFYEAR et YEARWEEK représentent des semaines selon des conventions qui peuvent différer. Un mode peut préciser début de semaine, numérotation et règle de première semaine. WEEKOFYEAR correspond à une convention particulière, tandis que WEEK sans mode dépend de réglages. Une date de début janvier peut appartenir à une semaine de l’année précédente ; pour un rapport hebdomadaire, conserve l’année de semaine avec son numéro et teste les frontières d’année.
DATE_FORMAT(date,format) produit un texte selon des spécificateurs. Pour les jours : %d donne deux chiffres, %e sans zéro initial, %D un suffixe ordinal anglais, %w un indice dimanche0, %W le nom entier et %a l’abrégé. Pour les mois : %m deux chiffres, %c forme courte numérique, %M nom et %b abrégé. %Y est l’année complète, %y deux chiffres : préfère la forme complète pour les échanges.
Pour l’heure, %r est une forme douze heures avec AM/PM et %T une forme vingt-quatre heures ; %h et %l donnent l’heure sur douze heures, %H et %k sur vingt-quatre, avec ou sans zéro initial. %i représente les minutes, %s ou %S les secondes et %p AM/PM. La casse distingue par exemple le mois %M et les minutes %i. Les caractères ordinaires sont recopiés ; une apostrophe de texte littéral doit être doublée selon la syntaxe SQL.
On peut assembler les éléments avec CONCAT_WS ou écrire DATE_FORMAT(date_reception,'le %W %e %M %Y'). TIME_FORMAT sert à l’heure et n’accepte pas utilement les spécificateurs de calendrier ; l’appliquer à une DATE peut produire une conversion incohérente ou un avertissement. Utilise une donnée et un format dont le sens correspondent, plutôt que copier une sortie ancienne étonnante.
GET_FORMAT(type,standard) fournit des modèles prédéfinis pour DATE, TIME ou DATETIME et les étiquettes EUR, USA, ISO, JIS ou INTERNAL. Par exemple DATE/EUR produit %d.%m.%Y, DATE/USA %m.%d.%Y et DATE/ISO ou JIS %Y-%m-%d ; INTERNAL supprime les séparateurs. Pour DATETIME, vérifier aussi les séparateurs d’heure et l’année complète. L’étiquette ISO de cette fonction ne constitue pas à elle seule une sérialisation ISO8601 avec fuseau.
STR_TO_DATE(texte,format) interprète un texte selon le modèle et peut produire une DATE, un TIME ou un DATETIME selon les éléments. Le résumé source nomme par erreur STR_TO_FORMAT : la fonction à utiliser est STR_TO_DATE. Un modèle doit être non ambigu ; les règles de validation peuvent évoluer, donc traite les entrées invalides et avertissements. Associer cette fonction à GET_FORMAT n’en fait pas une détection automatique de tous les formats possibles.
Exemple appliqué aux données
SET NAMES utf8mb4;
SET SESSION lc_time_names='fr_FR';
SELECT livraison_id,DATE(date_reception),TIME(date_reception),DAYOFWEEK(date_reception),WEEKDAY(date_reception),YEARWEEK(date_reception,3),DATE_FORMAT(date_reception,'le %W %e %M %Y à %Hh%i') AS reception_lisible
FROM livraison ORDER BY livraison_id;
SELECT STR_TO_DATE('06/11/2026 à 14h30','%d/%m/%Y à %Hh%i'),GET_FORMAT(DATE,'EUR');
Dates d’exemple fixes pour des résultats reproductibles ; le fuseau de session fait partie du contrat.
À toi de jouer
Pourquoi ne faut-il pas comparer deux semaines uniquement par WEEK(date) ?
Voir la correction expliquée
Le mode de semaine et l’année peuvent différer, notamment à la frontière décembre/janvier. Définir une convention et utiliser une identité de semaine incluant l’année correspondante.
Références : Fonctions temporelles MySQL 8.4.
Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 198–205. 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)
Calculer une durée, une échéance et une limite de période
DATEDIFF(a,b) calcule le nombre de jours entre les parties date de a et b, en ignorant les heures ; son sens est a−b. TIMEDIFF(a,b) produit une durée de type TIME à partir de deux expressions compatibles. TIMESTAMPDIFF(unité,début,fin) calcule au contraire fin−début dans l’unité demandée. Mélanger ces sens inverse le signe du résultat.
TIMESTAMPDIFF peut exprimer secondes, minutes, heures, jours, semaines, mois, trimestres ou années selon les unités autorisées. Une DATE utilisée avec une unité plus petite que le jour est complétée à minuit selon les règles du moteur. Une différence calendaire en mois ou années n’est pas une simple division d’un nombre de secondes par une constante ; pense aux limites, mois de tailles différentes et années bissextiles.
INTERVAL exprime une quantité et une unité. Les formes simples SECOND, MINUTE, HOUR, DAY, WEEK, MONTH et YEAR côtoient des formes composées comme MINUTE_SECOND, HOUR_SECOND, HOUR_MINUTE, DAY_SECOND, DAY_MINUTE, DAY_HOUR et YEAR_MONTH. Une valeur composée doit respecter le modèle attendu, par exemple '2 03:04:05' DAY_SECOND. Évite les ponctuations libres historiques qui masquent les erreurs de contrat.
DATE_ADD(date,INTERVAL q unité) et ADDDATE dans cette forme ajoutent l’intervalle ; ADDDATE(date,n) peut aussi ajouter n jours. date + INTERVAL ... est une autre écriture, avec l’intervalle également permis à gauche pour l’addition. TIMESTAMPADD(unité,q,date) propose une syntaxe sans le mot INTERVAL et son domaine d’unités documenté. Utilise MICROSECOND pour les fractions quand cela convient à la version, plutôt que présumer le nom historique FRAC_SECOND partout.
ADDTIME ajoute une durée TIME à une heure ou date-heure. SUBDATE, DATE_SUB et SUBTIME sont les formes de soustraction correspondantes ; date−INTERVAL demande la date à gauche et l’intervalle à droite. Ajouter une quantité négative revient à soustraire la positive et inversement. Les opérations sur mois et années doivent être testées aux fins de mois ; ajouter un mois ne signifie pas ajouter trente jours.
FROM_UNIXTIME transforme un epoch en date-heure dans le fuseau de session, et UNIX_TIMESTAMP(dateheure) réalise une conversion inverse dans ses limites. Une conversion aller-retour peut être ambiguë pour certaines heures locales lors des changements d’heure. Un epoch reçu en millisecondes ne se passe pas directement à une fonction attendant des secondes ; documente les unités.
MAKEDATE(année,jour_dans_année) construit une date et MAKETIME(heures,minutes,secondes) une durée ou heure compatible. SEC_TO_TIME transforme des secondes en TIME ; TIME_TO_SEC fait l’inverse. TIME peut dépasser vingt-quatre heures mais possède une plage bornée : un temps de traitement de plusieurs mois n’entre pas forcément dans ce type.
LAST_DAY(date) donne la date du dernier jour du mois. Comparer février2028 et février2100 illustre les règles bissextiles : 2100 n’est pas une année bissextile. Pour des filtres de période, un intervalle fermé à gauche et ouvert à droite reste souvent plus simple que calculer une dernière microseconde. Le choix d’un fuseau et d’un calendrier fait partie du calcul, pas seulement de l’affichage.
Exemple appliqué aux données
SELECT DATEDIFF('2026-11-08 01:00:00','2026-11-06 23:00:00'),TIMEDIFF('2026-11-08 01:00:00','2026-11-06 23:00:00'),TIMESTAMPDIFF(HOUR,'2026-11-06 23:00:00','2026-11-08 01:00:00');
SELECT DATE_ADD('2026-11-06',INTERVAL 12 WEEK),SUBTIME('12:30:00','01:15:00'),MAKEDATE(2028,60),MAKETIME(2,3,4),SEC_TO_TIME(90061),TIME_TO_SEC('25:01:01'),LAST_DAY('2100-02-03');
Dates d’exemple fixes pour des résultats reproductibles ; le fuseau de session fait partie du contrat.
À toi de jouer
Pourquoi DATEDIFF peut-il donner2 alors que moins de48heures se sont écoulées ?
Voir la correction expliquée
Il soustrait les parties date sans les heures. Pour une durée en heures, utiliser une fonction et une convention temporelle adaptées, comme TIMESTAMPDIFF après choix explicite du fuseau.
Références : Fonctions temporelles MySQL 8.4.
Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 206–212. 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)