← Complete program

Chapter 8 · Course 2 c08-m02

How do you find the right rows?

Your goal Select and order useful table rows while treating missing times as unknown, never as zero or an invented hour.

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.

01

Story · optional context

The story so far

You are Aster Motors’ new data recruit. After the crash that hurt Luca, Noctis 01 vanished; a log attributes an exit to your ID and Voss demands your suspension. In the gate database copy, code NOCTIS-01 appears at North and then South. Imani wants the relevant passages, but one South row has no time. Mara asks you to show it as incomplete data, not invent a place for it in the timeline.

You can read this lesson directly. A table has rows and columns; SQL reads them with SELECT ... FROM. Here you will add conditions with WHERE, an explicit order with ORDER BY, a result limit and a check for missing values. The query uses fictional data and does not prove that a repeated code names the same physical car.

02

Before the lesson

Purpose of this course

Select and order useful table rows while treating missing times as unknown, never as zero or an invented hour.

Topics covered

Write a WHERE filter and combine conditions with AND or OR.; Use parentheses when several conditions could be misread.; Use IS NULL and IS NOT NULL for missing values.; Read ORDER BY ... ASC and LIMIT without mistaking display for a proven timeline.

What you will learn

  • Write a WHERE filter and combine conditions with AND or OR.
  • Use parentheses when several conditions could be misread.
  • Use IS NULL and IS NOT NULL for missing values.
  • Read ORDER BY ... ASC and LIMIT without mistaking display for a proven timeline.

PART 1 · THE LESSON

Understand step by step

1

Lesson · explanation

A SQL table is a notebook with columns

Imagine a passage notebook. Each row describes one recorded passage, and each column holds one kind of information. The fictional table passages has id, vehicle, gate, and time. P1, for example, records code NOCTIS-01, North gate, and 21:10. A vehicle code is a label in a database; by itself it does not prove which physical car passed.

SQL is a language for asking questions of the table. SELECT id, gate FROM passages; requests two columns from each row. SELECT says what you want to see; FROM passages names the notebook to search. Reading the table does not move a car or erase notebook lines. It produces an answer to a particular question.

In our small table, P2 and P5 have other vehicle codes: TEST-02 and TEST-03. If all rows are displayed together, we might mix vehicles. If we show only two rows chosen by Voss, we might instead hide P4, whose time is missing. You will write the selection rule yourself so Imani can check it.

You can follow this lesson on paper. Draw six cards, P1 to P6, with the values in the mission. When a SQL condition appears, set aside cards that do not match. They are not destroyed; they remain in the fictional table for another question.

Pause and think

What does SELECT id, gate FROM passages; request? Does it delete P4?

See the explanation

It requests the id and gate columns of passages. It deletes no rows.

2

Lesson · explanation

WHERE picks rows that answer a question

WHERE adds a filter. WHERE vehicle = 'NOCTIS-01' keeps rows whose vehicle column contains exactly that text. Single quotation marks surround a text value; vehicle names a column and has no such marks. In our table, P1, P3, P4, and P6 pass this filter.

P2 and P5 leave this result because they have other codes. They still exist in the table. A filter is like looking up one name in a large notebook: turning past other pages does not tear them out. A second query can still find every row.

Narrow the question with AND. vehicle = 'NOCTIS-01' AND gate = 'South' requires both statements for one row. P3, P4, and P6 match; P1 fails because it says North. AND does not mean 'one or the other'. It demands both conditions.

For the investigation, a filtered result tells what the database copy records for a code. It does not prove the code was entered correctly or identify the driver. Mara must show Imani the exact query so she can see why a row appeared or did not appear.

Pause and think

Which rows pass WHERE vehicle = 'NOCTIS-01' AND gate = 'South'?

See the explanation

P3, P4, and P6. P1 has the Noctis code but says North gate.

3

Lesson · explanation

AND, OR, and parentheses prevent a trap

OR means at least one choice fits. To accept North or South for Noctis only, write vehicle = 'NOCTIS-01' AND (gate = 'North' OR gate = 'South'). Parentheses group the two gate choices. Outside that group, the Noctis code remains required. This filter keeps P1, P3, P4, and P6.

