Smart Statistics · SQL practical tutorial
SQL Overlapping Bookings: Find Equipment Conflicts Before Dispatch
A booking register can look tidy while promising the same machine to two customers. A daily total will not reveal the clash: the problem is whether two occupied time intervals intersect for the same physical resource.
This tutorial builds a small, repeatable conflict check for an equipment hire business. You will distinguish a genuine overlap from a valid handover, return each pair once and give the dispatch team a useful exception queue.
Illustrative example · Dispatch review
One resource needs attention
Source: booking register → confirmed reservations → conflict pairs → dispatch owner. Cancelled reservations are excluded. Pair counts are not counts of unique bookings.
Define what “occupied” means first
Use an identifier for a particular machine, not its model name. Two different excavators can legitimately be hired at the same time. Treat each interval as start included, end excluded: 09:00–12:00 and 12:00–13:00 do not clash.
If the machine needs cleaning, charging or transport, agree whether those activities extend its occupied interval. Add that time before checking conflicts. Do not silently change the comparison to count touching endpoints as a substitute for a real turnaround rule.
Run the complete worked example
Open a new query in your test connection and run the whole batch below together. The declared table exists only within the batch. Its primary key identifies a booking; required dates and the check rule reject empty or reversed intervals.
Microsoft documents datetime2 as a date/time type without a time-zone offset. The UTC meaning here is our data convention, not a property enforced by that type. [1]
-- Run the complete batch in a test SQL Server or Azure SQL Database session.
-- All dates and bookings below are illustrative; timestamps represent UTC.
DECLARE @Bookings TABLE (
BookingID int PRIMARY KEY,
ResourceID varchar(20) NOT NULL,
StartsAt datetime2(0) NOT NULL,
EndsAt datetime2(0) NOT NULL,
BookingStatus varchar(12) NOT NULL,
CHECK (EndsAt > StartsAt)
);
INSERT INTO @Bookings
(BookingID, ResourceID, StartsAt, EndsAt, BookingStatus)
VALUES
(1, 'EX-01', '2026-11-16T09:00:00', '2026-11-16T11:00:00', 'Confirmed'),
(2, 'EX-01', '2026-11-16T10:00:00', '2026-11-16T12:00:00', 'Confirmed'),
(3, 'EX-01', '2026-11-16T12:00:00', '2026-11-16T13:00:00', 'Confirmed'),
(4, 'EX-01', '2026-11-16T09:30:00', '2026-11-16T10:30:00', 'Cancelled'),
(5, 'GEN-02', '2026-11-16T10:00:00', '2026-11-16T12:00:00', 'Confirmed'),
(6, 'EX-01', '2026-11-16T09:15:00', '2026-11-16T09:45:00', 'Confirmed');
WITH ActiveBookings AS (
SELECT BookingID, ResourceID, StartsAt, EndsAt
FROM @Bookings
WHERE BookingStatus = 'Confirmed'
), Conflicts AS (
SELECT
a.ResourceID,
a.BookingID AS BookingA,
b.BookingID AS BookingB,
CASE WHEN a.StartsAt > b.StartsAt
THEN a.StartsAt ELSE b.StartsAt END AS OverlapStart,
CASE WHEN a.EndsAt < b.EndsAt
THEN a.EndsAt ELSE b.EndsAt END AS OverlapEnd
FROM ActiveBookings AS a
INNER JOIN ActiveBookings AS b
ON a.ResourceID = b.ResourceID
AND a.BookingID < b.BookingID
AND a.StartsAt < b.EndsAt
AND b.StartsAt < a.EndsAt
)
SELECT
ResourceID,
BookingA,
BookingB,
OverlapStart,
OverlapEnd,
DATEDIFF(minute, OverlapStart, OverlapEnd) AS OverlapMinutes
FROM Conflicts
ORDER BY ResourceID, BookingA, BookingB;
Why these four join conditions matter
ResourceID matches the same physical unit. a.BookingID < b.BookingID removes self-matches and mirrored pairs. The two strict time comparisons mean each interval starts before the other ends. Together they catch partial overlaps, identical intervals and complete containment.
Testing only whether one start falls inside the other booking can miss an enclosing reservation. Comparing only adjacent rows can also miss a long booking that overlaps several later ones.
Prove the answer before connecting live data
The sample must return exactly these two rows. All values below are an Illustrative example; times are UTC on 16 November 2026.
| Resource | Pair | Overlap | Minutes |
|---|---|---|---|
| EX-01 | 1 + 2 | 10:00–11:00 | 60 |
| EX-01 | 1 + 6 | 09:15–09:45 | 30 |
Booking 3 touches booking 2 but does not overlap it. Booking 4 is cancelled. Booking 5 uses a different resource. Booking 6 is fully inside booking 1, which proves that containment is detected.
Identical intervals
In a separate test, give two distinct IDs the same resource, start and end. Expect one pair, never two mirrored results.
Cross-midnight work
Test a booking ending on the following date. Preserve full timestamps; comparing clock times alone would break the result.
Invalid intervals
Try equal start/end, a reversed interval and a null endpoint separately. The sample must reject each rather than report it as clear.
Keep the result honest
Detection is not prevention. Two users can both see an available machine and submit overlapping reservations. A reporting query cannot guarantee booking exclusivity. Ask the application/database owner to design and test transactional controls if the system must block those writes.
Pairwise minutes are not lost capacity. Three simultaneous bookings produce three pairs. Their overlap minutes can count the same clock period repeatedly. Report conflict pairs, distinct affected bookings and distinct affected resources separately; do not label their sum as downtime or financial loss.
Precision changes interpretation. DATEDIFF counts date-part boundaries. With minute-aligned sample data it gives the displayed durations; with seconds present it is not an exact elapsed-minute calculation. Choose the required precision deliberately. [2]
Turn the query into a controlled dispatch check
- Map and validate the source. Confirm stable booking and resource IDs, a shared timestamp convention and the status values that reserve capacity. Quarantine missing dates and invalid intervals before running the conflict query; otherwise an empty result can disguise bad data.
- Choose the review window. To review a period, select bookings with StartsAt before the window end and EndsAt after the window start. Filtering only on StartsAt can omit an earlier booking that is still occupying the resource. Apply the window to both sides of the comparison.
- Make performance measurable. Start with a limited operational horizon. Ask the database owner to inspect the execution plan and test an index beginning with ResourceID and StartsAt, with relevant end/status/ID columns available. Treat that as a candidate to measure, not a universal fix; dense overlaps can legitimately generate many pairs.
- Assign decisions. Give each pair an owner, review state and resolution note. The dispatch supervisor decides whether to move a booking, substitute equipment or confirm an approved exception. Record the action in the booking system, then rerun the check.
- Pilot with dispatch. Run alongside the existing process, compare a sample with the booking diary and log false positives and missed conflicts. Train colleagues on the exclusive-end rule and show the data extraction time so an old result is not mistaken for current availability.
Measure time from detection to resolution, unresolved conflicts before dispatch and repeat causes such as missing turnaround time. An exception report earns its place when it changes a booking decision. It does not establish a savings claim on its own.
Is the check ready for an operational pilot?
Tick evidence you can demonstrate. This assessment stays in the page and sends no data.
Frequently asked questions
Do bookings that touch at the end time conflict?
Not under this tutorial’s rule. A booking ending at 12:00 and another starting at 12:00 can coexist. Include turnaround time in the occupied interval if immediate reuse is not realistic.
Does this query prevent double booking?
No. It detects conflicts in the data it reads. Preventing concurrent reservations requires a separate transactional design in the booking system.
Can I sum overlap minutes as total lost capacity?
Not safely. Several conflicting pairs can cover the same minutes. Pairwise overlap measures require further interval consolidation before they can describe unique affected time.
Can I use local UK timestamps?
Only with an explicit time policy. Local clock times can be ambiguous around daylight-saving changes. This example assumes the stored timestamps have already been normalised to UTC.
Make booking exceptions actionable
Smart Statistics can help turn SQL checks into a dependable operations report, with clear definitions, useful exceptions and accountable follow-through.