liveBook · Manning

Sorting algorithm

As explained in Learn SQL in a Month of Lunches

Result ordering is the specification of the sequence in which rows are returned by a query.

Sorting specifies the sequence in which query results appear. Like books arranged by author or events arranged by date, ordered data is easier to read and use. section 4.1 section 3.2.1

SQL does not guarantee a predictable row order unless the query explicitly requests one. Apparent insertion order may change as data or server settings change, because the database chooses an efficient retrieval strategy. section 3.2.1 section 4.0

Explicit sorting is useful when you need to:

  • Present rows in a readable sequence, such as alphabetical title order. section 4.1
  • Find the most recent entries or the smallest or largest values without reviewing every row. section 4.0
  • Make repeated query output predictable instead of relying on an accidental order. section 3.2.1

Alphabetizing titles

A practical task is to return every TitleName from the title table in alphabetical order while ignoring the article “The.” This produces a more useful catalog-style listing than leaving the database’s row order unspecified. section 15.4 section 4.0

Figure 3.3 The values of the TitleName column in the title table are returned in no particular order.

Use the figure to see how a simple column query can return values in no particular order before explicit sorting is applied. section 3.2.1

How Learn SQL in a Month of Lunches covers it

How deep it goes
Explains why implicit order is unreliable and motivates explicit sorting, but does not show sorting syntax or execution internals.
Examples
Uses library authors, building floors, calendars, title listings, recent entries, and alphabetizing titles while ignoring articles.
What it assumes
Assumes basic SQL querying and column selection, while reinforcing that returned rows have no guaranteed order by default.
What you can do after
Practice/perform it by writing queries whose results follow a required alphabetical, date-based, or value-based sequence.
How it connects
Connects sorting with SQL queries, result sets, relational database management systems, and limiting returned rows.

Also explained in

Compare how 18 books explain sorting algorithm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn SQL in a Month of Lunches. The section links point to the parts of the book it draws on.