Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Caribbean Aircraft Data in DuckDB: Query State Changes

· 5 min read · Home Tech

In this article
  1. Why State Changes Matter in Caribbean Aircraft Data
  2. Core Query Pattern: Using LAG() to Detect Changes
  3. Handling Irregular Time Intervals and Duplicates
  4. Advanced: Detecting Changes in Multiple Columns and Custom State Definitions
  5. Common Pitfalls and Misconceptions
  6. Alternatives: DuckDB-Specific Features and Other Tools
  7. Frequently Asked Questions

To query state changes in Caribbean aircraft data stored in DuckDB, you use window functions—specifically LAG() or LEAD()—to compare a row with its predecessor and detect when a field like status, altitude, or location changes. This article explains the exact SQL patterns, common pitfalls, and how to handle the region's unique data quirks.

Why State Changes Matter in Caribbean Aircraft Data

Aircraft tracking data—whether from ADS-B, radar, or flight plans—arrives as a series of timestamped records. Each record contains position, altitude, speed, and status flags. A “state change” occurs when any of these attributes transitions from one value to another, such as an aircraft climbing from cruise to descent, changing squawk code, or crossing from one FIR (Flight Information Region) to another. In the Caribbean, where many small islands each have their own airspace and reporting procedures, detecting these transitions is essential for air traffic control analysis, safety audits, and route optimization. Queries that simply filter for a specific status miss the transition moment; you need to compare consecutive rows per aircraft.

Core Query Pattern: Using LAG() to Detect Changes

DuckDB supports standard SQL window functions. The basic pattern to detect a change in a column (say status) for each aircraft, ordered by time, is:

SELECT
  *,
  LAG(status) OVER (PARTITION BY aircraft_id ORDER BY ts) AS prev_status
FROM caribbean_flights
QUALIFY status <> prev_status OR prev_status IS NULL;

The LAG() function fetches the previous row's status within the same aircraft partition. QUALIFY filters rows where the status differs from the previous one, or where there is no previous row (the first record). This returns only the rows where a change occurred, plus the initial state. If you want only actual changes (excluding the first record), add AND prev_status IS NOT NULL. For multiple columns, you can compare each with its own LAG().

Handling Irregular Time Intervals and Duplicates

Caribbean data often has gaps—radar coverage is patchy over open water, and some aircraft only transmit periodically. If you use LAG() directly, a change might be missed if the previous record is hours old. To address this, you can filter to only consider rows within a certain time window, e.g., WHERE ts - LAG(ts) OVER (...) < INTERVAL '15 minutes'. Also, duplicate records (same aircraft, same timestamp) can cause false changes. Use QUALIFY ROW_NUMBER() OVER (PARTITION BY aircraft_id, ts ORDER BY ts) = 1 to deduplicate first. Another approach is to use GROUP BY with array_agg to collapse consecutive identical states, but window functions are more flexible.

Advanced: Detecting Changes in Multiple Columns and Custom State Definitions

Sometimes a “state” is a composite of several fields, e.g., (altitude_bucket, status). You can concatenate them: LAG(status || '|' || altitude_bucket) OVER (...). Or use a CASE to define a derived state column first. For example, to detect when an aircraft transitions from cruising to descending, you might define CASE WHEN vertical_rate < -100 THEN 'desc' ELSE 'cruise' END, then apply LAG() on that. DuckDB also supports LEAD() for forward-looking changes, which is useful for detecting the start of a maneuver. For performance, ensure the table is sorted by aircraft_id, ts and consider creating an index on (aircraft_id, ts).

Common Pitfalls and Misconceptions

One frequent mistake is not partitioning by aircraft, causing changes to be detected across different planes. Another is ignoring NULLs—if a field is missing, LAG() returns NULL, and comparing with <> yields NULL (not true), so the change is missed. Use IS DISTINCT FROM instead: status IS DISTINCT FROM prev_status. Also, time zones: Caribbean data may be in UTC or local time; always convert to a consistent timezone before ordering. Finally, don't assume the first row is a change—decide whether you want to include it.

Alternatives: DuckDB-Specific Features and Other Tools

DuckDB offers the arg_max and arg_min functions, but for state changes, window functions remain the standard. You could also use a self-join: SELECT a.* FROM flights a JOIN flights b ON a.aircraft_id = b.aircraft_id AND a.ts = (SELECT MIN(ts) FROM flights WHERE aircraft_id = a.aircraft_id AND ts > b.ts) WHERE a.status <> b.status—but that's less readable. If your data is in Parquet files, DuckDB can query them directly, and you can use the same SQL. For very large datasets, consider pre-aggregating with GROUP BY and min/max timestamps per state, but for most Caribbean flight volumes (thousands of flights per day), window functions are fast enough.

Frequently Asked Questions

How do I get only the rows where the status changed, not the first row?

Add AND prev_status IS NOT NULL to your QUALIFY clause. That excludes the first record per aircraft, which has no previous status.

What if my data has a status change but the timestamp is the same for two rows?

That's a duplicate or simultaneous update. Use ROW_NUMBER() to pick one row per (aircraft_id, ts), or add a secondary sort key like a sequence number. Then apply LAG() on the deduplicated set.

Can I detect changes in altitude that are more than 1000 feet?

Yes. Compute the difference: abs(altitude - LAG(altitude) OVER (...)) > 1000. This requires the previous altitude, not just a status string.

How do I handle missing data for an aircraft for 30 minutes?

You can filter out gaps by checking the time difference: ts - LAG(ts) OVER (...) < INTERVAL '30 minutes'. This prevents false “changes” when the previous record is stale.

Is there a way to see the duration of each state?

Yes. After detecting changes, use LEAD(ts) to get the next change time, then compute the difference. Or use GROUP BY on the state with min(ts) and max(ts).

Does DuckDB support QUALIFY?

Yes, DuckDB supports the QUALIFY clause, which filters window function results. It's available in versions 0.7 and later.