Compare vehicle = 'NOCTIS-01' AND gate = 'North' OR gate = 'South'. SQL evaluates AND before OR without parentheses, so this means (vehicle = 'NOCTIS-01' AND gate = 'North') OR gate = 'South'. Every South row might now enter, even one belonging to another vehicle. P2, TEST-02 at South, is the counterexample.

Imagine an invitation saying 'accept pupils from school A wearing blue OR anyone wearing red'. If you meant 'pupils from A wearing blue or red', you needed to group the colors. Parentheses make the SQL rule clear. They are not decoration: they change which results are selected.

Test a filter with at least one card that should enter and one that should stay out. P1 should enter the Noctis North/South result. P2 should remain outside despite its South gate. If P2 appears, check the parentheses before claiming the table is wrong.

Pause and think

Why can P2 appear with the unparenthesized condition even though it says TEST-02?

See the explanation

The final OR gate = 'South' then accepts every South row. Group (gate = 'North' OR gate = 'South') under the Noctis condition.

4

Lesson · explanation

NULL means missing time, not midnight

P4 has code NOCTIS-01 and South gate, but time = NULL. In SQL, NULL marks an absent or unknown value in that field. It is not zero, an empty word, or 00:00. Giving P4 a midnight time would invent a fact. It is also wrong to say P4 proves no passage happened.

Find rows without a time using WHERE time IS NULL. In this small table, P4 matches. Keep rows with a supplied time using WHERE time IS NOT NULL. With the Noctis code, that second condition keeps P1, P3, and P6. Both results answer different questions and can be kept together.

Avoid time = NULL. An unknown marker does not compare like an ordinary time. In SQL, a comparison with NULL does not simply turn true or false. The intended question for a missing field is IS NULL, and IS NOT NULL asks for the other case. Learn them as complete phrases.

A missing time may come from a faulty device, a forgotten field, or a copying problem. We do not know which. Keep ID P4 and request the original record and clock source. The query flags the missing value in the copy; it does not fill the blank for the investigation.

Pause and think

What does WHERE time IS NULL find, and why should P4 not receive 00:00?

See the explanation

It finds P4. NULL means the time is unknown; 00:00 would be an invented precise time.

5

Lesson · explanation

ORDER BY arranges known times for display

ORDER BY time ASC requests increasing time order: smaller recorded values first. For known Noctis times, this gives P1 at 21:10, P3 at 21:25, then P6 at 21:35. The order helps us read the data, but it does not verify that the gate clocks were set correctly.

Add , id ASC as a second rule: ORDER BY time ASC, id ASC. If two passages show exactly the same time, their IDs break the display tie. It is like sorting books first by year, then by title. The second rule does not invent a difference in event time.

For a careful timed list, first filter vehicle = 'NOCTIS-01' AND time IS NOT NULL. P4 then receives no invented position among known times. The ordered result shows only what the copy can place in order. A second IS NULL query keeps incomplete cases visible.

Even supplied times can be hard to compare if gate clocks were mis-set or use different time zones. SQL sorts stored values, not guaranteed real-world time. Imani needs clock-source information before claiming a car was somewhere at the crash moment.

Pause and think

What order does ORDER BY time ASC, id ASC give for known Noctis times?

See the explanation

P1 21:10, P3 21:25, then P6 21:35. P4 has no time to place.

6

Lesson · explanation

LIMIT 2 displays two rows, not all facts

LIMIT 2 requests at most two rows in the final result. Add it after filtering Noctis rows with known times and sorting by time ASC, id ASC: the first two are P1 and P3. P6 is the third known row and is not shown in this short display. It has not been erased from the table.

Write query parts in this order: SELECT, FROM, WHERE, ORDER BY, then LIMIT. Read that as several questions: which columns, which table, which rows, what order, and how many to show. LIMIT without an explicit order does not promise the two earliest times.

Voss shows two passages only. This may be because a LIMIT 2 was applied; it does not mean the database contains only two Noctis passages. The practice copy has P1, P3, P4, and P6 under that code. Two are displayed in the limited list, one more has a known time, and one has no time.

As a counterexample, LIMIT 2 without first filtering vehicles might show P1 and P2. P2 is TEST-02, so this would not answer 'first two Noctis rows'. Build the entire SQL question and inspect what it leaves out before telling a story from two displayed lines.

Pause and think

After a Noctis filter, time IS NOT NULL, ascending order, and LIMIT 2, which IDs appear? Are P6 and P4 deleted?

