SQLite ORDER BY Ties and NULLs: Keep a Drone Review Queue Reproducible
Sort an invented drone review queue with explicit missing-value placement and a unique tie-breaker, while keeping query order separate from project priority.

A repeated sort can still leave ties unresolved
A drone delivery review may use a small queue of records that need checking. Two records can share the same priority, while another has no assigned priority at all. A query that orders only by priority does not fully describe where each record belongs. The visible order might look consistent during one review and still lack a rule for those equal values. This tutorial builds an invented queue in memory and makes both decisions explicit: where missing priorities appear and how equal priorities are separated. It does not inspect an actual NiVO project or assign operational importance to a customer record.
Start by writing the intended display rule in ordinary language. In this example, smaller numeric priorities appear first, unassigned priorities appear last, and a unique row identifier breaks every remaining tie. That is a local reporting convention, not a universal meaning of the word priority. Another delivery agreement may choose the opposite direction or put unassigned work first. The important step is to agree on that meaning before relying on a screenshot, exporting the first few records or comparing two reports. Sorting should expose an established decision rather than quietly create a new project policy.
Read the ordering contract and its limits
SQLite documents that results without ORDER BY have undefined order. With multiple ordering expressions, later expressions break ties from earlier expressions; if all expressions remain equal, relative order is still undefined. Ascending is the default. NULL sorts before other values in ascending order unless a different placement is requested. The NULLS LAST form makes missing priorities appear after supplied priorities here. A final unique row_id then supplies an unambiguous order within each priority group, including the missing group. This guarantee is about the selected, unchanged set of rows.
Do not confuse a row identifier with a timestamp, an aircraft serial number or an acceptance rank. The identifiers below are deliberately chosen integers that only distinguish records in this small example. They are not evidence that one observation occurred before another. If a real system uses a different stable key, inspect its uniqueness and meaning before choosing it for reporting. Also state the units and direction of the primary sort field. An unambiguous technical ordering can still be the wrong business ordering when the field has been misunderstood or a missing value has been given an invented interpretation.

Product context only; this photograph does not depict the constructed examples in this article.
Compare default and explicit missing-value placement
Run the following Python standard library example. It creates a temporary in-memory table, accepts only a small list of unique integer identifiers and integer-or-None priorities, and closes the connection after returning its results. No delivery database is opened or changed. The size bound is a teaching limit rather than an SQLite capacity claim. Both queries contain the same unique final key, so their difference isolates the missing-value placement. The page queries use the explicit rule and operate on the same unchanged table. Their parameters set the requested slice; they do not assign meaning to its records.
import sqlite3
def review_order(rows):
if not isinstance(rows, (list, tuple)) or len(rows) > 64:
raise ValueError("expected at most 64 teaching records")
checked = []
seen = set()
for row in rows:
if not isinstance(row, (list, tuple)) or len(row) != 2:
raise ValueError("expected id and priority")
ident, priority = row
if type(ident) is not int or not 0 <= ident <= 1000000:
raise ValueError("unsupported row id")
if priority is not None and (type(priority) is not int
or not -100 <= priority <= 100):
raise ValueError("unsupported priority")
if ident in seen:
raise ValueError("row ids must be unique")
seen.add(ident)
checked.append((ident, priority))
con = sqlite3.connect(":memory:")
try:
con.execute("CREATE TABLE queue(row_id INTEGER PRIMARY KEY, priority INTEGER)")
con.executemany("INSERT INTO queue VALUES (?, ?)", checked)
prefix = "SELECT row_id, priority FROM queue "
default = con.execute(prefix + "ORDER BY priority ASC, row_id ASC").fetchall()
ordered = prefix + "ORDER BY priority ASC NULLS LAST, row_id ASC"
complete = con.execute(ordered).fetchall()
pages = [con.execute(ordered + " LIMIT ? OFFSET ?", (3, offset)).fetchall()
for offset in (0, 3)]
return {"default_nulls": default, "missing_last": complete, "pages": pages}
finally:
con.close()
records = [(40, 2), (10, None), (30, 1), (20, 1), (50, None)]
print(review_order(records))Explain the resulting sequence by field
The default query returns identifiers 10, 50, 20, 30 and 40. Its two NULL priorities come first, and row_id orders that pair as well as the pair with priority one. The explicit missing-last query returns 20, 30, 40, 10 and 50. Its first three records have supplied priorities; the unassigned pair follows in identifier order. Neither result deletes a row or fills a missing priority. The difference is a presentation rule that should be visible in the report definition. Keep that distinction clear when someone asks why a record moved between two exported views.
The first page under the explicit rule contains 20, 30 and 40. The second contains 10 and 50. Concatenating them reproduces the full ordered result for this fixed five-record population. If row_id were removed from the query, the equal-priority pairs would no longer have a complete ordering contract, even if a particular run happened to print the same sequence. A demonstration should not promise to produce visibly shuffled ties on demand. The documented lack of an ordering guarantee is the reason to add a tie-breaker; an accidental change on one machine is not required to justify it.
Keep page stability separate from changing data
A unique tie-breaker does not freeze a changing database. If another process inserts a higher-priority row between two page requests, an offset-based page can move. This exercise avoids that question by keeping the population unchanged inside one short function. An actual review application needs a separate agreement about the file revision or database snapshot being compared. Record that identity with the query and its parameters. Do not treat stable sorting as evidence that two reports were generated from the same data. Establish the data boundary before investigating a difference in page membership.
The local profile also avoids mixed storage types, locale-sensitive text ordering and duplicated identifiers. Those are separate decisions that can change a real sort. Rejecting them here keeps the example focused rather than silently normalizing their values. If the real priority field is text, inspect its collation and intended ordering instead of copying this integer example unchanged. If identifiers are duplicated, resolve what each row represents before using the identifier alone as a final key. A reproducible report should preserve those uncertainties rather than hide them behind an apparently tidy list.
Carry the query rule into the review record
For a real handoff, save the exact query, the file or snapshot revision, the missing-value rule and the meaning of every ordering field. Include a tiny invented fixture like this one in technical documentation when it helps explain the expected sequence. Keep sensitive record content in its established project location. If the queue owner changes the display rule, compare the old and new results on the same input before interpreting the change as new work, resolved work or altered urgency. Sorting is a reporting operation; it does not itself establish completion, validity or flight readiness.
The owner-supplied NiVO photograph on this page provides aircraft context only. It does not show the constructed queue or identify software used by a particular project. The useful result is a clear contract for one report: explicit missing-value placement followed by a unique key after the main sort field. Once that contract is visible, another reviewer can reproduce the order and describe any difference precisely. Keep project priority decisions, record accuracy checks and acceptance criteria in their proper review process while the query handles the narrower task of returning a defined sequence.



