Databases & SQL Master Course — 113. MySQL SQL Modes
Lesson 113 MySQL SQL Modes
Verification scope and lab safety
MySQL 8.4 only. These scripts were checked against official documentation but were not executed on that engine in the authoring environment. Every result below is a reasoned expectation, not observed output. Use a dedicated disposable local lab with the required privileges, never an existing application database. No server installation, credential changes, or external database operation is part of this lesson.
Prerequisites and objectives
Complete the MySQL types lesson. You will record and restore session SQL mode, compare a strict assignment with a warning-producing nonstrict assignment, explain ONLY_FULL_GROUP_BY, and repair an ambiguous grouped query without weakening the session’s validation policy.
SQL mode is part of the test environment
MySQL SQL modes affect syntax and validation behavior. Two connections to the same server can have different session modes and therefore treat the same statement differently. A reproducible test records the session value rather than assuming an installation default. Changing a global value would affect other work and is outside this disposable exercise.
This lesson temporarily uses a small explicit mode list to isolate two behaviors. STRICT_TRANS_TABLES controls important invalid assignments to transactional tables. ONLY_FULL_GROUP_BY checks whether selected values have a well-defined relationship to grouped results. NO_ENGINE_SUBSTITUTION avoids silently substituting another engine when InnoDB is requested. This short list is a teaching control, not a complete production policy.
Create boundary values and an ambiguous group
Save the starting session mode before changing it. Session settings are not restored by ROLLBACK, so cleanup must restore the saved value explicitly. The unsigned tiny integer permits values from zero through 255. The sales table deliberately gives North two different representatives, making a single unaggregated representative per region ambiguous.
SET @saved_mode113 = @@SESSION.sql_mode;
SET SESSION sql_mode = 'STRICT_TRANS_TABLES,ONLY_FULL_GROUP_BY,NO_ENGINE_SUBSTITUTION';
CREATE TEMPORARY TABLE lab_qty113 (
id INT PRIMARY KEY, qty TINYINT UNSIGNED NOT NULL
) ENGINE=InnoDB;
CREATE TEMPORARY TABLE lab_sales113 (
id INT PRIMARY KEY, region VARCHAR(20) NOT NULL,
representative VARCHAR(20) NOT NULL, amount INT NOT NULL
) ENGINE=InnoDB;
START TRANSACTION;
INSERT INTO lab_qty113 VALUES (1,10);
INSERT INTO lab_sales113 VALUES
(1,'North','Ana',100),(2,'North','Bo',200),(3,'South','Cy',50);
SELECT @@SESSION.sql_mode;
Errors, warnings, and stored adjustments
Under the strict mode, inserting 256 into the unsigned tiny integer is expected to fail because it exceeds 255. Under the controlled nonstrict mode, the same assignment is expected to store the nearest valid upper boundary and issue a warning. A completed statement can therefore still represent a lossy adjustment.
Inspect SHOW WARNINGS immediately after the statement whose diagnostics you need. Later statements can replace the relevant diagnostic context. Do not turn an error into a warning merely to make an import finish; determine whether the adjusted value still means what the source intended. For this quantity, silently changing 256 to 255 loses an item.
| Mode condition | Input quantity | Expected outcome |
|---|---|---|
| Strict transactional mode | 256 | Statement error; no new row |
| Controlled nonstrict mode | 256 | Store 255 and report warning |
Grouping needs a defined value per group
A grouped query returning region, representative, and SUM(amount) must explain which representative belongs to the North total. The data contains Ana and Bo, with no dependency making region determine a single representative. ONLY_FULL_GROUP_BY is expected to reject that query. An ORDER BY does not repair the ambiguity by choosing a representative before aggregation.
MySQL can recognize certain functional dependencies, such as a selected value determined by a grouped unique non-NULL key. The mode is therefore more precise than a blanket slogan that every selected nonaggregate expression must literally appear in GROUP BY. This fixture intentionally lacks such a dependency for region and representative.
Worked practice
Exercise 1
Test the out-of-range quantity under strict mode.
Worked solution
SAVEPOINT trial;
INSERT INTO lab_qty113 VALUES (2,256);
-- Expected error: inspect it before running the recovery lines.
ROLLBACK TO SAVEPOINT trial;
RELEASE SAVEPOINT trial;
SELECT COUNT(*) FROM lab_qty113;
The invalid row should not be retained. Keep the primary key new so the test isolates the quantity boundary rather than a duplicate-key failure. Run the expected error separately if your client stops a script on errors. The final count verifies the fixture remains intact.
Exercise 2
Observe the controlled nonstrict adjustment, then undo it and restore the strict test mode.
Worked solution
SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY,NO_ENGINE_SUBSTITUTION';
SAVEPOINT trial;
INSERT INTO lab_qty113 VALUES (2,256);
SHOW WARNINGS;
SELECT qty FROM lab_qty113 WHERE id = 2;
ROLLBACK TO SAVEPOINT trial;
RELEASE SAVEPOINT trial;
SET SESSION sql_mode = 'STRICT_TRANS_TABLES,ONLY_FULL_GROUP_BY,NO_ENGINE_SUBSTITUTION';
The savepoint removes the adjusted row, but it does not restore the mode change. The final SET performs that separate responsibility. This controlled experiment is useful evidence about a conversion policy; it is not a recommendation to run application imports nonstrictly.
Exercise 3
Demonstrate the grouped query that lacks a single representative value for North.
Worked solution
SAVEPOINT trial;
SELECT region, representative, SUM(amount)
FROM lab_sales113 GROUP BY region;
-- Expected error: inspect it before running the recovery lines.
ROLLBACK TO SAVEPOINT trial;
RELEASE SAVEPOINT trial;
The expected rejection exposes an incomplete reporting requirement. Removing the mode would permit an arbitrary representative choice rather than establish a meaningful association. Adding ORDER BY representative would sort the resulting groups, not guarantee which representative contributes the selected value.
Exercise 4
Return region totals without an unjustified representative, then clean up.
Worked solution
SELECT region, SUM(amount) AS total_amount
FROM lab_sales113 GROUP BY region ORDER BY region;
ROLLBACK;
DROP TEMPORARY TABLE lab_sales113;
DROP TEMPORARY TABLE lab_qty113;
SET SESSION sql_mode = @saved_mode113;
The repaired query asks only for the grouped region and its aggregate. If the actual report needs representative totals, group by both region and representative instead, accepting that the result has a different grain. Cleanup handles row state, temporary definitions, and session settings separately.
Pitfalls and summary
Strict mode is not an assertion that every SELECT conversion raises an error, nor does it make INSERT IGNORE behave like an ordinary INSERT. Statement context and modifiers matter. Read the documented rule for the operation you are testing instead of extrapolating from one insert result to all expressions.
Do not compare the exact comma ordering of a displayed mode list when the requirement is membership. Do not overwrite a shared global mode to reproduce a local experiment. When a connection returns to a pool, its settings must match the application’s expectations rather than inherit a tutorial’s temporary choices.
Record SQL mode as part of the environment, treat warnings as evidence of possible data changes, and repair ambiguous queries at their intended reporting grain. Validation settings are most useful when their failures reveal a missing requirement instead of becoming obstacles to disable.
Knowledge check
Question 1
What is expected for qty 256 in the strict unsigned TINYINT trial?
- A statement error with no new row
- Storage as 255 without any diagnostic
- Storage as 256 because display width is unlimited
- Storage as SQL NULL despite the NOT NULL declaration
Answer and explanation
A. The value exceeds the unsigned tiny integer range and the strict transactional assignment should fail.
Question 2
Why run SHOW WARNINGS immediately after the nonstrict insert?
- Warnings are part of the table and must be selected before commit
- SHOW WARNINGS reverses any adjusted stored value
- Warnings are visible only after the transaction is committed
- Later statements can replace the relevant diagnostic context
Answer and explanation
D. Diagnostics should remain associated with the statement that produced them.
Question 3
Why does the representative query fail under ONLY_FULL_GROUP_BY?
- SUM cannot be combined with character columns in any query
- Region does not determine a unique representative in the fixture
- Every selected column must always be written literally in GROUP BY even with a recognized dependency
- The ORDER BY clause is missing a descending direction
Answer and explanation
B. North contains two representatives without a dependency selecting one for the group.
Question 4
Would ORDER BY representative make the ambiguous grouped value deterministic?
- Yes; it selects the alphabetically first representative before aggregation
- Yes; it adds representative to GROUP BY implicitly
- No; sorting the grouped output does not choose the group’s representative
- Yes; it converts representative into an aggregate
Answer and explanation
C. Ordering the output does not resolve which nonaggregated value belongs to a group.
Question 5
What restores the saved SQL mode after the lab?
- ROLLBACK TO SAVEPOINT by itself
- An explicit SET SESSION sql_mode using the saved value
- Dropping the temporary tables
- Releasing the final savepoint
Answer and explanation
B. Session configuration must be restored explicitly; transaction rollback does not restore it.
Dialect verification notes
The target is MySQL 8.4. Engine execution remains pending. SQLite was not used as a substitute for executing these dialect-specific scripts. Record actual server version, session settings, results, and errors when running the local lab. Python is not a learner prerequisite.
Primary references
- SQL modes: Strictness, session scope, and mode-dependent behavior.
- GROUP BY handling: Functional dependency and ambiguous grouped values.
- Numeric ranges: Unsigned TINYINT representation.
- SHOW WARNINGS: Statement diagnostics.
- Savepoints: Controlled rollback of trial row changes.