Advanced SQL with PostgreSQL / Correct rows and quantities

Make null-sensitive existence decisions

Lesson 5 of 51. Open to read. No account needed.

Harbor Supply receives a fictional external exclusion feed. A known order key means “hold this order”; a missing feed key cannot identify an order. The feed contains 101 twice and one unknown key. We want the remaining known orders, with one output row per order. What happens if the query uses NOT IN?

Use the checked small fixture and owned workspace from the fixture lesson. Its order keys are 101, 102, 103 and 104, all non-null primary keys. The external feed below is inline input, not a change to the fixture's refund or event tables.

Predict the predicate before filtering

SQL null represents a missing value here. Ordinary equality involving a null produces unknown, including NULL = NULL. IS NULL tests missingness directly. WHERE keeps true; both false and unknown are discarded.

For 102, checking that it differs from every feed key includes comparing it with the unknown key. We know it differs from 101; we cannot establish that it differs from an unknown identifier. NOT IN therefore produces unknown. For 101, an equal key is present, so NOT IN is false despite the missing key.

Candidate orderFeed contains a known equal key?NOT IN resultKept by WHERE NOT IN?
101YesfalseNo
102No; also an unknown keyunknownNo
103No; also an unknown keyunknownNo
104No; also an unknown keyunknownNo

The output would be empty, which conflicts with our policy. A filter returning no rows is not evidence that every order was explicitly excluded.

Ask whether a matching row exists

EXISTS asks whether a subquery produces any rows. NOT EXISTS is true when it produces none. A correlated subquery can refer to the outer candidate alias in its condition. Here f.order_key = o.order_id asks whether an equal known feed key is present. This describes logical matching, not a promise that the engine physically executes the inner query once for every order.

SELECT 1 is a conventional projected value for this existence test. It does not count rows. Even SELECT NULL WHERE TRUE produces a row, so EXISTS is true for that query. A matching row whose displayed value is null is different from no row at all. Duplicate matching feed rows do not multiply outer orders when used only through this predicate.

The inline input (VALUES (101), (101), (NULL)) AS f(order_key) supplies three one-column rows. Each parenthesized item is a row; f names the derived input and order_key names its column. It creates no persistent table. This small bridge lets you vary a nullable external feed without weakening the fixture's non-null key constraints.

Inspect the complete comparison

Recheck the local Docker context, owned labels and marker using the prior lesson's check-small.sql. Restore the small fixture first if you intentionally changed it. Save this complete input as null-worked.sql in the owned host lab folder. It uses only checks and SELECT queries, with bounded session timeouts.

\set ON_ERROR_STOP on
\if :{?lab_id}
\else
  \echo 'Stop: supply the non-secret lab_id from connection.txt.'
  SELECT 1 / 0 AS guard_rejected;
\endif
SELECT current_database() = 'asql_lab'
       AND current_user = 'asql_student'
       AND current_setting('server_version_num') = '180006' AS target_ok
\gset
\if :target_ok
\else
  \echo 'Stop: wrong database, execution role or server release.'
  SELECT 1 / 0 AS guard_rejected;
\endif
SET lock_timeout = '3s';
SET statement_timeout = '15s';
SELECT COUNT(*) = 1 AS marker_ok
FROM asql_control.lab
WHERE course_id = 'advanced-sql'
  AND lab_id = :'lab_id'
  AND fixture_id = 'harbor-small'
\gset
\if :marker_ok
\else
  \echo 'Stop: the course marker does not match this lab.'
  SELECT 1 / 0 AS guard_rejected;
\endif
\pset null '[NULL]'
-- Predicate inspection: duplicate and missing keys in an external feed.
SELECT o.order_id,
       o.order_id NOT IN (
         SELECT f.order_key FROM (VALUES (101), (101), (NULL)) AS f(order_key)
       ) AS not_in_feed,
       NOT EXISTS (
         SELECT 1 FROM (VALUES (101), (101), (NULL)) AS f(order_key)
         WHERE f.order_key = o.order_id
       ) AS no_equal_feed_row
FROM harbor.orders AS o
ORDER BY o.order_id;

-- WHERE retains only true: the contaminated NOT IN returns no order rows.
SELECT o.order_id FROM harbor.orders AS o
WHERE o.order_id NOT IN (
  SELECT f.order_key FROM (VALUES (101), (101), (NULL)) AS f(order_key)
)
ORDER BY o.order_id;

