Course contents 04 / 17

04 / 17 · Reading Tables

Duplicates and ordering

Predict which repetitions a query keeps, then specify a tie-breaker so that a limited result selects the intended rows.

Prerequisites

Types and NULL

On this page 4

The shop needs a list of products sold. The six order lines have distinct position identifiers. The product name answers a different question, and tea occurs in three of those positions. The answer depends on whether each output row stands for a sale line or for a product.

Why a query repeats a value#

The first query reads one product name for each order line. The second asks for one row per distinct name.

SELECT product
FROM order_lines
ORDER BY product;

SELECT DISTINCT product
FROM order_lines
ORDER BY product;
ProductOccurrences with SELECTOccurrences with SELECT DISTINCT
cocoa11
coffee21
tea31

The first result has six rows because projecting the product column retains one output row per input line. A multiset, also called a bag, records how many times each element appears. The multiplicity of tea is three because lines 101/1, 102/1 and 103/2 all contribute it. A mathematical set records membership alone. Classical relational algebra works with sets, so projection there produces one tuple for each distinct combination of retained attributes. A plain SQL SELECT uses ALL by default and preserves the multiplicities. Pavlo, 2025, §§4, 6 PostgreSQL 18, SELECT

DISTINCT compares complete output rows. In SELECT DISTINCT product, quantity, the two rows ('tea', 1) collapse into one, and ('tea', 2) still appears separately. There are five output pairs. Adding order_id and line_no to the output distinguishes all six positions in this example, so DISTINCT over that output removes nothing. Choose the fields that describe one unit of the answer before asking for duplicates to be removed.

Missing values in a distinct result#

Consider two provisional prices missing from a feed, plus a known price of 350 cents. The VALUES clause supplies the three input rows without changing the shop’s data.

SELECT DISTINCT price_cents
FROM (VALUES (NULL::integer), (350), (NULL)) AS feed(price_cents)
ORDER BY price_cents NULLS LAST;

The output is 350, then one NULL. A comparison such as price_cents = NULL still evaluates to unknown. Duplicate elimination uses a different comparison rule. At the same output position, two missing values count as indistinguishable for that operation. The one NULL row says that the input contains at least one missing value. It gives no count of the missing inputs. PostgreSQL 18, Select Lists SQLite, §2.6

A limit needs an order#

The shop also wants the highest-value line. We can compute its value in cents and request a single result.

SELECT order_id, line_no,
       quantity * unit_price_cents AS line_total_cents
FROM order_lines
ORDER BY line_total_cents DESC
LIMIT 1;

Lines 103/1 and 104/1 both cost 1200 cents. Each satisfies the only sort key equally well, so the query can return either one. A result that repeats across several runs still gives no contractual tie-breaker. With no ORDER BY at all, even membership in the group priced at 1200 cents is unspecified. Likewise, duplicate elimination by itself gives no order guarantee. PostgreSQL 18, §§7.5–7.6

To pick one line, specify what to do on a tie. First compare amounts from high to low. For equal amounts, take the lower order number. If the orders also match, take the lower position number. The pair (order_id, line_no) distinguishes every line in the sample.

SELECT order_id, line_no,
       quantity * unit_price_cents AS line_total_cents
FROM order_lines
ORDER BY line_total_cents DESC, order_id ASC, line_no ASC
LIMIT 1;

Line 103/1 comes first since 103 is less than 104. Sort directions apply to the key they follow. Only the amount goes in descending order here. PostgreSQL 18, §7.5

Figure

The limit cuts through a tie

The limit cuts through a tieTwo lines cost 1200. With amount as the only key either may come first. For tied amounts the smaller order number puts 103/1 first.103/1 · 1200104/1 · 1200Amount aloneLIMIT 1103/1 or 104/1Amount, order, lineLIMIT 1103/1
Both lines cost 1200 cents. With LIMIT 1 and amount as the only sort key, either line can be returned. The additional keys put line 103/1 first.

If the request is for every line tied for the maximum, keep the amount as the sole sort key and use FETCH FIRST 1 ROW WITH TIES in place of LIMIT 1. That returns both 1200-cent lines. Ties are judged using the entire sort key, so including the position identifier inside that query would change which rows qualify. PostgreSQL 18, SELECT

For a nullable amount, specify where missing values belong. In PostgreSQL, DESC puts them first by default, so one missing amount could fill the entire one-row result. With DESC NULLS LAST, known amounts come first. If the query may return only known amounts, exclude missing ones in WHERE as well. SQLite puts missing values last by default under DESC, which is a reason to write the null placement explicitly in queries used with both systems. PostgreSQL 18, §7.5 SQLite, §4

A stable order over changing data#

OFFSET skips rows of the ordered result. Over the original six rows, the order with tie-breakers starts 103/1, 104/1, 101/1. LIMIT 2 gives the first two, and LIMIT 2 OFFSET 2 starts at 101/1. Suppose an additional line 107/1 worth 1500 cents becomes visible between those requests. The second query now skips 107/1 and 103/1. It starts at 104/1, repeating a line from the first page even though both queries use the same sort keys. PostgreSQL 18, §§7.6, 13.2.1

A total order makes positions unambiguous for a given input. Keeping the same input visible across several queries is a separate requirement. The opening Databases note introduces the visibility of committed changes between queries.

Next#

DISTINCT can tell us which products occurred. To retain a count or a total for each product, we need to collect its rows and compute one result for the group. Grouping and aggregation develops that operation.

References#

  1. PostgreSQL Global Development Group. PostgreSQL 18 documentation, 2025. SELECT specifies row selection and WITH TIES. Select Lists explains duplicate elimination. §7.5 specifies sorting and null placement, §7.6 limits and offsets, and §13.2.1 visibility between statements under Read Committed.
  2. Andy Pavlo. Relational Model & Algebra. CMU 15-445/645, Fall 2025, §§4, 6. Defines relations as unordered sets and describes projection over a relation.
  3. SQLite project. SELECT, §§2.6 and 4. Specifies duplicate handling and the default placement of missing values in SQLite.