See the explanation

P1 then P3 appear. P6 remains in the table after them; P4 remains with unknown time.

7

Lesson · explanation

Two complementary queries keep P4 visible

The example's first question is SELECT id, vehicle, gate, time FROM passages WHERE vehicle = 'NOCTIS-01' AND time IS NOT NULL ORDER BY time ASC, id ASC LIMIT 2;. Read it piece by piece. It uses passages, keeps Noctis rows with known times, sorts them, and shows P1 and P3. It makes no claim about rows without times.

The second question is SELECT id, vehicle, gate FROM passages WHERE time IS NULL;. It looks for all rows lacking a time and finds P4 here. Notice that, as written, it does not filter by vehicle. Other missing-time rows would also appear if the table had them. In our six-row practice set, only P4 matches.

One result cannot replace the other. The first list helps inspect known times; the second shows what is missing. Publishing only the first might make a reader think P4 does not exist. Assigning P4 00:00 to make it appear in the first would invent a time. Keep both questions and describe the scope of each.

In your report, say 'P1 and P3 are the first two known times in the copy; P4 is a South Noctis row without a time and needs the original'. This separates observation, limitation, and next check. It does not claim where the physical car was at the moment of the crash.

Pause and think

Why must the second query not be replaced by assigning P4 00:00?

See the explanation

It flags an unknown time for checking. 00:00 would invent a value and a place in the timeline.

8

Lesson · explanation

Answer Imani without making SQL absolute proof

For the first task, write WHERE vehicle = 'NOCTIS-01' AND (gate = 'North' OR gate = 'South'). Parentheses keep P2 out even though it used South. The copy gives P1, P3, P4, and P6. This shows what the vehicle code says in a fictional table, not the certain identity of a physical car.

For the short list, write SELECT id, time FROM passages WHERE vehicle = 'NOCTIS-01' AND time IS NOT NULL ORDER BY time ASC, id ASC LIMIT 2;. P1 at 21:10 appears before P3 at 21:25. P6 at 21:35 would appear with a larger limit. Do not claim these two lines exhaust all passages.

For the gap, write SELECT id, gate FROM passages WHERE time IS NULL;. P4 is the only row in this small table without a time. Keep its ID, South gate, and unknown-time status. Ask Imani for the original record and clock information rather than guessing midnight or dropping the row.

Voss claims the car was at South at crash time. This SQL copy alone cannot support that claim: a South row lacks a time, clocks may need checking, and a repeated code does not automatically identify one physical car. Your two results show the uncertainty and give the investigation a checkable next question.

Pause and think

Which IDs are the first two known Noctis times, and which row remains separate without a time?

See the explanation

P1 then P3 are the first two known times in the copy. P4 remains separate with an unknown time.

Visual guide

Four stages of the SQL question

  1. 1FROM passages: choose the table
  2. 2WHERE: keep rows matching conditions
  3. 3ORDER BY: request an explicit order
  4. 4LIMIT 2: display only two rows

A second IS NULL query keeps passages without a time visible.

SQL · query or table structure

Two complementary readings

SELECT id, vehicle, gate, time
FROM passages
WHERE vehicle = 'NOCTIS-01' AND time IS NOT NULL
ORDER BY time ASC, id ASC
LIMIT 2;

SELECT id, vehicle, gate
FROM passages
WHERE time IS NULL;

The first question shows the two earliest Noctis passages with known times. The second flags missing-time rows. They answer different questions and should be read together.

PART 2 · WATCH IT WORK

A complete worked example

Follow each step, then the result

Worked example: do not lose P4

The practice table has P1 Noctis North 21:10, P2 Test-02 South 21:20, P3 Noctis South 21:25, P4 Noctis South without time, P5 Test-03 North 21:40, P6 Noctis South 21:35.

  1. Write WHERE vehicle = 'NOCTIS-01': P1, P3, P4 and P6 match. Other vehicle codes leave only this answer, not the database.
  2. Add AND time IS NOT NULL: P4 leaves the timed list because its time is unknown, not because the row vanished.
  3. Add ORDER BY time ASC, id ASC LIMIT 2: P1 21:10 then P3 21:25 appear. P6 would be third.
  4. Run WHERE time IS NULL separately: P4 appears. Mark its time for verification and keep its ID to request the source.
What this shows

