Test iOS SQLite NULL filters and aggregates on a cloud Mac

Test iOS SQLite NULL filters and aggregates on a cloud Mac

Test iOS SQLite NULL filters and aggregates on a cloud Mac

A colleague in Asia-Pacific submitted a query to “exclude processed items.” When a North American colleague opened the list the next day, it was empty. No data had been lost, and the network was working: a new NULL in the exclusion table had changed the result of NOT IN. Capturing this kind of issue in a small SQL fixture makes it easier to diagnose than repeatedly refreshing the UI.

This article sets up an isolated check of NULL semantics on a cloud Mac, then carries the same sample data into the iOS data-access layer. It is intended for teams that already use SQLite queries and hand work off across time zones. If a remote API handles all filtering, run these checks where the queries actually execute.

Define what NULL means first

NULL represents a missing or unknown value. It is neither zero nor an empty string. Start by writing a one-sentence business definition for each field: a missing amount means “not entered yet,” while zero means “confirmed no charge.” Do not merge the two simply to make display logic easier.

SQL comparisons have three possible outcomes: TRUE, FALSE, and UNKNOWN. WHERE keeps only TRUE results, so amount <> 0 does not select rows with a missing amount. Nor can amount = NULL find missing values; use amount IS NULL instead.

The presentation layer can display a dash for a missing value, but the query layer must preserve the distinction between NULL and zero. A display default does not define database semantics.

Also establish whether identifiers can be NULL. In the examples below, the main table’s integer primary key is always non-NULL. The exclusion table allows NULL to simulate imported records whose identifiers have not yet been resolved.

Reproduce the filtering trap in an isolated database

Create tests/sql/null-contract.sql in the repository and save the complete contents below. The test uses only an in-memory database. It does not connect to application database files or require you to clear existing data on a remote development machine.

.bail on

CREATE TABLE items (
    id INTEGER PRIMARY KEY,
    amount INTEGER
);

CREATE TABLE excluded (
    item_id INTEGER
);

INSERT INTO items VALUES (1, 10), (2, NULL), (3, 0);
INSERT INTO excluded VALUES (2), (NULL);

CREATE TEMP TABLE checks (
    name TEXT NOT NULL,
    ok INTEGER NOT NULL CHECK (ok IS 1)
);

INSERT INTO checks
SELECT 'not-in-with-null',
       (SELECT COUNT(*) FROM items
        WHERE id NOT IN (SELECT item_id FROM excluded)) = 0;

INSERT INTO checks
SELECT 'not-exists',
       (SELECT COUNT(*) FROM items AS i
        WHERE NOT EXISTS (
            SELECT 1 FROM excluded AS e
            WHERE e.item_id = i.id
        )) = 2;

INSERT INTO checks
SELECT 'not-in-filtered',
       (SELECT COUNT(*) FROM items
        WHERE id NOT IN (
            SELECT item_id FROM excluded
            WHERE item_id IS NOT NULL
        )) = 2;

INSERT INTO checks
SELECT 'nonzero-only',
       (SELECT COUNT(*) FROM items WHERE amount <> 0) = 1;

INSERT INTO checks
SELECT 'nonzero-or-missing',
       (SELECT COUNT(*) FROM items
        WHERE amount <> 0 OR amount IS NULL) = 2;

INSERT INTO checks
SELECT 'aggregate-contract',
       COUNT(*) = 3 AND COUNT(amount) = 2
       AND SUM(amount) = 10 AND AVG(amount) = 5.0
FROM items;

INSERT INTO checks
SELECT 'empty-aggregate',
       COUNT(*) = 0 AND SUM(amount) IS NULL
       AND AVG(amount) IS NULL
FROM items WHERE id < 0;

SELECT 'null-contract-ok';

The first assertion deliberately records the dangerous query’s actual behavior; it is not a recommendation. The NULL in the exclusion table makes the condition evaluate to UNKNOWN for items without a match, so no rows pass the filter. The next two assertions verify two ways to fix this: a correlated NOT EXISTS, and NOT IN with NULL values filtered out of the exclusion table first.

Do not apply either rewrite mechanically to every query. If the outer column also allows NULL, the two approaches may not be equivalent. Add cases that define whether rows with unknown identifiers should be retained.

Pin down aggregation semantics too

The sample amounts are ten, NULL, and zero. COUNT(*) counts all three rows, while COUNT(amount) counts only the two non-NULL values. The denominator for AVG(amount) is also two, giving a result of five. Replacing NULL with zero before calculating the average changes both the denominator and the business meaning.

An empty result set introduces another boundary case: COUNT(*) returns zero, but SUM and AVG return NULL. If a report needs to display zero, first define the intended semantics, then use COALESCE. Do not let the data-mapping layer silently make that conversion.

The assertion table uses CHECK (ok IS 1). This detail is easy to miss: an ordinary CHECK expression can pass when it evaluates to NULL. Here, the result must explicitly equal one, so NULL cannot bypass the check itself. .bail on stops the script as soon as a constraint fails.

Run the checks on a cloud Mac and keep the evidence

Run the following commands from the repository root. Record the runtime library version, but do not include the version output in the assertion.

set -eu
mkdir -p artifacts
/usr/bin/sqlite3 --version > artifacts/sqlite-version.txt
actual=$(/usr/bin/sqlite3 :memory: < tests/sql/null-contract.sql)
test "$actual" = "null-contract-ok"
printf '%s\n' "$actual" > artifacts/null-contract.txt

If any assertion fails, the command returns a nonzero exit status and the pipeline must stop. Do not ignore the exit status and continue. A missing output marker also counts as a failure, preventing a partially executed script from being mistaken for a successful run.

For the handoff, keep the commit identifier, SQL file, and version record. This fixture contains no customer data, so a colleague in another time zone can rerun it directly in their own working directory without sharing a database that is in use.

Finish by testing through the iOS data-access layer

Passing the command-line checks proves only how the fixture behaves with the current runtime library. The app may use the system SQLite library or bundle a different version. Its wrapper layer may also convert NULL values to defaults, so the same data must be tested through the app’s actual database connection.

At a minimum, verify three things: writing a missing value actually uses NULL binding rather than binding an empty string; the column type is checked before reading an integer, so NULL is not treated as zero; and filtering tests compare the sorted sets of identifiers directly, not just row counts. The corrected exclusion query should return one and three, and the query for missing amounts should return two.

Add cases where the exclusion table is empty, contains only NULL, or contains duplicate identifiers. Give each test its own database and close the connection when the test ends. The handoff is then no longer “the list looks fine on my machine,” but executable evidence that checks filtering results, aggregation denominators, and NULL mapping together.

Frequently asked questions

Why can NOT IN return fewer rows when its subquery contains NULL?

A comparison can evaluate to UNKNOWN even without matching a known value, and WHERE retains only TRUE. Use correlated NOT EXISTS or remove NULL from the subquery according to the intended semantics. Nullable outer keys need an explicit policy too.

Does passing the SQLite command-line test validate the iOS query?

No. Run the same fixtures through the app's actual connection or wrapper and check bindings, NULL reads and returned IDs. The runtime SQLite version and mapping code may differ.

Get a dedicated Mac mini for your project

A whole machine, dedicated to one customer—ideal for remote development, automated builds, and always-on workloads. Rent by the day for short-term projects, then choose the term that works for you.

Get a cloud Mac

Choose a setup that fits your project

Check the memory, storage, and rental term first. Choose a rental for continuous availability, or keep using a suitable device you already own.