MySQL ORDER BY and LIMIT
Use a complete order before LIMIT so tied values do not move unpredictably between pages.
How it works
ORDER BY defines result order and LIMIT bounds how many rows are returned. A limit without an order is not a reliable “first records” rule. If the chosen sort column can tie, add a unique tie-breaker. Here the stock desk wants the two cheapest kinds of parts. The ID makes the order complete even if another part later receives the same cost. Sorting and filtering remain separate decisions.
Run in a disposable MySQL lab
Use Oracle MySQL 8.4 with InnoDB, not Bhylu’s SQLite playground. The examples were reviewed on MySQL 8.4.8. XAMPP may provide MariaDB, which has different feature and collation behaviour. Check your actual server before running the script. These lessons do not require a change to Bhylu’s PHP, Apache or normal database service.
- On a separate lab instance, create the empty bhylu_mysql_lab schema. Stop if it already exists; do not overwrite an existing database.
- Select that schema and import the complete repair-parts seed once. It sets the documented session mode, utf8mb4 collation, UTC and English date-name locale.
- Run this lesson in a fresh copy of the seed, not after another lesson’s writes. Use the command-line client or a compatible editor. DELIMITER lines are client instructions for stored-program examples.
Download this complete lesson script. Its setup is the linked seed; review the dataset before changing it. Administrative and destructive examples are restricted to the specifically named disposable objects. Every script repeats the session settings because each new connection has its own session. No MySQL browser runner is currently available.
Example
SET NAMES utf8mb4 COLLATE utf8mb4_0900_ai_ci;
SET SESSION sql_mode = 'STRICT_TRANS_TABLES,ONLY_FULL_GROUP_BY,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
SET SESSION time_zone = '+00:00';
SET SESSION lc_time_names = 'en_US';
SELECT id, name, unit_cost
FROM parts
ORDER BY unit_cost ASC, id ASC
LIMIT 2;
Expected result
3 | Cotton cord | 1.2 1 | Canvas patch | 2.5
The zero-stock cord remains because this query asks about cost, not availability. Add a quantity predicate if the real requirement excludes it. LIMIT with an offset can be useful for small reports, but large offsets require skipping earlier rows and can shift under concurrent writes. A later keyset lesson uses the complete sort key to resume after a known row.
Use the official MySQL 8.4 reference for statement contracts and version details.