9. Structured Query Language (SQL)
Opening
Big idea: Ask the database a precise question and check what its result really means.
Use a separate practice folder for the programs. Each example is self-contained unless its section says otherwise.
- Create and constrain related tables.
- Insert, query, update and delete records with explicit conditions.
- Use functions, aggregates, grouping, set operations and joins.
- Recognise nulls, duplicates, ordering and dialect differences.
Read the rule, trace the worked example, and try the quick check before reading its answers. When a result surprises you, change one input and explain the difference.
This is an original lesson following the listed syllabus topics. Examples, datasets, questions and diagrams were created for this edition.
The previous chapter designed the store. It separated things from events and chose keys. This chapter uses that design. It asks questions, adds rows and changes values without breaking the rules.
The chapter builds in five stages. First it reads the starting data carefully.
Then it sorts statements into families. Then it creates tables with types and constraints.
Then it loads, queries and edits rows. Last it combines and summarises with functions, groups, sets and joins.
One running example threads through most sections. A school equipment store keeps one asset record per device and one loan record per borrowing.
A second small dataset, a table of test scores, joins the chapter where averages per group are needed.
Study by predicting. Cover each result table and say its rows aloud first. When a prediction fails, find the first clause where your trace diverged. That clause holds the lesson. Short sentences carry one idea each.
No database server is needed to follow the reasoning. Every query is traced row by row on paper-sized tables. The result tables shown were all checked by execution. Trust them, but still trace them yourself.
Expect the same vocabulary to return in every section. Clause, condition, key, null and aggregate keep one meaning throughout. When a sentence confuses you, check which term it uses.
Questions in this chapter are practical on purpose. Each query starts from the same baseline unless its section says otherwise. That reset keeps an earlier update from silently changing a later answer.
A precise question plus a visible trace gives a trustworthy answer.
9.1 Introduction
Each SQL query asks a question about some starting data. If you do not know that starting state, an output table is difficult to check. Begin by reading what one row represents and what each column means.
In the equipment dataset, asset rows describe stored equipment. Loan rows describe related events. An unknown unit count is different from a recorded zero, so a query must respect that distinction.
- Identify the table and the records it describes.
- Read the fields needed by the question.
- State the desired result in plain English before translating it into SQL.
A school office keeps a register of lab devices and a separate slip for each borrowing.
SQL is a language for defining and working with relational data. A statement is one complete instruction to the database system.
A result set is the table of rows and columns returned by a query. Statements describe the wanted result, and the engine chooses an execution strategy.
Think of the school office at stock-check time. The register lists each device once.
A pile of slips lists each borrowing. The office needs answers like which devices have more than ten units, or which loans point at one device.
SQL asks such questions precisely.
A phone contact list shows the same split. Contacts are the stored things.
The call log records events. A question such as which numbers were called twice joins the two lists.
SQL performs that kind of combination on tables.
A query asks a question. Its result set answers it. The stored tables remain unchanged by asking.
These lessons use one original equipment dataset. Each worked query starts from the same baseline unless its section explicitly shows a change. This reset keeps an earlier update from silently changing a later answer.
Read the asset table row by row. Each row describes one device category: its id, its label, its kind and its recorded unit count.
The loan table, shown in later sections, records borrowing events that refer to these ids.
| asset_id | label | kind | units |
|---|---|---|---|
| 31 | screen P | display | 14 |
| 42 | screen Q | display | 8 |
| 53 | camera P | imaging | 6 |
| 64 | sensor P | sensing | NULL |
Read the table again as facts. Device 31 is screen P, a display item with 14 units.
Device 42 is screen Q, a display item with 8 units. Device 53 is camera P, an imaging item with 6 units.
Device 64 is sensor P, a sensing item whose count is not yet recorded.
NULL means a missing, unknown or inapplicable value under the documented policy. In this dataset, the sensor count is not yet recorded. It does not mean the count is zero. Zero would claim that no sensor exists.
The table holds four asset rows. A count query confirms that number, so later grouping answers can be checked against it.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT COUNT(*) AS total_assets FROM asset;| total_assets |
|---|
| 4 |
Read the result. One row, one column, the value 4. COUNT(*) counts rows, whatever they contain. It does not inspect the units column.
SQL dialects differ. These lessons use MySQL-oriented terminology and portable syntax where possible. Check the version and configuration of your practice system when a command or conversion behaves differently.
Read the diagram. State the question in ordinary words first. Then write the query with its clauses. The engine plans the execution. Finally read the result table against the original question.
A query should carry a question you can explain without reading its syntax aloud. If you cannot say what it asks in one sentence, rewrite the question before rewriting the query.
How many display items have a known unit count?
Goal. Turn the office question into a checkable answer.
Approach. Name the table, the kind filter and the null rule.
Trace. The asset table holds two display rows, 31 and 42. Both carry known counts, 14 and 8. The sensing row is not display, and the imaging row is not display.
Result. Two display items with known counts.
Result: Two: screen P and screen Q. Both display rows carry recorded counts.
Read the data first. Every later answer depends on that starting picture.
9.2 Structured Query Language (SQL)
SQL commands can describe structure, change rows or ask for a result. SELECT is the command you use to request data. The server interprets it according to the chosen database system’s rules.
Read a query as instructions with separate responsibilities. FROM identifies the source. SELECT identifies what to show. WHERE, when present, limits which source rows qualify. ORDER BY decides how the result should be arranged.
- Say which table provides the information.
- Say which values should appear in the result.
- Add filtering and ordering only when the question needs them.
Office staff sort their paperwork into structure changes, row changes and questions.
SQL statement families separate changes to structure from changes to stored rows. Data definition changes the shape of storage. Data manipulation changes the stored rows. Data query returns data or derived results.
Think of the school register again. Ordering a new column for the register is a structure change.
Writing a new device line is a row change. Asking which devices are low on stock is a question.
Each job needs different care.
A kitchen shows the same split. Buying a new shelf changes storage. Putting jars on it changes contents. Counting jars answers a question. You would not demolish the shelf to remove one jar.
| Family or role | Examples | Purpose |
|---|---|---|
| Data definition | CREATE, ALTER, DROP | Create or change structure. |
| Data manipulation | INSERT, UPDATE, DELETE | Change stored rows. |
| Data query | SELECT | Return data or derived results. |
Read the table. The first row reshapes containers. The second row edits contents. The third row asks and reports. Matching the family to the task prevents demolishing structure when only one row should change.
SQL keywords are generally case-insensitive, but identifier and text-comparison behaviour can depend on the server, operating system and collation. Use consistent spelling instead of relying on a universal case rule.
String literals use single quotes in these examples.
A command-line client commonly sends a statement when you finish it with a semicolon. A continuation prompt means the statement is incomplete; the prompt itself is not part of the statement.
Do not copy mysql> or continuation arrows into a SQL script.
CREATE DATABASE practice_store;
USE practice_store;Read the two lines. The first line creates a separate practice database. The second line selects it for the following statements. These are MySQL management commands; other database systems manage databases differently.
Use a separate practice database so learning queries cannot alter real records. A practice area turns mistakes into lessons instead of incidents.
The next query returns one display row. It filters on the units column and orders the single answer explicitly.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT asset_id, label FROM asset WHERE units > 10 ORDER BY asset_id;| asset_id | label |
|---|---|
| 31 | screen P |
Trace it row by row. Device 31 holds 14, which passes. Device 42 holds 8, which fails. Device 53 holds 6, which fails. Device 64 holds NULL, which is not greater than 10. One row qualifies.
An explicit ORDER BY determines the displayed sequence. Without it, do not depend on an observed order, even if several runs happen to return the same arrangement.
Read the diagram. FROM names the source table. WHERE keeps matching rows. SELECT shapes the output columns. ORDER BY arranges the surviving rows. Written order puts SELECT first, but execution starts from FROM.
| Written order | Execution order | Job |
|---|---|---|
| SELECT | 3 | Choose output expressions. |
| FROM | 1 | Name the source table. |
| WHERE | 2 | Keep rows that satisfy the condition. |
| ORDER BY | 4 | Arrange the result rows. |
Read the table. The middle column numbers the execution steps. FROM runs first because later steps need its rows. SELECT runs third because it shapes rows that WHERE has already kept.
Classify three office jobs: add a location column, correct one unit count, list low-stock labels.
Goal. Assign each job to its statement family.
Approach. Ask whether the job reshapes storage, rewrites rows or asks a question.
Trace. A new column reshapes the table, so it is definition. Correcting a count rewrites a stored value, so it is manipulation. Listing labels asks and reports, so it is query.
Result. Definition, manipulation, query in that order.
Result: ALTER TABLE for the column, UPDATE for the count, SELECT for the list.
Name the family before writing the statement. The family decides the risk.
9.3 Data Types and Constraints in MySQL
Choosing an integer field means the value is meant to be a whole number. It does not by itself say whether a negative number is allowed or whether the value may be missing. Additional rules express those requirements.
NOT NULL and a nonnegative CHECK solve different problems. A count may satisfy the nonnegative condition when known but still be unknown. Use both requirements when the task needs a known nonnegative count.
- Describe the field’s meaning in everyday language.
- Choose a type that represents that meaning.
- Add each required constraint separately and test values that should be rejected.
A label needs letters, a count needs numbers, and a stock rule needs an explicit check.
Types describe representable values, while constraints express additional rules. A type says what shape a value has. A constraint says which values the task accepts. Both are needed for reliable storage.
Think of admission forms. A roll-number box accepts digits. A name line accepts letters. A tick box for bus use accepts only yes or no. The box shape is the type; the yes-or-no rule is the constraint.
A library card shows the same split. The member number field holds digits. The rule that every card needs a different number is separate. Shape alone cannot enforce uniqueness.
A type fixes the kind of value. A constraint states an extra rule that stored values must satisfy.
| MySQL type | Typical use |
|---|---|
| INT | Whole-number counts or identities. |
| DECIMAL(p,s) | Exact fixed-point values with stated precision and scale. |
| FLOAT or DOUBLE | Approximate numeric measurements. |
| CHAR(n) | Fixed-length character fields under the type’s storage and comparison rules. |
| VARCHAR(n) | Variable-length character fields within a limit. |
| DATE | Calendar dates. |
Read the table. INT suits counts and ids.
DECIMAL suits exact money-like values with stated places. FLOAT and DOUBLE suit approximate measurements.
CHAR and VARCHAR suit text of fixed or variable length. DATE suits calendar days.
| Example field | Suitable type | Why |
|---|---|---|
| asset_id | INT | An identity used in comparisons and joins. |
| label | VARCHAR(40) | A short name of varying length. |
| units | INT | A whole-number count of items. |
| loan date | DATE | A calendar day, not free text. |
Read the table. Each field gets the type matching its meaning. The id and the count are whole numbers. The label is variable text. A calendar fact would use DATE rather than a typed date string.
| Constraint | Rule |
|---|---|
| NOT NULL | A value must be supplied. |
| UNIQUE | A declared set of values must satisfy the DBMS’s uniqueness rules. |
| PRIMARY KEY | The chosen unique non-null row identity. |
| FOREIGN KEY | A permitted reference to a parent key. |
| CHECK | A row condition that must not evaluate false. |
| DEFAULT | A value used when an insertion omits that column in a way that invokes its default. |
Read the table. NOT NULL demands presence.
UNIQUE demands distinctness. PRIMARY KEY combines distinctness with presence as the row identity.
FOREIGN KEY demands a permitted parent. CHECK demands a true-enough row condition.
DEFAULT supplies a fallback value.
A check such as units >= 0 does not by itself require a known count. A comparison with NULL is unknown, and a CHECK generally does not reject that unknown result. Add NOT NULL when a recorded count is mandatory.
Read the diagram. Name the meaning first. Then pick the fitting type. Then add each rule separately. Finally test with a value that should be rejected. A design that skips the last step is a hope, not a check.
Should an optional phone-like identifier use INT?
It may have leading zeros or symbols and is not normally used in arithmetic.
Result: A documented character field is usually more appropriate than a numeric count type.
A new fee column must hold exact amounts with two decimal places. Which type, and why not FLOAT?
Goal. Choose an exact decimal type.
Approach. Compare exact fixed-point storage with approximate binary storage.
Trace. DECIMAL(8,2) stores each decimal digit exactly. FLOAT stores an approximation, so 0.10 plus 0.20 can print with a tiny error. Money totals must not carry such noise.
Result. Use DECIMAL(8,2); keep FLOAT for approximate measurements.
Result: DECIMAL(8,2), because exact decimal places need exact storage.
Constraint enforcement and accepted type conversions depend on the DBMS version and settings. Use current MySQL documentation and test the required rule on the deployed server; do not infer MySQL type behaviour from SQLite’s more flexible storage rules.
Shape first, rules second, rejection test third. All three protect the data.
9.4 SQL for Data Definition
CREATE TABLE describes how future rows will be stored and checked. It names the columns and can declare identities and relationships. This is a structural operation, not the creation of one ordinary equipment record.
Once a table exists, changing its columns differs from changing values in its rows. ALTER changes structure. UPDATE changes row contents. DELETE removes rows. DROP removes the table itself.
- Define the fields and their constraints.
- Create referenced parent structures before dependent records need them.
- Inspect the structure to confirm it matches the intended design.
The office builds the shelves before placing any files on them.
Define tables around stable identities and explicit relationships. Parent records exist first. Child records refer to them. The structure states the rules before any row arrives.
Think of setting up the register. First the office rules the columns: id, label, kind, units. Then it rules a second page for loans with a column that must name a real device. Only then does writing begin.
A new shelf shows the same order. Fix the brackets, label the sections and state the borrowing rule. Then place the books. Structure before content keeps every later step checkable.
CREATE TABLE asset (
asset_id INTEGER PRIMARY KEY,
label VARCHAR(40) NOT NULL UNIQUE,
kind VARCHAR(20) NOT NULL,
units INTEGER CHECK (units >= 0)
);
CREATE TABLE loan (
loan_id INTEGER PRIMARY KEY,
asset_id INTEGER NOT NULL,
account_tag VARCHAR(20) NOT NULL,
FOREIGN KEY (asset_id) REFERENCES asset(asset_id)
);Read the first block line by line. The CREATE TABLE line names the asset table.
The asset_id line makes an integer primary key. The label line demands a non-null unique name of up to 40 characters.
The kind line demands a non-null category. The units line allows only counts that are not negative.
Read the second block line by line. It names the loan table.
The loan_id line makes its primary key. The asset_id line demands a value on every loan row.
The account_tag line names the borrower account. The FOREIGN KEY line requires each loan reference to name a permitted asset key.
The asset table describes equipment categories and counts. The loan table records events referring to an asset.
The foreign key connects each non-null loan reference to a permitted asset key. The default deletion behaviour should be checked; a production design must choose what should happen to historical loans when an asset is removed.
SHOW TABLES;
DESCRIBE asset;Read the two lines. SHOW TABLES lists the tables in the selected database. DESCRIBE asset shows its columns, types and key flags. Inspecting confirms the structure matches the intended design.
ALTER TABLE asset ADD COLUMN location VARCHAR(40);Read the line. ALTER TABLE changes the schema. The asset table gains a location column holding short text. Existing rows receive NULL in that column unless a default says otherwise.
ALTER TABLE changes the schema. UPDATE changes values in existing rows. DROP TABLE removes a table’s structure and data; DELETE removes selected rows while retaining the table. These commands are not interchangeable.
| Command | Changes | Keeps |
|---|---|---|
| ALTER TABLE | Table shape and columns. | All existing rows, adjusted to the new shape. |
| UPDATE | Values inside matching rows. | The table shape and the other rows. |
| DELETE | Selected rows. | The table and its definition. |
| DROP TABLE | The whole table. | Nothing of that table. |
Read the table. Each command touches a different level. ALTER reshapes. UPDATE rewrites. DELETE removes rows. DROP removes everything. Choosing by level prevents using DROP when one row should go.
Read the diagram. Name things and events first. Create the parent table that others will reference. Then create the child table with its foreign key. Finally inspect and test before loading real data.
The added nullable column does not remove the existing asset rows. The count query below proves it on the same baseline plus the new column.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT COUNT(*) AS known_assets FROM asset;| known_assets |
|---|
| 4 |
Read the result. Four rows survive the structural change.
Columns changed; the row count did not. A real migration may need default values, backfilling and integrity checks.
Practice structural changes on a disposable copy first.
The store wants a warranty-months column, then must correct one count. Which commands, in which order?
Goal. Separate the structural job from the row job.
Approach. Ask which job changes columns and which changes values.
Trace. Adding warranty months changes the shape, so ALTER TABLE applies. Correcting one stored count changes a value, so UPDATE applies. The shape must exist before values fill it.
Result. ALTER TABLE first, then UPDATE for the single row.
Result: Shape with ALTER, values with UPDATE. Never swap their roles.
Containers first, contents second. Rules before rows.
9.5 SQL for Data Manipulation
An INSERT statement has a mapping: a named column receives its corresponding supplied value. An explicit column list makes that mapping visible even if the schema contains other columns.
NULL is a special missing-value marker. Quoting the letters creates an ordinary string instead. Similarly, leaving out a field uses only the default behaviour that the schema and statement actually define.
- Read the named columns in order.
- Match each supplied expression to that column.
- Check required values, defaults and referenced parent records before accepting the row.
Each new line in the register must land under the correct column heading.
Explicit column lists keep insertion intent visible when a table evolves. Each value position matches its named column. A reader can verify the mapping without memorising the full table shape.
Think of a form with labelled boxes. Name goes in the name box, count in the count box. Writing values without box names works only while everyone remembers the box order. Named columns are the box labels.
A seating plan shows the same idea. Each slip names the seat and the guest. Nobody assigns guests by counting chairs from the door. Names beat positions whenever the layout can change.
INSERT INTO asset (asset_id, label, kind, units) VALUES
(31, 'screen P', 'display', 14),
(42, 'screen Q', 'display', 8),
(53, 'camera P', 'imaging', 6),
(64, 'sensor P', 'sensing', NULL);
INSERT INTO loan (loan_id, asset_id, account_tag) VALUES
(71, 31, 'account A'),
(72, 31, 'account B'),
(73, 53, 'account A');Read the first statement row by row. It names four columns: asset_id, label, kind, units.
Row 31 stores screen P, display, 14. Row 42 stores screen Q, display, 8.
Row 53 stores camera P, imaging, 6. Row 64 stores sensor P, sensing, with NULL for the unknown count.
Read the second statement row by row. It names loan_id, asset_id and account_tag.
Loan 71 links asset 31 to account A. Loan 72 links asset 31 to account B.
Loan 73 links asset 53 to account A. Every reference names an asset that the first statement created.
Each value position matches the corresponding named column. Use NULL without quotes for an unknown value; the string 'NULL' is ordinary text.
If a nullable field is omitted and has no other default, the result is normally null under the relevant rules.
Read the diagram. Name the columns first. Match each value to its column in order. Check parent records and constraints before accepting. Only then is the row stored. Skipping the third step stores trouble.
The full table below shows the baseline after both statements. Check each cell against the INSERT lines above. This is the starting picture every later query in the chapter assumes.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT asset_id, label, kind, units FROM asset ORDER BY asset_id;| asset_id | label | kind | units |
|---|---|---|---|
| 31 | screen P | display | 14 |
| 42 | screen Q | display | 8 |
| 53 | camera P | imaging | 6 |
| 64 | sensor P | sensing | NULL |
The unknown count below needs a special test. Ordinary equality cannot match it.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT asset_id, units FROM asset WHERE units IS NULL ORDER BY asset_id;| asset_id | units |
|---|---|
| 64 | NULL |
Read the result. Only device 64 qualifies, because only its units cell holds NULL. The query names the condition IS NULL explicitly. Writing units = NULL would not match it.
A foreign-key parent must exist when the child reference is checked, unless a documented deferred mechanism changes the timing. MySQL’s ordinary InnoDB foreign keys are checked immediately.
Do not insert a loan first and hope its missing asset appears later.
An insert supplies three values but names four columns. What should you inspect?
Count named columns, match their order to the supplied expressions, and decide which values or defaults were intended.
Result: Correct the insertion contract; do not invent a placeholder that violates the field meaning.
One more row can join the baseline without disturbing it. The statement below adds screen R with 3 units, and the display-only query shows exactly where it lands.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT label, units FROM asset WHERE kind = 'display' ORDER BY asset_id;| label | units |
|---|---|
| screen P | 14 |
| screen Q | 8 |
| screen R | 3 |
Trace the check. Screen P passes as display. Screen Q passes as display. Camera P fails as imaging. Sensor P fails as sensing. Screen R passes as display. Three rows qualify in id order.
A generated identifier or default may reduce the values you supply, but only if the schema defines that behaviour. Omitting the column list makes accidental schema-order dependence easier.
Name the columns. Match the values. Check the parents. Then store.
9.6 SQL for Data Query
WHERE is easiest to understand by testing one row at a time. Imagine substituting that row’s values into the condition. If the condition is true, the row can contribute to the result.
After filtering, SELECT chooses the output expressions. ORDER BY arranges those output records. These steps solve different parts of the question, so changing one does not automatically change the others.
- Choose a sample row and test the complete condition.
- Repeat for the other candidate rows.
- Project the requested columns and arrange the result using the explicit ordering rule.
The office asks one question, filters the pile, then sorts the answer.
A query selects columns, filters rows and orders the result through separate clauses. Each clause does one job. Reading them in execution order keeps their effects distinct.
Think of sorting exam slips. First gather the pile from the correct drawer.
Then keep only the slips for this term. Then copy the wanted fields onto the answer sheet.
Then arrange the sheet alphabetically. Each step has its own tray.
A playlist shows the same pipeline. Choose the library, skip the songs you do not want, show title and length, then sort by title. Filtering before sorting avoids arranging songs you will discard.
FROM gathers. WHERE filters. SELECT shapes. ORDER BY arranges. Each clause answers a different part of the question.
The main example lists labels with enough units, arranged from most to fewest. Follow each row through the filter before reading the answer.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT label, units FROM asset
WHERE units >= 8
ORDER BY units DESC, asset_id;| label | units |
|---|---|
| screen P | 14 |
| screen Q | 8 |
Trace all four rows. Screen P holds 14, which satisfies 14 >= 8, so it qualifies.
Screen Q holds 8, which satisfies 8 >= 8, so it qualifies. Camera P holds 6, which fails.
Sensor P holds NULL, and a NULL comparison is not true, so it fails. Two rows qualify.
SELECT chooses output expressions. FROM identifies input tables.
WHERE filters individual rows. ORDER BY controls the result order.
Use ASC or DESC explicitly when it improves clarity. A second ordering key resolves ties in the first.
Read the diagram. Take one candidate row. Test the complete condition with its values. Keep the row or drop it. Repeat for every row. WHERE never sees groups or summaries; it sees single rows only.
| Candidate row | Condition test | Verdict |
|---|---|---|
| screen P, 14 | 14 >= 8 is true. | Kept. |
| screen Q, 8 | 8 >= 8 is true. | Kept. |
| camera P, 6 | 6 >= 8 is false. | Dropped. |
| sensor P, NULL | NULL >= 8 is unknown. | Dropped. |
Read the table. Each row shows one candidate, the test with its own values and the verdict.
The unknown test drops the sensor row without claiming its count is small. Unknown means the row cannot qualify, not that it qualifies as zero.
Use =, <>, <, <=, > and >= for comparisons. Combine conditions with AND, OR and NOT, adding parentheses to make grouping clear.
BETWEEN includes both endpoints. IN tests membership in a list.
LIKE uses % for any sequence and _ for one character under its pattern rules.
The next query combines a pattern with a range. Screen labels start with the word screen followed by a space, and the units must lie between 8 and 14 inclusive.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT label FROM asset
WHERE label LIKE 'screen %' AND units BETWEEN 8 AND 14
ORDER BY asset_id;| label |
|---|
| screen P |
| screen Q |
Trace the pattern first. Screen P, screen Q and sensor P match the screen-space pattern; camera P does not. Then trace the range: 14 and 8 lie inside 8 to 14, while 6 and NULL do not. Two rows satisfy both parts.
Parentheses decide grouping when AND meets OR. The query below keeps display or imaging rows that also carry a known count. Without the parentheses, AND would bind tighter and ask a different question.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT label FROM asset
WHERE (kind = 'display' OR kind = 'imaging') AND units IS NOT NULL
ORDER BY asset_id;| label |
|---|
| screen P |
| screen Q |
| camera P |
Trace each row. Screen P is display with a known count, so it qualifies.
Screen Q is display with a known count, so it qualifies. Camera P is imaging with a known count, so it qualifies.
Sensor P is sensing, so the OR part already fails. Three rows qualify.
Use IS NULL and IS NOT NULL to test missing values. Comparing a value to NULL with = does not produce an ordinary true match. SELECT DISTINCT removes duplicate result rows over the entire selected column combination.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT DISTINCT kind FROM asset ORDER BY kind;| kind |
|---|
| display |
| imaging |
| sensing |
Read the result. Three rows share two display values, so DISTINCT collapses them into one. Imaging and sensing appear once each. The answer lists each stored kind exactly once.
An alias gives an output expression a readable name. It does not necessarily become a stored column.
SQL evaluation and alias visibility rules differ between clauses; use a clear expression or an appropriate derived query when an alias cannot be used where you need it.
A query asks for labels with units = NULL. It returns no rows even though sensor P has a missing count. What went wrong?
Goal. Explain the empty answer.
Approach. Test what the condition produces for the NULL row.
Trace. Sensor P holds NULL, and NULL = NULL is unknown, not true. WHERE keeps only true rows, so the sensor row is dropped. Every other row fails the equality too.
Result. The condition can never be true; IS NULL is the correct test.
Result: Nothing is wrong with the data. The test itself is wrong; use units IS NULL.
Filter rows first, shape columns next, arrange last. One clause, one job.
9.7 Data Updation and Deletion
An UPDATE or DELETE condition chooses which existing records will change. Before executing it, use the same condition in a SELECT and inspect the matching identities. This turns an abstract condition into a visible target set.
Without the intended condition, a valid command can change many more rows than expected. Syntax checking cannot tell whether you meant all records or one specific record.
- Select the records using the intended condition.
- Confirm the identities and count match the task.
- Apply the change under the appropriate transaction and recovery plan, then inspect the result.
Corrections need a visible target before any value changes.
A modifying statement should make its intended target visible before it changes data. Preview the rows, confirm their identities and only then apply the change.
The preview turns an abstract condition into a checkable list.
Think of correcting one entry in the register. First point at the exact line with your finger. Read its id aloud. Then overwrite the count. Pointing first prevents correcting the neighbour.
A notice board shows the same habit. Read the old notice fully before replacing it. Confirm the date and title match the one you meant. Then pin the new notice over it.
Without WHERE, UPDATE affects every row the statement reaches. A missing condition is valid syntax with a destructive meaning. Treat every bare UPDATE as guilty until proven careful.
The change below raises device 42 from 8 to 10 units. The SELECT before it shows the intended target. The condition uses the primary key, which identifies exactly one row.
SELECT asset_id, label, units FROM asset WHERE asset_id = 42;
UPDATE asset SET units = units + 2 WHERE asset_id = 42;Read the two lines. The first line previews the target row.
The second line adds 2 to its units. The arithmetic uses the stored value 8, so 8 + 2 gives 10.
The WHERE clause repeats the same primary-key condition in both lines.
The verified result below shows the whole table after the update. Only device 42 changed. Every other row kept its baseline value.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT asset_id, units FROM asset ORDER BY asset_id;| asset_id | units |
|---|---|
| 31 | 14 |
| 42 | 10 |
| 53 | 6 |
| 64 | NULL |
Trace the condition asset_id = 42 across all rows. Device 31 fails. Device 42 passes and becomes 8 + 2 = 10. Device 53 fails. Device 64 fails. One row changes; three rows survive untouched.
Read the diagram. Preview with SELECT using the intended condition. Confirm the identities and the count. Apply the change. Inspect the result with the same ordering. Any surprise at step two stops step three.
Without WHERE, UPDATE affects every row the statement reaches. DELETE also affects all rows when no condition limits it. A primary-key condition is often clearer than a description that might match many records.
The deletion below removes one loan event. Its condition names the loan primary key, so exactly one row can match. The table structure and all other loans survive.
DELETE FROM loan WHERE loan_id = 73;Read the line. DELETE FROM loan names the target table. The WHERE clause keeps only loan 73. Loans 71 and 72 fail the condition and remain. The asset table is untouched.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT loan_id FROM loan ORDER BY loan_id;| loan_id |
|---|
| 71 |
| 72 |
Read the result. Two loans remain: 71 and 72. The count fell from 3 to 2. Loan 73 is gone because it matched; nothing else matched, so nothing else changed.
Deleting an asset can fail or trigger a declared action when loans reference it. Inspect the foreign-key policy.
For a group of related changes, a suitable transaction can commit them together or roll them back; transaction support and DDL commit behaviour depend on the DBMS.
A second correction shows the same care with NULL. The sensor count is unknown, so the office records 5 after a recount.
The preview names device 64; the update sets its units; the check confirms exactly one changed cell.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT asset_id, units FROM asset WHERE asset_id = 64;| asset_id | units |
|---|---|
| 64 | 5 |
Trace it. The condition matches only device 64. Its NULL becomes 5. No other row carries id 64, so no other row changes. Unknown became known through an explicit, targeted statement.
You intended to update one asset but the matching label appears twice. What should you do?
Preview the condition, identify the intended key, and make the update condition reflect that identity.
Result: Do not execute an ambiguous modification merely because its syntax is valid.
A clerk must remove loan 73 but keep loans 71 and 72. Write the safe sequence.
Goal. Delete exactly one named loan.
Approach. Preview with the primary key, then delete with the same condition.
Trace. SELECT with loan_id = 73 shows one row. DELETE with loan_id = 73 removes that row. A final SELECT shows 71 and 72 remain.
Result. Two loans remain; the target alone is gone.
Result: SELECT first, DELETE with loan_id = 73, then SELECT again to confirm.
Preview, confirm, apply, inspect. Every change earns its evidence.
9.8 Functions in SQL
A scalar function transforms one supplied value or set of arguments. An aggregate combines a collection of rows into a summary. UPPER can return a transformed label for each row; COUNT summarises how many qualifying values or rows exist.
Missing values make the aggregate question important. Counting rows is different from counting recorded values in an optional field. An average of known counts uses the known counts, not an invented zero for each unknown.
- Decide whether you want one result per row or a summary.
- Read the function’s argument and null-handling rules.
- Check a small example manually before trusting a larger report.
The office needs tidy labels and honest totals from the same register.
Functions derive values without requiring the original column to be rewritten. A scalar function transforms each input row. An aggregate function summarises many rows into one answer. Neither rewrites the stored column.
Think of name badges. Printing every name in capitals changes the badges, not the register.
Counting badges gives one number for the whole pile. Badges per person versus one total for all badges is the scalar-aggregate split.
A score sheet shows the same split. Rounding each score tidies the display row by row. Averaging the column answers one question about the whole class. Both derive; neither erases the original marks.
A scalar function returns a result for each input row or expression. Common MySQL numeric functions include ABS, ROUND, CEIL, FLOOR, MOD and POW.
String functions include UPPER, LOWER, LENGTH, CHAR_LENGTH, CONCAT, SUBSTRING, LEFT, RIGHT, TRIM and INSTR. Read each function’s argument and indexing rules.
The query below applies six scalar functions to fixed values. Each output column answers for its own inputs only. Trace each one separately.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT UPPER('screen'), LENGTH('screen'),
SUBSTR('screen', 2, 3), INSTR('screen', 're'),
ROUND(7.625, 2), ABS(-9);| upper | ASCII length | substring | position | rounded | absolute |
|---|---|---|---|---|---|
| SCREEN | 6 | cre | 3 | 7.63 | 9 |
Trace each column. UPPER returns SCREEN. LENGTH counts 6 letters. SUBSTR from position 2 takes 3 letters: cre. INSTR finds re at position 3. ROUND(7.625, 2) gives 7.63. ABS(-9) gives 9. Six independent answers, one row.
For ASCII text, byte length and character count agree. They need not agree for other characters: MySQL LENGTH counts bytes, while CHAR_LENGTH counts characters.
The substring position in this example is one-based, unlike Python list indexing.
The marks table below threads through the rest of this section and the next. Six students, two subjects, and one score not yet recorded. Read every row before any total is computed.
CREATE TABLE marks (
student_id INTEGER PRIMARY KEY,
student_name VARCHAR(30) NOT NULL,
subject VARCHAR(20) NOT NULL,
score INTEGER CHECK (score >= 0 AND score <= 100)
);
INSERT INTO marks (student_id, student_name, subject, score) VALUES
(1, 'student P', 'maths', 82),
(2, 'student Q', 'maths', 64),
(3, 'student R', 'maths', 91),
(4, 'student S', 'science', 73),
(5, 'student T', 'science', 58),
(6, 'student U', 'science', NULL);Read the six rows. Students P, Q and R take maths with 82, 64 and 91. Students S, T and U take science with 73, 58 and an unrecorded score. Student U is the NULL case for every aggregate rule.
Scalar functions tidy one name. The query uppercases student Q and measures the name length. The stored name stays exactly as inserted.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT UPPER(student_name), LENGTH(student_name) FROM marks WHERE student_id = 2;| upper | name length |
|---|---|
| STUDENT Q | 9 |
Trace it. Only student 2 satisfies the condition. UPPER gives STUDENT Q. LENGTH counts 9 characters: seven letters, one space, one letter. The stored value student Q is unchanged.
Read the diagram. One value enters a scalar function and one transformed value leaves. Many rows enter an aggregate and one summary leaves. Asking which picture fits prevents averaging labels or uppercasing a total.
MySQL date functions such as CURDATE, YEAR, MONTH, MONTHNAME and DAYNAME derive current or calendar information. A current-date result changes with time and configuration; a fixed-date exercise must state the date rather than pretending a live clock is a constant.
The asset totals below ignore the unknown sensor count. COUNT(*) counts all four rows. COUNT(units) counts the three known values. The average divides by three, not four.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT COUNT(*), COUNT(units), SUM(units),
ROUND(AVG(units), 6), MIN(units), MAX(units) FROM asset;| all rows | known counts | sum | mean (rounded) | minimum | maximum |
|---|---|---|---|---|---|
| 4 | 3 | 28 | 9.333333 | 6 | 14 |
Trace the denominator. The sum is 14 + 8 + 6 = 28. Known counts are three, so the mean is 28 divided by 3, which rounds to six places as shown. Dividing by four rows would wrongly treat the unknown as zero.
COUNT(*) counts rows. COUNT(column) counts non-null values in that column.
The shown aggregate functions ignore null inputs, so AVG(units) divides by the number of known counts. An all-null sum or average is not automatically zero.
The marks totals tell the same story with more rows. Six students, five known scores, sum 368, mean 368 divided by 5.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT COUNT(*), COUNT(score), SUM(score),
ROUND(AVG(score), 1), MIN(score), MAX(score) FROM marks;| all rows | known scores | sum | mean | minimum | maximum |
|---|---|---|---|---|---|
| 6 | 5 | 368 | 73.6 | 58 | 91 |
Trace the mean step by step. The sum is 82 + 64 + 91 + 73 + 58 = 368. Known scores are five, so divide: 368 / 5 = 73.6. Rounded to one place it stays 73.6. Student U contributes to the row count but not to the sum.
A report divides the marks sum by 6 students instead of 5 known scores. What is the error?
Goal. Name the wrong denominator and its effect.
Approach. Compare the row count with the known-value count.
Trace. The sum 368 is correct, but 6 includes the unrecorded score as if it were zero. 368 / 6 understates the true mean of 73.6. The average must divide by known scores only.
Result. Wrong denominator: 6 rows instead of 5 known scores.
Result: Divide 368 by 5 known scores, giving 73.6, not by 6 rows.
One result per row is scalar. One result for many rows is aggregate. Count what the question asks.
9.9 GROUP BY Clause in SQL
GROUP BY first places rows into groups sharing the chosen grouping values. An aggregate then answers its question separately inside each group. This is like sorting records into labelled piles before counting each pile.
WHERE decides which individual rows enter those piles. HAVING decides which completed group summaries remain. Moving a condition between them can change the question and the answer.
- Select the input rows allowed by WHERE.
- Form groups using the grouping key.
- Calculate each summary, then apply any HAVING condition to those summaries.
The office wants one summary line per kind of device, not one grand total.
Grouping asks the same summary question separately for each group of matching keys. Rows with the same kind form one pile. Each pile gets its own count and total.
Think of sorting slips into labelled trays. One tray per kind: display, imaging, sensing. Then count the slips in each tray and total each tray. Trays first, totals second.
A fruit stall shows the same habit. Apples go in one crate, oranges in another. Each crate is weighed separately. Nobody mixes the crates and then claims per-fruit totals.
GROUP BY makes the piles. Aggregates weigh each pile. HAVING keeps the heavy piles.
The query below groups assets by kind. Display holds two rows with 14 + 8 = 22. Imaging holds one row with 6. Sensing holds one row with an unknown count.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT kind, COUNT(*) AS assets, SUM(units) AS total_units
FROM asset
GROUP BY kind
ORDER BY kind;| kind | assets | total_units |
|---|---|---|
| display | 2 | 22 |
| imaging | 1 | 6 |
| sensing | 1 | NULL |
Trace the piles. Display collects devices 31 and 42: two rows, sum 22.
Imaging collects device 53: one row, sum 6. Sensing collects device 64: one row, sum NULL because its only input is unknown.
Three piles, three summaries.
GROUP BY partitions the selected input rows by grouping values. Aggregates summarise each partition.
Every selected nonaggregate expression must obey the DBMS’s grouping rules; writing an arbitrary non-grouped label can be invalid or misleading.
Read the diagram. WHERE admits input rows. GROUP BY forms the piles. Aggregates summarise each pile. HAVING keeps the piles whose summaries qualify. Moving a condition across this pipeline changes the question.
| Step | Filters | Example |
|---|---|---|
| WHERE | Single input rows. | units IS NOT NULL drops the sensor row. |
| GROUP BY | Nothing; it organises. | Rows collect into display, imaging, sensing. |
| Aggregate | Nothing; it summarises. | Each pile gets its count and sum. |
| HAVING | Whole group summaries. | SUM(units) > 10 keeps display only. |
Read the table. WHERE touches rows before piles exist. GROUP BY organises without removing. Aggregates compute without removing. HAVING removes whole piles by their summaries. Each step has one job.
WHERE filters individual input rows before grouping. HAVING filters groups after aggregation. Put a unit-count threshold in WHERE when it limits rows; put a group-total threshold in HAVING when it limits summaries.
The query below keeps only groups whose total exceeds 10. Display totals 22 and survives. Imaging totals 6 and goes. Sensing totals NULL, which is not greater than 10, and goes.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT kind, SUM(units) AS total_units
FROM asset
GROUP BY kind
HAVING SUM(units) > 10
ORDER BY kind;| kind | total_units |
|---|---|
| display | 22 |
Trace the filter. Three piles enter HAVING. Display with 22 passes. Imaging with 6 fails. Sensing with NULL fails because NULL > 10 is unknown. One row remains.
The marks table gives a two-pile version with real averages. Maths piles three known scores; science piles two known scores plus one unknown.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT subject, COUNT(*), COUNT(score), SUM(score),
ROUND(AVG(score), 1) FROM marks
GROUP BY subject ORDER BY subject;| subject | rows | known | sum | mean |
|---|---|---|---|---|
| maths | 3 | 3 | 237 | 79 |
| science | 3 | 2 | 131 | 65.5 |
Trace the maths pile. Scores 82, 64, 91 sum to 237.
Three known of three rows, so the mean is 237 / 3 = 79. Trace the science pile.
Scores 73 and 58 sum to 131. Two known of three rows, so the mean is 131 / 2 = 65.5.
Student U counts as a row but not as a score.
A null group total does not satisfy a numeric greater-than condition. If the application wants to replace missing summaries with a default, it should do so deliberately and label the policy rather than silently treating unknown counts as measured zero.
The office wants subjects whose mean score exceeds 70. Which subjects qualify?
Goal. Filter group summaries by their mean.
Approach. Group by subject, compute each mean, then apply HAVING.
Trace. Maths means 79, which exceeds 70. Science means 65.5, which does not. The subject means come from known scores only.
Result. Maths alone qualifies.
Result: Maths with 79. Science at 65.5 falls short.
Piles first, summaries second, pile filter last. WHERE and HAVING are not synonyms.
9.10 Operations on Relations
Union, intersection and difference ask which rows belong in a result according to their membership in the inputs. A Cartesian product does something else: it makes every possible cross-input pair.
Difference is directional. “In the first collection but not the second” is not the same request with the collection names reversed. Set operations also need compatible corresponding columns so that their rows can be meaningfully compared.
- State whether the task concerns membership or combinations.
- Check that the input columns are compatible for a set operation.
- Decide whether duplicates should be removed or retained.
Sometimes the office merges two answer lists; sometimes it pairs every slip with every device.
Relational operations combine compatible sets of tuples or make combinations across relations. Union, intersection and difference test membership. Cartesian product builds every possible pair.
Think of two attendance lists for two loan desks. Merging them answers who borrowed anywhere.
Intersecting answers who used both desks. Subtracting answers who used the first desk only.
Pairing every borrower with every device answers nothing until a condition links them.
A sports day shows the same split. Merging class lists gives all runners. Crossing runners with lanes gives every possible assignment. Membership questions and pairing questions need different tools.
| Operation | Meaning |
|---|---|
| Union | Rows in either input; ordinary UNION removes duplicates. |
| Intersection | Rows common to both inputs. |
| Difference | Rows in the first input but absent from the second. |
| Cartesian product | Every row of one input paired with every row of the other. |
Read the table. The first three rows test membership in different ways. The fourth row manufactures pairs. Union asks either. Intersection asks both. Difference asks first-but-not-second. Product asks every combination.
Set operations need compatible output columns in corresponding positions. UNION ALL retains duplicates.
Difference is directional: changing the input order changes its meaning. A Cartesian product has one combined row for every possible pair, before filtering.
The union below merges borrower accounts from two devices. Account A borrowed both devices, so it appears once after duplicate removal. Account B borrowed only device 31.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT account_tag FROM loan WHERE asset_id = 31
UNION
SELECT account_tag FROM loan WHERE asset_id = 53
ORDER BY account_tag;| account_tag |
|---|
| account A |
| account B |
Trace the inputs. Device 31 loans name accounts A and B. Device 53 loans name account A. Merging gives A, B, A; duplicate removal leaves A and B. Ordering arranges them alphabetically.
The intersection below keeps only accounts naming both devices. Only account A borrowed from each, so only it survives.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT account_tag FROM loan WHERE asset_id = 31
INTERSECT
SELECT account_tag FROM loan WHERE asset_id = 53
ORDER BY account_tag;| account_tag |
|---|
| account A |
Trace it. Candidates from device 31 are A and B. Account A also appears for device 53, so it is kept. Account B never appears for device 53, so it is dropped. One row remains.
The difference below reverses the question: accounts of device 31 that never borrowed device 53. Only account B qualifies. Swapping the two inputs would ask the opposite question and return an empty table here.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT account_tag FROM loan WHERE asset_id = 31
EXCEPT
SELECT account_tag FROM loan WHERE asset_id = 53
ORDER BY account_tag;| account_tag |
|---|
| account B |
Trace the direction. From A and B, remove any account found for device 53. Account A is removed. Account B stays. Direction matters: first-but-not-second differs from second-but-not-first.
Read the diagram. List each input set. Test membership row by row. Keep or drop each row. When the task needs pairs instead, stop and write a join condition; set tools cannot invent relationships.
Current MySQL releases support INTERSECT and EXCEPT, while older classroom installations may not. Confirm the deployed version. A NOT EXISTS query can express an exclusion without relying on those newer operators.
The query below lists devices nobody borrowed. Screen Q and sensor P have no matching loan. Screen P and camera P each have at least one.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT a.label FROM asset AS a
WHERE NOT EXISTS (SELECT 1 FROM loan AS l
WHERE l.asset_id = a.asset_id)
ORDER BY a.asset_id;| label |
|---|
| screen Q |
| sensor P |
Trace each asset. Screen P matches loans 71 and 72, so EXISTS is true and NOT EXISTS drops it.
Camera P matches loan 73, so it is dropped. Screen Q matches nothing, so it is kept.
Sensor P matches nothing, so it is kept. Two rows qualify.
How large is the Cartesian product of the baseline asset and loan tables?
Every asset can pair with every loan before a join condition removes unrelated pairs.
Result: 12 rows.
Trace the count. Four asset rows times three loan rows gives 12 pairs. Most pairs are meaningless, such as sensor P with loan 71. A join condition would keep only pairs where the ids agree.
Membership asks who belongs. Pairing makes combinations. Use the tool that matches the question.
9.11 Using Two Relations in a Query
A join pairs rows that satisfy a condition. In the equipment example, a loan’s asset reference is compared with an asset’s identity. Each matching pair produces a combined result row.
If an asset has several loans, it can appear in several result rows. That can be correct: the query is showing loan events, not promising one row per asset. Decide what one result row should represent before trying to remove duplicates.
- Read the relationship named in ON.
- Find every pair satisfying that relationship.
- Check whether unmatched left records should be retained and how aggregates should count them.
Borrowing slips become useful only when each slip is matched to its device.
A join reconstructs a useful view by combining rows according to an explicit relationship. Each loan names an asset id. Each asset owns its id. Matching pairs produce combined rows that show the event with its thing.
Think of stapling each borrowing slip to its device card. The staple is the shared id. Slip 71 staples to screen P. Slip 73 staples to camera P. A slip that names no card stays unstapled.
A bus pass shows the same link. The pass names a student id. The student record owns that id. Joining pass to student prints the journey with the name attached. The id does the stapling.
A join pairs rows whose stated relationship holds. The ON condition names that relationship. Every result row is one qualifying pair.
The inner join below staples each loan to its asset. Three loans each name a real asset, so three combined rows appear. Screen P appears twice because it backs two separate loans.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT l.loan_id, a.label, l.account_tag
FROM loan AS l
JOIN asset AS a ON a.asset_id = l.asset_id
ORDER BY l.loan_id;| loan_id | label | account |
|---|---|---|
| 71 | screen P | account A |
| 72 | screen P | account B |
| 73 | camera P | account A |
Trace the pairs. Loan 71 names 31, which is screen P: kept. Loan 72 names 31, which is screen P: kept. Loan 73 names 53, which is camera P: kept. No loan names 42 or 64, so those assets contribute no inner-join row.
| Loan | Names asset | Stapled label | Kept |
|---|---|---|---|
| 71 | 31 | screen P | Yes. |
| 72 | 31 | screen P | Yes. |
| 73 | 53 | camera P | Yes. |
Read the table. Each loan finds its device through the shared id. All three loans match, so all three appear. The table explains why screen P repeats: repetition records two events, not a data error.
Aliases shorten qualified column references. Qualifying both asset_id expressions makes their origin explicit.
The join emits one row for every matching pair, so one asset with several loans appears several times. That is not necessarily an accidental duplicate.
Read the diagram. Read the ON condition first. Test every candidate pair against it. Keep the matching pairs. For a left join, also keep unmatched left rows with nulls for the missing side.
An inner join returns matching pairs. A left join also retains each unmatched left row with nulls for the missing right-side fields.
A natural join chooses same-named columns automatically; an added shared column can therefore change its meaning. Explicit ON conditions are usually easier to audit.
The left join below keeps every asset, borrowed or not. Screen Q and sensor P have no loans, so their loan columns arrive as NULL. The grouping then counts real loans per asset.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT a.asset_id, COUNT(l.loan_id) AS loans
FROM asset AS a
LEFT JOIN loan AS l ON l.asset_id = a.asset_id
GROUP BY a.asset_id
ORDER BY a.asset_id;| asset_id | loans |
|---|---|
| 31 | 2 |
| 42 | 0 |
| 53 | 1 |
| 64 | 0 |
Trace the groups. Asset 31 pairs with loans 71 and 72: two matches.
Asset 42 pairs with nothing: zero matches. Asset 53 pairs with loan 73: one match.
Asset 64 pairs with nothing: zero matches. The counts are 2, 0, 1 and 0.
COUNT(l.loan_id) counts actual right-side matches because the loan key is non-null for a real loan. COUNT(*) would count the retained left row too.
A careless WHERE condition on a right-side column can remove unmatched rows and undo the intended outer-join effect.
The comparison below measures that difference directly. Five joined rows exist, but only three carry a real loan id.
Predict the result table before reading it. The table after the code shows the verified answer.
SELECT COUNT(*) AS joined_rows, COUNT(l.loan_id) AS real_loans
FROM asset AS a LEFT JOIN loan AS l ON l.asset_id = a.asset_id;| joined_rows | real_loans |
|---|---|
| 5 | 3 |
Trace the five rows. Screen P contributes two.
Screen Q contributes one null-extended row. Camera P contributes one.
Sensor P contributes one null-extended row. COUNT(*) sees five; COUNT(loan_id) skips the two nulls and reports three.
Screen Q shows zero loans in the left-join count. Is that an error?
Goal. Decide whether zero is correct.
Approach. Check whether any loan names asset 42.
Trace. Loans name 31, 31 and 53. None names 42. The left join retains screen Q with NULLs, and COUNT(loan_id) counts zero real matches. Zero reports idleness, not absence.
Result. Correct: zero loans, honestly reported.
Result: Zero is correct. No loan references asset 42, and the count shows it.
One result row per pair, not per asset. Multiplicity describes the real borrowing history.
Summary
Use these points to test what you can explain without looking back.
- Define appropriate types, identities and relationship constraints before loading records.
- Use explicit insertion columns and distinguish NULL from text and zero.
- SELECT, FROM, WHERE, GROUP BY, HAVING and ORDER BY perform different jobs.
- Read execution order FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY when tracing.
- Preview the target rows before UPDATE or DELETE.
- Scalar functions derive values per row; aggregates summarise rows or groups.
- COUNT(*) and COUNT(column) differ for nulls; averages divide by known values.
- UNION, INTERSECT and EXCEPT test membership; difference is directional.
- Cartesian product pairs everything; joins keep only related pairs.
- Joins combine matching pairs; outer joins retain selected unmatched rows.
- Check MySQL-specific syntax and behaviour on the actual server version.
Exercises
Work independently. For a program, predict the result before running it. Explain your reasoning as well as giving an answer.
9.1 Write a query listing labels with known unit counts in descending count order.
9.2 Find the sum of known unit counts in the baseline.
9.3 A query tests units = NULL and returns nothing. Find the error and repair it.
9.4 Write a query counting assets separately by kind, with kinds in order.
9.5 How many loans refer to screen P in the baseline?
9.6 Write a query finding kinds with more than one asset.
9.7 Explain why the primary-key condition matters in an update intended for asset 42.
9.8 What does a nonnegative CHECK fail to guarantee without NOT NULL?
9.9 Which rows disappear in an inner join that a left join can retain?
9.10 What is the risk in SELECT * from a Cartesian product of asset and loan?
9.11 Why can a natural join become fragile after a schema change?
9.12 State the difference between deleting rows and dropping a table.
9.13 Explain why query verification with SQLite does not prove MySQL-specific type behaviour.
9.14 Predict the result table of SELECT label, units FROM asset ORDER BY units ASC, asset_id;
SELECT label, units FROM asset ORDER BY units ASC, asset_id;9.15 A practice script runs DELETE FROM loan; with no WHERE. State the damage and the safe repair.
DELETE FROM loan;9.16 Write a query giving each subject mean score for means above 70, and predict the answer.
SELECT subject, ROUND(AVG(score), 1) AS mean_score
FROM marks
GROUP BY subject
HAVING AVG(score) > 70
ORDER BY subject;9.17 Trace this query clause by clause and predict its single result row.
SELECT kind, SUM(units) AS t FROM asset
WHERE units IS NOT NULL
GROUP BY kind
HAVING SUM(units) >= 8
ORDER BY kind;Answers
9.1 SELECT label, units FROM asset WHERE units IS NOT NULL ORDER BY units DESC, asset_id;
9.2 28; the unknown count is not silently treated as a measured zero.
9.3 A comparison with NULL produces unknown, never true. Use WHERE units IS NULL.
9.4 SELECT kind, COUNT(*) FROM asset GROUP BY kind ORDER BY kind;
9.5 2.
9.6 SELECT kind, COUNT() AS n FROM asset GROUP BY kind HAVING COUNT() > 1 ORDER BY kind; only display, with 2 assets, qualifies.
9.7 It identifies the exact row independently of labels and current display order; a missing WHERE would change every row.
9.8 That a known count was supplied; NULL comparisons stay unknown and pass the check.
9.9 Unmatched rows from the chosen left table, here screen Q and sensor P.
9.10 It combines unrelated pairs and can produce many rows unless an appropriate condition supplies the intended relationship.
9.11 A new shared column name can become an unintended additional join condition.
9.12 DELETE retains the table structure; DROP TABLE removes the table and its data.
9.13 Their type systems, conversions, configuration and dialect features differ; the actual MySQL deployment needs its own checks.
9.14 In SQLite the order is sensor P NULL, camera P 6, screen Q 8, screen P 14, because SQLite sorts NULL before all values in ascending order. Do not depend on null placement elsewhere: other servers may put NULL last, so state the wanted placement explicitly when it matters.
9.15 All three loans vanish while the table structure survives. Repair: restore the loans from backup, then rerun with WHERE loan_id = 73 after previewing with SELECT.
9.16 Maths alone, with mean 79. Science at 65.5 fails the HAVING test. Both means divide by known scores only.
9.17 WHERE drops sensor P. Piles: display sums 22, imaging sums 6. HAVING keeps display only. Result: display, 22.