A short known-time list and a missing-time list complement each other. Never turn an absence into certainty.

How this helps with your mission

Mara's worked example starts with Noctis rows, removes P4 only from the known-time list, then sorts and limits that list to P1 and P3. It finds P4 again with time IS NULL. The mission asks for exactly those two readings plus a parenthesized North/South filter. Together they show Imani what is known, what is missing, and why Voss's selection cannot prove the car's real position at crash time.

PART 3 · YOUR TURN

Use the lesson to solve the mission

Story scene · practical task

Mission: the missing hour

In the story, Voss shows only two NOCTIS-01 passages and claims the car was at South when the crash happened. Mara notices P4, a South row without a time. Imani gives you fictional rows: P1 Noctis North 21:10, P2 Test-02 South 21:20, P3 Noctis South 21:25, P4 Noctis South NULL, P5 Test-03 North 21:40, P6 Noctis South 21:35. You have a few fictional minutes to prepare a checkable answer.

Your task

  1. Write a filter retaining Noctis rows at North or South, with clear parentheses.
  2. Write a query showing the first two Noctis rows with known times, then name their IDs.
  3. Write a query finding rows without times and name the matching row.
  4. Explain why P4 must neither be placed at 00:00 nor removed from the investigation.

How to know you have succeeded

  • The filter connects Noctis to (gate = 'North' OR gate = 'South').
  • Ascending order and LIMIT 2 give P1 then P3 among known times.
  • time IS NULL finds P4.
  • P4 stays as a row to verify; its time position remains unknown.
Open this mission in the browser workspace

Try code or SQL and keep a local draft. The mission questions are checked separately below.

Check the facts in your mission

Answer each factual question, then write your report in your own words. The program checks the choices; compare the report with the worked answer below.

1. Which filter keeps Noctis rows at North or South without accepting `TEST-02` at South?
2. Which query gives the first two known times for `NOCTIS-01`?
3. After that filter, sort, and `LIMIT 2`, which IDs appear?
4. Which SQL question finds P4 without inventing a time?
5. What can the table copy establish about P4 and the real timeline?
See the worked answer
  1. Use WHERE vehicle = 'NOCTIS-01' AND (gate = 'North' OR gate = 'South'). Parentheses prevent accepting every South row regardless of vehicle.
  2. Use SELECT id, time FROM passages WHERE vehicle = 'NOCTIS-01' AND time IS NOT NULL ORDER BY time ASC, id ASC LIMIT 2;. P1 21:10 and P3 21:25 appear.
  3. Use SELECT id, gate FROM passages WHERE time IS NULL;. P4 is the missing-time row in this small table.
  4. NULL is not 00:00 and does not mean “no passage.” Imani requests the original record and clock source before concluding a timeline.

You can filter and order without erasing unknowns. Next you will count rows by group and distinguish repeats from a simple total.

Before you leave

Remember this

  • WHERE filters rows for a question without deleting them; AND needs both conditions, while OR accepts at least one.
  • Parentheses in vehicle = 'NOCTIS-01' AND (gate = 'North' OR gate = 'South') prevent all South vehicles from entering.
  • NULL marks a missing time: find it with IS NULL, not = NULL, and do not replace it with midnight.
  • ORDER BY time ASC, id ASC LIMIT 2 shows P1 then P3 among known times; P6 and P4 remain in the table.
  • A query describes the available copy. It proves neither clock accuracy nor the car's or driver's identity.

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.

A–Z

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.

Filter
A rule deciding which rows appear in the result.
WHERE
The SQL part introducing conditions for rows.
AND
Requires two conditions to be true together.
OR
Accepts a row when at least one condition is true.
NULL
SQL marker for an absent or unknown value; it is neither zero nor an empty string.
ORDER BY
Requests a display order using one or more columns.
LIMIT
Maximum number of result rows requested.

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.

Filtrer les lignes, combiner les critères et traiter NULL

SELECT choisit des expressions ou colonnes ; FROM indique leur table. SELECT lot_id, nom_source FROM lot; exprime une projection explicite. SELECT * est pratique pour une exploration, mais un pipeline doit demander les champs nécessaires : cela stabilise son contrat et évite de transférer des données inutiles. WHERE restreint ensuite les lignes selon un prédicat, par exemple format_fichier='csv'.