-- Exclude known matching keys; missing feed keys cannot identify an order.
SELECT o.order_id FROM harbor.orders AS o
WHERE NOT EXISTS (
  SELECT 1 FROM (VALUES (101), (101), (NULL)) AS f(order_key)
  WHERE f.order_key = o.order_id
)
ORDER BY o.order_id;

-- Filtering the feed is another valid form for these non-null parent keys.
SELECT o.order_id FROM harbor.orders AS o
WHERE o.order_id NOT IN (
  SELECT f.order_key FROM (VALUES (101), (101), (NULL)) AS f(order_key)
  WHERE f.order_key IS NOT NULL
)
ORDER BY o.order_id;

-- Candidate keys can themselves be unknown in an external input.
SELECT c.order_key,
       NOT EXISTS (
         SELECT 1 FROM (VALUES (101), (NULL)) AS f(order_key)
         WHERE f.order_key = c.order_key
       ) AS no_equal_feed_row,
       NOT EXISTS (
         SELECT 1 FROM (VALUES (101), (NULL)) AS f(order_key)
         WHERE f.order_key IS NOT DISTINCT FROM c.order_key
       ) AS no_null_safe_match
FROM (VALUES (101), (102), (NULL), (104)) AS c(order_key)
ORDER BY c.order_key NULLS LAST;

-- Empty-set boundary: no right-hand values can contradict NOT IN.
SELECT NULL NOT IN (
         SELECT order_id FROM harbor.orders WHERE FALSE
       ) AS missing_not_in_empty,
       NULL NOT IN (SELECT 101) AS missing_not_in_nonempty;

-- EXISTS examines rows, including a row whose projected value is null.
SELECT EXISTS (SELECT NULL WHERE TRUE) AS row_exists,
       EXISTS (SELECT NULL WHERE FALSE) AS row_absent;

Run it from that folder with the same sourced session.sh helper:

asql exec -T db psql -X -v ON_ERROR_STOP=1 -v lab_id="$asql_run" \
  -U asql_student -d asql_lab < null-worked.sql

The first query exposes each predicate rather than immediately hiding rows. \pset null '[NULL]' makes the client's null display explicit; it does not convert nulls into strings in the data. PostgreSQL displays booleans as t/f. Illustrative values for this supplied input are:

order_idnot_in_feedno_equal_feed_row
101ff
102[NULL]t
103[NULL]t
104[NULL]t

The second query returns zero rows. The third returns 102, 103, 104. Its equality condition finds no matching feed row for those keys, so NOT EXISTS is true. That is the intended answer under our declared policy. Repeated 101 entries still exclude only one parent order.

The fourth query also returns 102, 103, 104. Filtering nulls out of the right side makes NOT IN a valid alternative here because the left side is also known non-null. Choose from the actual key contracts; replacing every NOT IN by a slogan is less useful than explaining the predicate. These queries make no comparative speed claim.

Decide what an unknown candidate means

The fifth query changes the input contract: candidates can now have unknown keys. Under ordinary equality, a null candidate has no true equality match, even against a null feed value. Ordinary NOT EXISTS therefore includes it.

IS NOT DISTINCT FROM supplies null-safe equality: two nulls compare as equal. The second predicate deliberately uses that rule instead. The results are:

Candidateno_equal_feed_rowno_null_safe_match
101ff
102tt
104tt
[NULL]tf

NULLS LAST explicitly places the missing candidate after known keys in this ordered display. Neither predicate discovers a real order identity for that missing value. Null-safe matching is useful only when the domain intentionally treats missing values as one matching category. Unknown order IDs do not prove that two records describe the same order. For an actionable known-key list, require c.order_key IS NOT NULL as well as the anti-existence test.

Do not replace missing identifiers by a made-up value using COALESCE. A chosen sentinel can collide with a legitimate identifier, and the query then asserts an identity that the input never established. The previous lesson's zero policy for an absent monetary group does not justify inventing order keys.

Check the boundaries and diagnose disagreements

The sixth query returns t for the empty right side and [NULL] for the nonempty right side. There are no values in the empty subquery that can violate NOT IN, even when the candidate is null. The rule is therefore more precise than “a null left operand always yields unknown.” The seventh query returns t and f: row presence determines EXISTS, not the projected null value.

Before moving on, hide the printed results and predict what happens if you remove the feed's NULL row. For known parents, NOT IN now returns 102, 103, 104. Adding another duplicate 101 does not change either membership answer. Make those two edits only in a copy of your local read-only file, run it, and explain the observations. No fixture reset is needed afterward.

