Build a Support Queue from Status History in SQL

Vladimir Lomtev•
Build a Support Queue from Status History in SQL

To build the support queue for the end of the day from status history, take events up to the report cutoff, select the last event for each ticket, and only then keep the open statuses. For an AI-written query, it is especially important to verify the order of these operations. If you remove closed tickets before selecting the last event, a ticket that had already been closed will appear in the queue again.

This guide is suitable for an analyst or support manager who has an event export. The output will be a list of IDs and history rows that explain why each ticket was included in the report. The example covers one log and one date. Transfers between teams, SLA calculations, and reconstructing history from a current-status export will require additional data.

Contents

Step 1. Set the report cutoff

For the queue as of the end of November 27, 2026, UTC, include events with a time strictly earlier than November 28, 00:00:00 UTC. A close exactly at midnight belongs to the new day. For an open snapshot, there is no lower bound on the status-change date: a ticket opened the day before and still open is included in the queue. For a report by local time, first determine midnight in the team’s time zone and convert that cutoff to UTC.

Separately choose which data version to use to build the queue:

What you need to get Event time Storage ingestion time
Repeat of the report generated shortly after midnight Before November 28, 00:00 UTC Before November 28, 00:15 UTC
Refined report after the morning backfill Up to the same midnight Up to November 28, 08:00 UTC

The second cutoff is needed if the source delivers events with a delay. It changes which rows are available, while the queue in both cases refers to the same point in time. For an exact repeat, you need a saved data snapshot or an immutable ingestion history with sufficient precision. If the load overwrites rows, the previous report state may not be available from a single current export.

Step 2. Prepare the events

Each row needs the ticket ID, the status after the change, the event time, and the ingestion time. To resolve ties in time, the example includes a fifth field source_seq — a unique event number within the ticket. The source guarantees that when event times are equal, the larger value means a later change. Load order, a random UUID, and the CSV row number do not provide that guarantee on their own.

In the training log, open and pending are included in the queue, closed is excluded from it. Align this list with the report owner. If the code for “waiting on customer” is excluded from your shift load, change the list explicitly and record the rule next to the report.

Copy the block into events.sql. It creates ten fictional events across five tickets. For brevity, time is written as text in a single UTC format with second-level precision. Sorting and comparison here rely on the same format for all values and both boundaries. For exports with different offsets or precision, normalize the timestamps first while preserving the source precision. SQLite documentation on time values.

CREATE TABLE ticket_events (
    ticket_id   TEXT NOT NULL,
    source_seq  INTEGER NOT NULL,
    status      TEXT NOT NULL,
    occurred_at TEXT NOT NULL,
    ingested_at TEXT NOT NULL,
    PRIMARY KEY (ticket_id, source_seq)
);

INSERT INTO ticket_events VALUES
  ('A', 1, 'open',    '2026-11-26 16:00:00', '2026-11-26 16:01:00'),
  ('A', 2, 'closed',  '2026-11-28 00:00:00', '2026-11-28 00:00:00'),
  ('B', 1, 'open',    '2026-11-27 19:00:00', '2026-11-27 19:01:00'),
  ('B', 2, 'closed',  '2026-11-27 21:00:00', '2026-11-27 21:01:00'),
  ('B', 3, 'open',    '2026-11-27 21:00:00', '2026-11-27 21:02:00'),
  ('C', 1, 'pending', '2026-11-27 18:00:00', '2026-11-27 18:01:00'),
  ('C', 2, 'closed',  '2026-11-27 23:55:00', '2026-11-28 00:20:00'),
  ('D', 1, 'open',    '2026-11-27 20:00:00', '2026-11-28 00:12:00'),
  ('D', 2, 'closed',  '2026-11-27 22:00:00', '2026-11-27 22:01:00'),
  ('E', 1, 'open',    '2026-11-28 00:05:00', '2026-11-28 00:06:00');

Step 3. Reconstruct the status at the report cutoff

Save the query in queue.sql. Inside WITH both cutoffs are applied. PARTITION BY ticket_id gives separate numbering for each ticket. ROW_NUMBER() assigns number 1 to the last known row in event-time order and source-number order. The outer query keeps that row and checks its status. Its ORDER BY is responsible for the convenient output order of IDs. SQLite on ROW_NUMBER, SQLite on WITH.

WITH ranked AS (
    SELECT ticket_id, source_seq, status, occurred_at, ingested_at,
           ROW_NUMBER() OVER (
               PARTITION BY ticket_id
               ORDER BY occurred_at DESC, source_seq DESC
           ) AS rn
    FROM ticket_events
    WHERE occurred_at < :event_cutoff
      AND ingested_at < :ingestion_cutoff
)
SELECT ticket_id, source_seq, status, occurred_at, ingested_at
FROM ranked
WHERE rn = 1 AND status IN ('open', 'pending')
ORDER BY ticket_id;