Les comparaisons courantes sont =, <, <=, >, >= et <> ou !=. Les dates littérales doivent être de format explicite et leur précision doit correspondre à celle de la colonne. MySQL propose <=> pour une égalité qui traite aussi NULL ; c’est une particularité utile à reconnaître. Pour les tests d’absence lisibles et portables, utilise IS NULL et IS NOT NULL.

AND exige les deux conditions, OR en accepte au moins une, NOT inverse une condition. MySQL propose aussi XOR, vrai lorsque exactement une de ses deux conditions est vraie, avec les règles de NULL correspondantes. Les formes &&, || et ! existent dans certains modes, mais préfère les mots : || peut servir à concaténer dans d’autres dialectes ou modes. Une expression booléenne peut être inconnue en présence de NULL.

Parenthèse chaque groupe pour exprimer la règle métier. (format_fichier='csv' AND nom_source IS NOT NULL) OR format_fichier='json' accepte tous les JSON ; format_fichier='csv' AND (nom_source IS NOT NULL OR commentaire IS NOT NULL) impose CSV dans tous les cas. La priorité des opérateurs ne doit pas devenir un jeu de devinettes pour le lecteur.

Une règle complexe peut être décomposée en niveaux : accepter les lots arrivés à partir de 2026, ou les CSV nommés, ou les CSV sans nom reçus avant une date de seuil. Écris les trois cas, puis les groupes. Pour un DATETIME, une date sans heure renvoie généralement à minuit : date_reception > '2025-12-31' n’exprime pas exactement « après l’année 2025 ». Utilise une borne '2026-01-01 00:00:00' avec >=.

nom_source = NULL ne sélectionne pas les noms absents ; la comparaison produit inconnu, que WHERE ne retient pas. nom_source <> NULL ne sélectionne pas non plus les valeurs connues. Écris nom_source IS NULL ou IS NOT NULL. De même, NOT nom_source='x' n’inclut pas automatiquement les noms inconnus. Distingue un nom manquant d’un nom vide et décide explicitement si chacun est accepté.

Exemple appliqué aux données

SELECT lot_id, format_fichier, nom_source FROM lot
WHERE (format_fichier='csv' AND nom_source IS NULL)
   OR (format_fichier='json' AND date_reception >= '2026-01-01 00:00:00');

MySQL 8.4 dans un environnement de test autorisé ; exemple non exécuté sur un serveur MySQL pendant cette adaptation.

À toi de jouer

Écris un filtre sélectionnant les lots CSV dont le nom manque, ou tous les lots JSON reçus depuis le 1er janvier 2026.

Voir la correction expliquée

WHERE (format_fichier='csv' AND nom_source IS NULL) OR (format_fichier='json' AND date_reception >= '2026-01-01 00:00:00'). Les parenthèses rendent chaque cas explicite.

Références : Lecture et filtres · Comparaisons.

Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 53–57. 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)

Ordonner, dédupliquer et paginer une lecture

Sans ORDER BY, SQL ne promet pas un ordre de restitution stable. Le fait de constater l’ordre d’insertion ou l’ordre d’une clé lors d’un essai ne constitue pas un contrat. ORDER BY date_reception ASC trie de la plus ancienne à la plus récente ; DESC inverse le sens. Pour le texte, le tri dépend de l’interclassement et n’est pas un simple ordre universel des lettres.

Plusieurs clés de tri s’appliquent dans l’ordre donné : ORDER BY format_fichier, date_reception DESC, lot_id DESC. Le dernier identifiant départage ici les dates identiques. Un ENUM MySQL peut être ordonné selon les indices déclarés plutôt que lexicalement. Vérifie donc le type et l’interclassement avant d’interpréter un classement.

DISTINCT supprime les doublons du résultat projeté. SELECT DISTINCT format_fichier FROM lot; renvoie chaque valeur distincte du format ; ajouter nom_source change la combinaison comparée. DISTINCT ne supprime pas les lignes de la table et ne corrige pas forcément un doublon métier. Une différence de grain doit se traiter à la conception et dans la logique d’ingestion.

LIMIT 6 OFFSET 3 saute les trois premières lignes de l’ordre demandé puis renvoie au plus six lignes. LIMIT 10 est équivalent à LIMIT 10 OFFSET 0. MySQL accepte aussi LIMIT 3,6 où le premier nombre est le décalage, ordre inverse de la forme avec OFFSET. LIMIT n’est pas pris en charge de la même manière dans tous les SGBD ; vérifie le dialecte plutôt que de présenter cette forme comme la norme universelle.

