sqlcmd.net validated sql reference
beginner ordering MySQL MariaDB SQL Server PostgreSQL SQLite

Sort By Multiple Columns

Use more than one sort key so ties are broken deterministically.

Docker-validated Not currently validation-green

Sort by priority, then by name

Rows with the same priority are then sorted alphabetically by name.

Rows loaded before the example query runs.
Setup
CREATE TABLE tasks (name VARCHAR(50), priority INT);

INSERT INTO
  tasks (name, priority)
VALUES
  ('Deploy', 1),
  ('Backups', 2),
  ('Alerts', 1);
Shared across supported engines.
SQL
SELECT
  name,
  priority
FROM
  tasks
ORDER BY
  priority ASC,
  name ASC;
Returned rows for the shared example.
namepriority
Alerts1
Deploy1
Backups2

The secondary sort key makes the result deterministic across engines.

Where this command helps.

  • sorting by date and then by id for stable results
  • adding a tie-breaker when many rows share the same primary sort value

What the command is doing.

Multiple ORDER BY expressions are common in production queries. The first expression sets the primary sort, and later expressions break ties so the output remains stable and predictable.