# 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.
:::

### 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.

## 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.

:::info Related documentation
- [SUBSAMPLE and SDT](/docs/query/sql/subsample/#sdt---swinging-door-trending)
- [sdt() window function](/docs/query/functions/window-functions/reference/#sdt)
- [Views](/docs/concepts/views/)
- [TTL](/docs/concepts/ttl/)
- [Parquet](/docs/concepts/parquet/)
:::
