SQLite RANK and DENSE_RANK: Keep Shared Review Scores Separate from Queue Positions
Compare RANK, DENSE_RANK and ROW_NUMBER on an invented drone review queue, preserving tied score groups while assigning reproducible row positions.

Decide whether the number describes a group or a row
A drone handoff team may arrange review records by an assigned score while still needing a reproducible place for every row in an export. Those are two different questions. If two records share the same score, a shared rank can describe that relationship without deciding which record appears first. A queue position does decide which row comes first. This tutorial compares those meanings using a small invented register. The scores are teaching inputs, not a NiVO inspection method, a customer priority list or evidence that any delivered dataset has passed a quality assessment.
Start by writing down what the number will be used for. A reviewer asking how many score groups precede a record needs a different answer from someone assigning the first four rows to a person. A spreadsheet column called rank can conceal that distinction. Preserve the original identifier and score in the result so another reader can see both the group relationship and the selected row order. Neither calculated label validates the score, and neither should silently become a measure of flight importance, asset condition or delivery readiness.
Keep the peer definition separate from the queue tie-breaker
SQLite defines peers using all the ordering expressions in a window. RANK gives tied peers the same rank and leaves gaps after a tie; DENSE_RANK numbers peer groups without gaps. ROW_NUMBER assigns consecutive row numbers. The window ordering determines those calculations, while the outer query ordering determines how the result is returned. In the example, the two rank calculations use only descending score. The row numbering additionally uses an ascending unique identifier. The final result uses that same complete row ordering so the queue positions and displayed rows can be compared directly.
Adding the unique identifier to the DENSE_RANK window would change the question. The records with score ninety would no longer be peers because their identifiers differ. That is valid SQL, but it would label distinct score-and-identifier combinations instead of distinct scores. A tie-breaker is useful for row positions precisely because it separates the rows. It is unsuitable inside a score-group definition when the intention is to preserve equal scores as one group. Keep the two window definitions visible rather than assuming that every ordering clause should be made identical.

Product context only; this photograph does not depict the constructed examples in this article.
Run a bounded comparison without opening a project database
The following Python standard library function creates only an in-memory teaching table. Each supplied record has an integer identifier and an integer score. Identifiers must be unique, and this local profile accepts scores from zero through one hundred. The bounds keep the example easy to inspect; they are not a NiVO scoring specification or a database capacity statement. Missing scores, text values and duplicate identifiers are rejected rather than being assigned an invented priority. A real register needs its own documented selection, identity and missing-value policies before adopting a ranking query.
The function returns five columns in order: identifier, score, competition rank, dense rank and queue position. Parameters are bound when the invented rows are inserted. The SQL expressions remain fixed. The connection closes after the comparison, and no existing database file is opened or changed. If your environment cannot execute window functions, record that limitation and check the installed SQLite version; do not replace the returned ranks with manually filled numbers and describe that as a successful run of the same query.
import sqlite3
def rank_review_rows(rows):
if not isinstance(rows, (list, tuple)) or len(rows) > 64:
raise ValueError("expected at most 64 teaching records")
clean = []
seen = set()
for row in rows:
if not isinstance(row, (list, tuple)) or len(row) != 2:
raise ValueError("expected identifier and score")
ident, score = row
if (type(ident) is not int or type(score) is not int
or not 1 <= ident <= 1000000 or not 0 <= score <= 100
or ident in seen):
raise ValueError("expected unique integer ID and bounded score")
seen.add(ident)
clean.append((ident, score))
con = sqlite3.connect(":memory:")
try:
con.execute("CREATE TABLE review(id INTEGER PRIMARY KEY, score INTEGER)")
con.executemany("INSERT INTO review VALUES (?, ?)", clean)
return con.execute(
"SELECT id, score, "
"RANK() OVER (ORDER BY score DESC), "
"DENSE_RANK() OVER (ORDER BY score DESC), "
"ROW_NUMBER() OVER (ORDER BY score DESC, id) "
"FROM review ORDER BY score DESC, id").fetchall()
finally:
con.close()
print(rank_review_rows([(20, 90), (40, 50), (10, 90), (30, 70)]))Explain the tied and untied cases from the returned rows
The returned identifiers are ten, twenty, thirty and forty. Their competition ranks are one, one, three and four. Their dense ranks are one, one, two and three. Queue positions are one through four. The third record has competition rank three because two rows precede its score group, while its dense rank is two because only one distinct score group precedes it. Both descriptions are consistent with the same supplied records. A recipient should choose between them using the question being asked, rather than treating a gap as evidence of a lost row.
Try all records with the same score. Both rank columns then contain only ones, while the queue positions remain distinct under identifier ordering. Next try all different scores, then a single record and an empty collection. The empty collection returns no rows; it does not invent a first-ranked record. These cases show why a test containing only distinct scores cannot expose a mistaken peer definition. Reorder the input rows as well. With the same identifiers and scores, this complete query should produce the same result independently of the insertion order.
Check what a rank threshold would actually select
Suppose a downstream report asks for the first two score groups. In this constructed result, dense rank at most two selects three records: both ninety-score records and the seventy-score record. Queue position at most two instead selects only the two ninety-score records. Competition rank at most two also selects those two records here, because the next group starts at rank three. These different selections follow directly from the returned columns. Write down the intended selection before someone applies a threshold to a column whose name merely sounds appropriate.
Test the selection at a tie boundary as well as the labels themselves. If a report expects exactly two rows, a score-group threshold can legitimately return more than two when the boundary group contains several records. If it expects complete score groups, cutting at an individual row position can split a group. Neither policy is universally correct. The tutorial makes the distinction inspectable so a reviewer can document the report requirement and verify its output on a fixed set of records before using the query in a larger workflow.
Retain the selected population when sharing the result
A rank is relative to the rows being ranked. Keep the register revision, selection rule and query with the export. If another reviewer removes a record or changes a score, compare that as a different population rather than interpreting the new rank as a measured improvement. The example deliberately uses one undivided queue. A production report that needs separate queues must define its grouping contract before adding partition expressions. Do not compare ranks from unrelated populations as if the same number establishes the same inspection need or workload.
For a useful handoff, name the columns explicitly and retain the original row identifiers. Explain that dense rank describes score groups, competition rank includes gaps after ties, and queue position selects individual rows. The owner-supplied aircraft photograph provides product context only; it does not illustrate a scored survey or an operational queue. The practical outcome of this exercise is a reproducible query whose labels reveal their meaning. It gives a team a clear basis for checking a report without turning an arbitrary number into a claim about NiVO performance or project acceptance.