Une pagination reproductible nécessite un ordre total et une vue cohérente des données. Si des lignes sont insérées ou supprimées entre deux pages, OFFSET peut provoquer des omissions ou répétitions même avec ORDER BY. Pour de gros volumes, un curseur fondé sur une clé et une stratégie d’instantané peut être préférable. Ne confonds pas lecture des dix premières lignes et échantillon représentatif.

Exemple appliqué aux données

SELECT lot_id, date_reception, nom_source FROM lot
ORDER BY date_reception DESC, lot_id DESC
LIMIT 5;

MySQL 8.4 dans un environnement de test autorisé ; exemple non exécuté sur un serveur MySQL pendant cette adaptation.

À toi de jouer

Comment obtenir les cinq dernières livraisons de façon déterministe si plusieurs ont la même heure ?

Voir la correction expliquée

ORDER BY date_reception DESC, lot_id DESC LIMIT 5, à condition que lot_id soit une clé unique. Le second critère départage les égalités.

Références : SELECT et ses clauses.

Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 58–61. 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)

Rechercher un motif, un intervalle ou une liste

LIKE compare un texte à un motif : % représente une suite de zéro ou plusieurs caractères et _ exactement un caractère. Le livre indique parfois zéro ou un pour _ : cette imprécision est corrigée. Ainsi 'c%' accepte c, csv et client ; 'c_' exige deux caractères, et ne correspond pas au seul c. Ce mécanisme est un motif avec jokers, pas une mesure de proximité orthographique.

Pour chercher un joker littéral, utilise un échappement explicite, par exemple nom_source LIKE '%!_%' ESCAPE '!' recherche un trait de soulignement. L’antislash historique interagit avec l’échappement des chaînes et les modes SQL ; une convention explicite évite des surprises. NOT LIKE exclut les correspondances, mais ne transforme pas NULL en texte connu.

La sensibilité à la casse dépend du jeu de caractères, de l’interclassement et des opérandes. La source utilise LIKE BINARY pour forcer une comparaison différente : dans un projet actuel, choisis les règles de comparaison correspondant à la colonne et au besoin, plutôt que de supposer que tous les LIKE ignorent la casse. Le fait que MySQL puisse convertir un nombre en texte pour LIKE n’en fait pas une recherche numérique portable ou optimale ; un identifiant préfixé est souvent mieux modélisé comme texte.

BETWEEN minimum AND maximum inclut ses deux bornes et correspond à >= minimum AND <= maximum pour des comparaisons compatibles. Il fonctionne avec nombres, dates et textes selon leurs règles de comparaison. Il n’est pas intrinsèquement plus rapide que les deux comparaisons. Pour une période de jours appliquée à un DATETIME, préfère souvent une borne haute exclusive : >= '2026-11-01' AND < '2026-12-01' inclut toutes les heures de novembre sans fabriquer une dernière seconde.

IN ('csv','json','parquet') exprime l’appartenance à une liste et évite une série d’égalités reliées par OR. NOT IN exprime l’exclusion, mais une valeur NULL dans la colonne ou la liste doit être analysée avec la logique à trois valeurs. Le type des membres et leur conversion doivent correspondre à la colonne. Une longue liste de valeurs peut aussi être mieux représentée par une table de référence et une jointure.

Exemple appliqué aux données

SELECT lot_id, nom_source FROM lot
WHERE format_fichier IN ('csv','json')
  AND date_reception >= '2026-11-01'
  AND date_reception < '2026-12-01';

MySQL 8.4 dans un environnement de test autorisé ; exemple non exécuté sur un serveur MySQL pendant cette adaptation.

À toi de jouer

Écris un filtre des livraisons CSV ou JSON reçues en novembre 2026. Pourquoi éviter BETWEEN deux dates à minuit ?

Voir la correction expliquée

WHERE format_fichier IN ('csv','json') AND date_reception >= '2026-11-01' AND date_reception < '2026-12-01'. Une borne haute égale à minuit du dernier jour exclurait les heures ultérieures de ce jour.

Références : Comparaisons et intervalles · Motifs LIKE.

Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 62–65. 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)