A simple MAX(occurred_at) shows the time, but it can leave two rows when joining back by time. For ticket B, the close and reopen are recorded in the same second. Selecting event No. 3 is reproducible thanks to the source rule. If the order is unknown, flag that ID for review. Without this rule, the query cannot determine which change was the last one. SQLite on sorting, PostgreSQL on row order when window keys tie.

Step 4. Reconcile IDs and history rows

Save the code in check_queue.py alongside the two SQL files. Run python3 check_queue.py from this directory. Python creates an in-memory SQLite database, loads the training data, and passes the boundaries as named parameters. After execution, the console will show the IDs, the selected event number, and the status. Python documentation on sqlite3 parameters.

from pathlib import Path
import sqlite3

with sqlite3.connect(":memory:") as db:
    db.executescript(Path("events.sql").read_text(encoding="utf-8"))
    query = Path("queue.sql").read_text(encoding="utf-8")
    for cutoff in ("2026-11-28 00:15:00", "2026-11-28 08:00:00"):
        rows = db.execute(query, {
            "event_cutoff": "2026-11-28 00:00:00",
            "ingestion_cutoff": cutoff,
        }).fetchall()
        print(cutoff, [row[:3] for row in rows])

On November 28, 2026, we ran these three blocks locally in Python 3.14.3 with SQLite 3.50.4. The first query returned A, B, C, the second — A, B. The test was run on ten training rows. The live support system and the answers from a specific AI model were not included in this run.

ID Version at 00:15 UTC Version at 08:00 UTC What the row verifies
A No. 1, open No. 1, open The older open state is counted. Midnight close is beyond the cutoff.
B No. 3, open No. 3, open When times match, the reopen was selected.
C No. 1, pending Not in the queue The close happened at 23:55 and was ingested at 00:20.
D Not in the queue Not in queue The first opening occurred after the closing, but took place before it.
E Not in queue Not in queue The first event occurred after the report cutoff.

Cross-check the list and event number for each ID. For example, if the query returns D instead of B, the queue size will remain the same, even though the list will be wrong. For a control check, you can temporarily remove the status condition from the outer filter and see the selected closing for D in both versions and for C in the second one. E has no row before the cutoff at all.

Step 5. Define the rule for the AI query

Provide the model with the table schema, queue statuses, both cutoffs, and the ordering guarantees from your export documentation. For the query, sample rows are enough. A short task prompt could look like this:

Build a list of open tickets at the end of the day in SQLite. Before numbering, apply two strict cutoffs on occurred_at and ingested_at. Within each ticket_id, choose one row by occurred_at DESC and source_seq DESC. After selection, keep open and pending. Return ticket_id, source_seq, status, occurred_at, and ingested_at. For the sample data, I expect A1, B3, C1 with an ingestion cutoff at 00:15 and A1, B3 at 08:00.

This text is an example task for the model. The verified query above is written for a sample schema. When porting it, start with one completed day: open the history for several disputed IDs and compare the event order manually. If the log starts recently or misses ticket creation, you need an opening snapshot with the remaining queue. If the report is needed for a specific team, you will need assignment history and a team-selection rule for the same date.

If the final totals in SQL-based reports don't match, it helps to check joins and denominators separately. FAQ on totals and average ticket size in AI reports. If the assistant is just being introduced into support, start with clear roles and ticket rules. AI service desk guide.

How the studio helps with support reporting

Vladimir Lomtev's AI studio helps break down the reporting process, prepare the source data, and test the prototype on an agreed slice. For the first conversation, it is enough to describe where the status history is stored, what hour the shift closes, and which tickets should remain in the queue. This section describes the publisher's services for the material. Discuss the project.

Conclusion

For the queue at a given moment, save the event boundary and the data ingestion cutoff. Select one last event per ticket and check the status of that row. Along with the counter, store the list of IDs and the markers of the selected events. These let you explain which tickets changed the queue after late loading and why.

Request an audit

Share your contact details and we will follow up.

← All articles

Comments (0)

Loading comments…

Leave a comment
No registration required

Book a strategy call
for agentic operations

Tell us which workflow you want to improve. We will map feasibility, risks, and the fastest MVP path.

By submitting, you agree to our privacy policy

Contacts

Global Operations

Serving U.S. clients remotely
with private cloud and on-prem options

Strategy calls by request

We respond after reviewing your workflow context.

info@agentsunrise.pro

For partnership inquiries

Have a proposal?

Write to us in messengers

© 2026 AgentSunrise