# Downsample GPS tracks with SDT

> **For AI agents:** the complete documentation index is at [llms.txt](https://questdb.com/docs/llms.txt). Every page is available as markdown by appending `.md` to its URL, or by sending an `Accept: text/markdown` request header.

Shrink historical vehicle GPS data with Swinging Door Trending, keeping only the points needed to rebuild each route within a known distance.

Keep months of vehicle GPS history without storing every ping. The `sdt()`
window function keeps only the points needed to rebuild each route within a
distance you choose, and a view joins the compressed history with recent raw
data.

## Problem

A fleet of 300 trucks sends a GPS position every 10 seconds. That is about 2.6
million rows per day and 233 million rows over 90 days. Most of those rows
add nothing: a truck on a motorway at constant speed, or parked overnight,
produces thousands of points that lie on a straight line.

The positions are stored in a table like this:

```questdb-sql title="Raw GPS table"
CREATE TABLE gps (
  ts TIMESTAMP,
  truck_id SYMBOL,
  lat DOUBLE,
  lon DOUBLE,
  speed DOUBLE,
  event_type SYMBOL
) TIMESTAMP(ts) PARTITION BY DAY TTL 8 DAYS;
```

You want to keep recent days at full resolution, and only the significant
points for older days.

## Solution

[Swinging Door Trending](/docs/query/sql/subsample/#sdt---swinging-door-trending)
(SDT) keeps the points needed so that straight-line interpolation in time
between kept points stays within a tolerance. It does not keep "points where
the position changed": a truck moving steadily changes position constantly,
yet keeps almost no points. Straight stretches and stops collapse to a few
points, while turns and speed changes keep more.

SDT works on one value at a time, so run it once per axis and keep a row when
either flag is set:

```questdb-sql title="Compress each truck's track for the day one week ago"
DECLARE
  @day := '$today-7d',
  @ref_lat := 25.0,
  @lon_factor := cos(radians(@ref_lat)),
  @tol := 5
WITH flagged AS (
  SELECT ts, truck_id, lat, lon, speed,
    sdt(ts, lat * 111320.0, @tol)
      OVER (PARTITION BY truck_id ORDER BY ts) AS keep_y,
    sdt(ts, lon * 111320.0 * @lon_factor, @tol)
      OVER (PARTITION BY truck_id ORDER BY ts) AS keep_x
  FROM gps
  WHERE ts IN @day
)
SELECT ts, truck_id, lat, lon, speed
FROM flagged
WHERE keep_x OR keep_y;
```

This keeps each truck's route to within roughly 10 meters:

- `@day` is the time range to compress. It accepts any
  [TICK](/docs/query/operators/tick/) interval, such as
  `'$today-14d..$today-8d'` for a backfill.
- `111320.0` converts degrees of latitude to meters, so the tolerance is in
  meters and both axes are comparable.
- A degree of longitude is shorter away from the equator, by the cosine of
  the latitude. `@ref_lat` is a reference latitude for the fleet: 25° suits
  trucks running between roughly 19°N and 31°N. Set it to your own fleet's
  average latitude, which `SELECT avg(lat) FROM gps` returns.
- `PARTITION BY truck_id` compresses each truck's series independently.
- The reconstruction error of SDT is bounded by `2 * compdev`, so
  `@tol := 5` gives 10 meters. For a maximum error `E`, use `E / 2`.

The variables must hold literals or constant expressions, because `compdev`
must be a constant. A variable defined as a subquery, such as
`(SELECT avg(lat) FROM gps)`, is rejected.

:::note
Do not compute the cosine per row with `cos(radians(lat))`. Multiplying the
absolute longitude by a factor that changes with latitude turns small
north-south moves into false east-west movement, and SDT keeps many more
points than it should.
:::

### Why SDT

SDT is the only `SUBSAMPLE` method that fits this job:

- It is the only one with an error bound. You can reconstruct where a truck
  was at any moment to within a known distance, which matters for ETAs,
  geofence audits, and disputes.
- The data decides how many points survive. `lttb`, `m4`, `minmax`, and
  `uniform` take a row budget, and `cadence` keeps every Nth row, so turns get
  cut while straight stretches keep points nobody needs.
- `minmax` and `m4` pick the extremes of one column per interval. For a
  position split across two columns, those rows do not describe the route.
- Only the `sdt()` window function supports `PARTITION BY`, so a single query
  compresses every truck.

The trade-off is that SDT works on one value at a time, which is why the
query runs it once per axis.

### Keep speed changes and events

Position-only SDT can drop rows where the speed changed but the route did
not. Add more flags, and keep rows that must survive regardless, such as
braking events:

```questdb-sql title="Also keep speed changes and event rows"
DECLARE
  @day := '$today-7d',
  @ref_lat := 25.0,
  @lon_factor := cos(radians(@ref_lat)),
  @tol := 5,
  @speed_tol := 2.5
WITH flagged AS (
  SELECT ts, truck_id, lat, lon, speed, event_type,
    sdt(ts, lat * 111320.0, @tol)
      OVER (PARTITION BY truck_id ORDER BY ts) AS keep_y,
    sdt(ts, lon * 111320.0 * @lon_factor, @tol)
      OVER (PARTITION BY truck_id ORDER BY ts) AS keep_x,
    sdt(ts, speed, @speed_tol)
      OVER (PARTITION BY truck_id ORDER BY ts) AS keep_speed
  FROM gps
  WHERE ts IN @day
)
SELECT ts, truck_id, lat, lon, speed, event_type
FROM flagged
WHERE keep_x OR keep_y OR keep_speed OR event_type IS NOT NULL;
```

## Store the compressed history

Run the query once a day and insert the result into a history table with the
same columns. With the 8-day TTL on `gps`, the raw table stays small while the
compressed history grows slowly. `INSERT` does not accept a leading
`DECLARE`, so wrap the declarations and the query in a subquery:

```questdb-sql title="Daily job: append the compressed day to the history table"
INSERT INTO gps_history
SELECT * FROM (
  DECLARE
    @day := '$today-7d',
    @ref_lat := 25.0,
    @lon_factor := cos(radians(@ref_lat)),
    @tol := 5
  SELECT ts, truck_id, lat, lon, speed
  FROM (
    SELECT ts, truck_id, lat, lon, speed,
      sdt(ts, lat * 111320.0, @tol)
        OVER (PARTITION BY truck_id ORDER BY ts) AS keep_y,
      sdt(ts, lon * 111320.0 * @lon_factor, @tol)
        OVER (PARTITION BY truck_id ORDER BY ts) AS keep_x
    FROM gps
    WHERE ts IN @day
  )
  WHERE keep_x OR keep_y
);
```

Compressing the day one week ago, not yesterday, lets late-arriving data
settle first.

A [view](/docs/concepts/views/) then combines both tables in a single query,
reading from the raw table only the rows newer than the latest entry in the
history table:

```questdb-sql title="One view over compressed history and recent raw data"
CREATE VIEW gps_all AS (
  SELECT ts, truck_id, lat, lon, speed FROM gps_history
  UNION ALL
  SELECT ts, truck_id, lat, lon, speed FROM gps
  WHERE ts > (SELECT ts FROM gps_history LIMIT -1)
);
```

SDT always keeps the last point of each truck's series, so the latest row in
`gps_history` is the real last point of the most recently compressed day. The
view has no gaps or duplicates, whenever the daily job runs.

:::note
Create the view after the first `INSERT INTO gps_history`. While the history
table is empty, the subquery returns no row and the view returns no raw rows
either.
:::

## Tuning

- **Set the tolerance above GPS noise.** Consumer GPS wanders a few meters.
  With a tolerance below that, SDT keeps points that only follow the jitter.
- **Gaps are interpolated across.** A tunnel or a GPS outage is not a
  boundary for SDT. To respect trip boundaries, partition by a trip ID
  instead of `truck_id`, or insert a row with a `NULL` position at each
  boundary, since SDT treats `NULL` values as hard run boundaries.
- **The two-axis bound is looser.** Each axis is bounded only against its own
  kept points, so the combined error can in theory exceed `2 * compdev`.
  Tighten `compdev`, or compare against the raw data, if you need a hard
  bound.
- **Measure before committing.** Check the actual reduction per truck on a
  month of data before choosing a retention scheme.

## Alternative without SDT: one point every X meters

Window functions alone can sample a track by distance travelled.
[`geo_distance_meters()`](/docs/query/functions/spatial/#geo_distance_meters)
measures each step against the previous ping, a running `sum()` adds up the
distance, and a row is kept each time the total crosses the next multiple of
`@every_m`. The distance function handles latitude itself, so no conversion
to meters is needed:

```questdb-sql title="Keep one point every 250 meters travelled"
DECLARE
  @day := '$today-7d',
  @every_m := 250
WITH steps AS (
  SELECT ts, truck_id, lat, lon, speed,
    lag(lat) OVER (PARTITION BY truck_id ORDER BY ts) AS prev_lat,
    lag(lon) OVER (PARTITION BY truck_id ORDER BY ts) AS prev_lon
  FROM gps
  WHERE ts IN @day
),
travelled AS (
  SELECT ts, truck_id, lat, lon, speed,
    sum(coalesce(geo_distance_meters(prev_lat, prev_lon, lat, lon), 0))
      OVER (PARTITION BY truck_id ORDER BY ts) AS dist_m
  FROM steps
),
buckets AS (
  SELECT ts, truck_id, lat, lon, speed,
    floor(dist_m / @every_m) AS bucket,
    lag(floor(dist_m / @every_m))
      OVER (PARTITION BY truck_id ORDER BY ts) AS prev_bucket
  FROM travelled
)
SELECT ts, truck_id, lat, lon, speed
FROM buckets
WHERE prev_bucket IS NULL OR bucket <> prev_bucket;
```

A point every X meters, whatever the route does, can suit mileage reports or
drawing routes on a map. For a retention archive, prefer SDT.

### How the two compare

The figures below run both recipe queries on one synthetic truck route: city
blocks, a roundabout, a motorway, a 20 minute stop, and a short city finish.
The worst error is the largest distance between a ping's real position and
the position rebuilt from the kept rows.

Comparing row counts alone is misleading, because the two methods trade rows
for very different accuracy. On the same route:

| Method | Rows kept (of 192) | Worst error |
|--------|-------------------|-------------|
| SDT, 10 m bound | 37 | 7 m |
| One point every 25 m | 87 | 49 m |
| One point every 100 m | 71 | 88 m |
| One point every 250 m | 45 | 96 m |
| One point every 500 m | 23 | 311 m |

SDT keeps fewer rows than any spacing that comes close to its accuracy. A
coarse spacing can keep fewer rows than SDT, but only by allowing an error
of hundreds of meters. Even at 25 m the distance approach stays far from the
10 m bound, mostly because of the stop:

The distance approach loses:

- **Time.** A parked truck produces no new distance, so the stop's start and
  end are not kept, and the rebuilt track creeps through the stop. GPS jitter
  also adds up while parked and produces false distance and extra rows.
- **Shape.** Straight motorway keeps a point every `@every_m`, and a sharp
  turn between two samples is cut.
- **An error bound.** Nothing limits how far the kept track strays from the
  real one.
- **The last point.** It is not always kept, so the `gps_all` view cutoff
  above is no longer exact.

SDT's row count follows the shape of the route, while the distance approach's
follows its length. Long, smooth drives favor SDT the most. On a synthetic
day of 2.59 million rows from 300 trucks on long, gently curving routes with
regular stops, SDT kept about 30,000 rows in about 0.5 seconds. One point
every 250 m kept about 1.25 million rows in about 0.7 seconds.

## Other retention options

Instead of a local history table, you can export the compressed result to
Parquet with
[`COPY (query) TO ... WITH FORMAT PARQUET`](/docs/query/sql/copy/#export-mode-copy-to)
and move the files to object storage.

To keep the full-resolution history, convert older partitions to
[Parquet](/docs/concepts/parquet/#in-place-conversion) on a schedule in
QuestDB Open Source, or use
[storage policies](/docs/concepts/storage-policy/) in QuestDB Enterprise to
move older partitions to object storage, where they stay queryable as part
of the same table.

The same technique works on market data: [Find significant price moves with SDT](/docs/cookbook/sql/finance/significant-price-moves/)
keeps the turning points of each FX pair to within a tolerance in pips.

:::info Related documentation
- [SUBSAMPLE and SDT](/docs/query/sql/subsample/#sdt---swinging-door-trending)
- [Find significant price moves with SDT](/docs/cookbook/sql/finance/significant-price-moves/)
- [sdt() window function](/docs/query/functions/window-functions/reference/#sdt)
- [geo_distance_meters()](/docs/query/functions/spatial/#geo_distance_meters)
- [Views](/docs/concepts/views/)
- [TTL](/docs/concepts/ttl/)
- [Parquet](/docs/concepts/parquet/)
:::
