Logistics

Logistics Case Study and SQL Recipe Book

Logistics is a complex ecosystem involving the coordination of transport, warehouse operations, inventory, and delivery execution. Integrating telematics into logistics processes allows companies to collect real-time data on vehicles, drivers, routes, and cargo conditions, which significantly improves decision-making and operational efficiency.

Navixy IoT Query, with its robust data ingestion and time-series analytics capabilities, supports the digital transformation of logistics operations by enabling deep visibility into each lifecycle stage. Its robust telematics ingestion capabilities, provides comprehensive visibility into these operations. Real-time GPS data, sensor data diagnostics, geofencing, and sensor analytics allow logistics operators to digitize workflows, automate controls, and make informed decisions.

Lifecycle Phase
Goals
Covered Use Cases / Recipes

Route management

Optimize vehicle routing, ensure efficient dispatching, and reduce delays

Trip Counts per Day Mileage Count per Vehicle per Day (Last 7 Days)

Cargo Monitoring

Ensure proper transport conditions for sensitive goods

Temperature (and Humidity) Violation Events in the Last 7 Days

Vehicle Operation

Track fleet utilization, ensure maintenance, and reduce downtime

Engine Hours Summary per Vehicle / Driver / Day (Last 7 Days) Vehicle Downtime Analysis Asset Tracking Without Movement

Route Security & Safety

Detect misuse, unauthorized activity, and safety violations

Route Deviation Detection- Unauthorized Stops (Last 24 Hours) Off-Hour Usage Detection

Compliance Management

Monitor driver behavior, enforce policies and operational compliance

Engine Hours Summary per Vehicle / Driver / Day (Last 7 Days) Off-Hour Usage Detection

Post-Delivery Analysis

Evaluate operational efficiency and historical performance

Vehicle Event Log Report Mileage Count per Vehicle per Day (Last 7 Days) Trip Counts per Day Asset Tracking Without Movement

Asset Tracking Without Movement

This case identifies assets (e.g., vehicles or trailers) that have not changed their GPS compare the minimum and maximum coordinates during the period. If both values fall within a very narrow range (a tolerance threshold, e.g., ±0.01 degrees), we flag the asset as non-moving. The query also joins with the objects and vehicles tables in raw_business_data to retrieve meaningful asset labels for the result output.

WITH gps_bounds AS (
    SELECT
        td.device_id,
        MIN(td.latitude) AS min_lat,
        MAX(td.latitude) AS max_lat,
        MIN(td.longitude) AS min_lon,
        MAX(td.longitude) AS max_lon,
        COUNT(*) AS location_records
    FROM raw_telematics_data.tracking_data_core td
    WHERE td.device_time >= now() - interval '48 hours'
    GROUP BY td.device_id
),
stationary_devices AS (
    SELECT
        device_id
    FROM gps_bounds
    WHERE location_records > 10 -- exclude devices with very sparse data
	AND((max_lat - min_lat) <= 2000 -- ~10 meters
		OR
      	(max_lon - min_lon) <= 1000  -- ~10 meters
    		)
SELECT
    v.vehicle_id,
    v.vehicle_label,
    o.object_id,
    o.object_label,
    sd.device_id,
    gb.min_lat / 1e7 AS latitude,
    gb.min_lon / 1e7 AS longitude,
    gb.location_records
FROM stationary_devices sd
JOIN gps_bounds gb ON sd.device_id = gb.device_id
JOIN raw_business_data.objects o ON o.device_id = sd.device_id
LEFT JOIN raw_business_data.vehicles v ON v.object_id = o.object_id
ORDER BY gb.location_records DESC;

Vehicle Downtime Analysis

This case focuses on analyzing how long vehicles are non-operational due to maintenance, breakdowns, or inactivity. Downtime metrics are crucial for logistics operations to monitor fleet health, reduce idle time, and improve overall utilization and scheduling efficiency.

The core of the downtime analysis lies in leveraging the vehicle_service_tasks table from raw_business_data, which logs both planned and unplanned maintenance events. Each task contains a start_date and an end_date, representing the downtime period. By filtering for completed service tasks, we can compute the exact duration each vehicle was out of operation.

The query calculates total downtime per vehicle by summing up the durations of all its service tasks (in hours). It also allows breakdown by planned vs unplanned maintenance by using the is_unplanned flag. To make the results more actionable, it joins with the vehicles table to include vehicle labels, registration numbers, and model information.

Route Deviation Detection

This case identifies instances where vehicles deviate from their assigned or expected routes — particularly geofenced zones or delivery corridors. Tracking such deviations helps in ensuring route compliance, reducing delays, detecting risky driving behavior, and maintaining delivery SLAs.

This logic compares the vehicle’s actual GPS positions from tracking_data_core (in the raw_telematics_data schema) against predefined geographic zones from the zones table in raw_business_data. These zones represent assigned routes or route segments. Using geometric comparisons via ST_DWithin, we determine whether a point is inside or outside the buffered route area.

The query joins each GPS position with every known route zone using a spatial CROSS JOIN, then applies ST_DWithin() to check if the vehicle was within the permitted corridor. We isolate the rows where the vehicle was outside all geofenced routes and flag them as deviations. The final output lists these deviations, including the device, timestamp, vehicle label, and how far the point was from the nearest zone center.

Engine Hours Summary per Vehicle / Driver / Day (Last 7 Days)

This case measures how long engines were active for each vehicle on a daily basis, allowing fleet managers to track utilization, identify overuse or underuse, and correlate activity with driver assignments. When tied to drivers, it also supports labor hour validation and performance analysis.

The states table in raw_telematics_data records time-series engine state indicators, typically with a state_name like 'ignition' and a value of 1 (on) or 0 (off). To calculate engine hours, we find all timestamped transitions for each device and compute durations where the engine was on (1).

To tie engine activity to both vehicles and drivers, we use the objects, vehicles, and driver_history tables from raw_business_data. We associate each state record to the current driver on that object (via driver assignment history) and to the corresponding vehicle. We then group the data by day, vehicle, and driver, summing total active engine time (in hours).

Temperature (and Humidity) Violation Events in the Last 7 Days

This case identifies sensor readings — such as temperature or humidity — that exceed critical thresholds during transport. Monitoring such violations is vital for industries transporting perishable goods (e.g., food, pharmaceuticals) to ensure compliance with cold chain requirements and to prevent spoilage.

This query extracts sensor input data from the inputs table in the raw_telematics_data schema. Each row represents a sensor reading (e.g., temperature, humidity) recorded at a specific timestamp by a device. We filter these records to include only those from the last 7 days.

The main filtering logic is based on sensor name patterns and a comparison of their numeric values against thresholds (e.g., >25°C for temperature, >80% for humidity). Because value is stored as text, we cast it to numeric before applying the threshold conditions. To enrich the results, we join with the objects table to retrieve vehicle or asset labels, which improves interpretability for fleet managers.

Unauthorized Stops (Last 24 Hours)

This case identifies unauthorized or unplanned stops made by vehicles within the past 24 hours. It helps in detecting potential violations of delivery routes, unauthorized breaks, or idle time that may affect fuel efficiency and SLA performance.

The query analyzes location points with low or zero speed using the The query uses the tracking_data_core table from raw_telematics_data to extract time-series location data and speed. A stop is detected when speed drops below 3 km/h for a duration of more than 2 minutes. Using LAG and LEAD functions, the query segments these low-speed periods to determine stop start and end timestamps.

To detect unauthorized stops, it filters out locations that fall within known geofenced zones (zones table) using PostGIS's ST_DWithin. Only stops outside of any zone buffer are reported. The result includes vehicle ID, object label, registration, timestamps, duration, and coordinates for each stop.

Off-Hour Usage Detection

This case identifies instances where vehicles are operated outside normal business hours — defined here as Monday through Friday, 09:00–18:00. Such detections are essential for flagging unauthorized use, identifying potential vehicle misuse, and improving asset security.

The logic is built on the tracking_data_core table from raw_telematics_data, which logs timestamped GPS events per device. We derive local day of week and hour of use from each device_time entry and filter for records outside the defined business window (i.e., before 9 AM, after 6 PM, or any time on weekends).

To provide clarity, we enrich the GPS data with object and vehicle metadata from raw_business_data (e.g., vehicle label, registration, object ID). For more meaningful summaries, we optionally aggregate the usage to count how many off-hour events occurred per vehicle and when they happened. This can help in identifying patterns or repeat offenders.

Trip counts per day

This case measures how many trips each vehicle completes daily and how far they travel, helping logistics teams assess vehicle usage, optimize routes, and detect anomalies like incomplete trips or unreported usage.

To define a trip, we use a change in vehicle movement state — i.e., transition from stopped to moving and back to stopped. Using the speed values from the tracking_data_core table, the query segments the data based on these transitions. A trip is identified as a continuous movement period where the speed stays above a threshold (e.g., >5 km/h).

Each trip includes:

  • A start timestamp and location (first moving point)

  • An end timestamp and location (last moving point before stopping)

  • The Haversine distance between start and end locations

We calculate the trip count and total distance per day per vehicle, optionally enriched with vehicle labels from the vehicles table.

Mileage Count per Vehicle per Day (Last 7 Days)

This case calculates the daily mileage (in kilometers) for each vehicle over the last 7 days. It is fundamental for tracking vehicle utilization, monitoring fuel efficiency, planning maintenance, and detecting underuse or overuse.

We extract all GPS records from tracking_data_core for the past 7 days. Each GPS point has a timestamp, latitude, and longitude. For each vehicle and each day, we:

  1. Sort GPS points chronologically per device.

  2. Calculate distance between consecutive points using the Haversine formula.

  3. Sum the distances per day per device to get total mileage.

This approach provides high accuracy without relying on external odometer sensors. Optionally, the query joins with objects and vehicles to enrich results with asset metadata.

Vehicle Event Log Report

This case provides a comprehensive report of all vehicle-related events (e.g., ignition, door open, harsh braking, etc.) across the fleet. It includes event type, timestamp, and vehicle context, allowing operations teams to audit behavior, track abnormal activity, or drive alerts and analytics.

The primary source is the states table from the raw_telematics_data schema. Each row includes: device_id (source of the event), device_time (timestamp), state_name (event label), and value (status or measurement).

To create a usable report:

  1. We extract all records from the last 7 days.

  2. Group them by event type, vehicle, and date to provide a count of how often each event occurred and when it occurred.

  3. Enrich the results with vehicle metadata (vehicle_label, registration_number, object_label) via objects and vehicles.

This gives a daily event timeline across the fleet - essential for diagnostics, behavioral analysis, and proactive maintenance.

Last updated

Was this helpful?