If you see zero rows unexpectedly, inspect the predicate as a selected column and examine nulls on both sides. If a supposedly actionable output contains a missing key, inspect the candidate policy rather than changing equality blindly. If duplicate orders appear, check whether the query joined raw feed rows instead of using an existence predicate, and revisit its intended grain. A guard error requires checking identity/marker from the lab lesson before running any query.

Independent task: two honest outputs from one input

Use inline candidates 201, 202, NULL and 204, and an exclusion feed containing 201 and NULL. These fictional external keys need not exist in harbor.orders; this task tests the policy on the supplied input, not a referential-integrity claim. Write and predict two reports before running either:

  1. An actionable list: only known candidate keys without an equal feed key.
  2. A review list: every candidate without a known equal feed key, retaining an unknown candidate for human investigation.

Keep one row per supplied candidate, order known keys ascending and missing keys last. Explain why the reports differ. Explain separately what would happen if you matched with IS NOT DISTINCT FROM. Use only the small inline inputs and read-only queries in the checked lab. Do not add rows to the persistent fixture.

Hints

First trace equality for the null candidate: which comparison can become true? Then write each policy in words before selecting predicates. The actionable list needs a separate known-key condition. The review list intentionally keeps uncertainty visible; it does not authorize action on an unidentified order.

Answer and reasoning

The complete reference input null-solution.sql is:

\set ON_ERROR_STOP on
\if :{?lab_id}
\else
  \echo 'Stop: supply the non-secret lab_id from connection.txt.'
  SELECT 1 / 0 AS guard_rejected;
\endif
SELECT current_database() = 'asql_lab'
       AND current_user = 'asql_student'
       AND current_setting('server_version_num') = '180006' AS target_ok
\gset
\if :target_ok
\else
  \echo 'Stop: wrong database, execution role or server release.'
  SELECT 1 / 0 AS guard_rejected;
\endif
SET lock_timeout = '3s';
SET statement_timeout = '15s';
SELECT COUNT(*) = 1 AS marker_ok
FROM asql_control.lab
WHERE course_id = 'advanced-sql'
  AND lab_id = :'lab_id'
  AND fixture_id = 'harbor-small'
\gset
\if :marker_ok
\else
  \echo 'Stop: the course marker does not match this lab.'
  SELECT 1 / 0 AS guard_rejected;
\endif
\pset null '[NULL]'
-- Policy A: actionable known keys only.
SELECT c.order_key
FROM (VALUES (201), (202), (NULL), (204)) AS c(order_key)
WHERE c.order_key IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM (VALUES (201), (NULL)) AS f(order_key)
    WHERE f.order_key = c.order_key
  )
ORDER BY c.order_key NULLS LAST;

-- Policy B: review candidates with no known equal feed key, including unknowns.
SELECT c.order_key
FROM (VALUES (201), (202), (NULL), (204)) AS c(order_key)
WHERE NOT EXISTS (
  SELECT 1 FROM (VALUES (201), (NULL)) AS f(order_key)
  WHERE f.order_key = c.order_key
)
ORDER BY c.order_key NULLS LAST;

Execute with the same guarded command, substituting null-solution.sql for the worked filename. The first result is 202, 204. The second is 202, 204, [NULL]. 201 has a true equal feed match. For the unknown candidate, ordinary equality never supplies a true match; the first report rejects it explicitly while the second retains it. With null-safe matching the null feed row would match the null candidate, so that candidate would be excluded. That third behavior would need an intentional missing-category policy; it does not identify an order.

A correct alternative may use NOT IN after filtering right-side nulls and applying the required left-side policy. Simply filtering feed nulls and using NOT IN for the review report still loses its unknown candidate. State both contracts and check all three cases: known match, known nonmatch and unknown.

Leave the session and fixture clean

These files create no database objects or fixture changes. Let the psql process exit normally; its display setting and timeouts end with that session. Remove only your optional edited file copy when finished. Keep the owned lab and the baseline fixture for the next lesson; follow the connection lesson's exact label-checked shutdown procedure when ending the lab session.

Self-check: changing NOT IN to NOT EXISTS fixes the contaminated exclusion behavior for known keys here. Does it alone decide whether an unknown candidate belongs in an actionable list? Explain why the candidate policy is separate.

Source notes: PostgreSQL 18 subquery predicates, comparison predicates, VALUES inputs and ordering support these semantics. The feed, policies, worked data and practice variation are original synthetic examples.

46 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 149 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy