IMD SolutionComputing LibraryShop main store

How-to

Get the last N stored records from an Ignition tag history query

Edge computing and IIoT Published 9 min read

Short answer

A positive returnSize in system.tag.queryTagHistory splits the window into that many time buckets and aggregates each one, so it never yields the newest N stored events. Query raw history with no fixed return size and noInterpolation=True over a bounded window ending at a fixed cutoff, count rows, and step back through earlier windows until you reach N.

On this page
  1. Why does returnSize=5 return five time buckets instead of the five newest records?
  2. How do you request raw history without aggregation?
  3. How do you step back through windows until you have N records?
  4. How large should the first query window be?
  5. Should you read the historian's partitioned SQL tables directly?
  6. Why can a healthy change-only tag return fewer than N records?
  7. How do you get the last N records for several tags?
  8. Questions asked

You want the newest N stored samples from a change-only tag, and the obvious shortcut does not work: setting a fixed return size of N in system.tag.queryTagHistory fixes the number of output rows, not the number of stored events, because the query slices the range into N equal time intervals and reduces each interval with an aggregation mode. The method that works is a raw query with no fixed return size and noInterpolation=True over a bounded window ending at a fixed cutoff, counting returned rows and stepping back through earlier windows until the count reaches N. The historian resolves its month-partitioned storage along the way, which direct SQL cannot easily do.

Why does returnSize=5 return five time buckets instead of the five newest records? #

A positive returnSize fixes the number of output rows, not the number of stored events: the query divides the requested range into that many equal time intervals and reduces the samples inside each interval to a single value with an aggregation mode. That is the documented behavior: the function reference for Ignition 7.9 and 8.1 explains that the aggregation mode applies whenever the data is denser than the request, and that this is the normal situation with fixed return sizes, because a real tag almost always stores more samples than the row count you asked for. The reference does not state a default aggregation mode, so never build on a guess about which one runs; if you want bucketed output for a trend, pass the mode explicitly.

Run the arithmetic on the classic case, a five-row request over the last eight hours: 8 hours x 60 = 480 minutes, and 480 / 5 = 96 minutes per bucket. Each of the five rows is one aggregation of everything stored inside its 96-minute slice, and the row's timestamp is the slice boundary, not the time the tag changed.

What you observe What it tells you
Five rows across an 8-hour range from returnSize=5 Five 96-minute buckets, one aggregated value each
Float values from an integer tag An aggregation produced the value; a stored sample keeps the tag's data type
noInterpolation=True but timestamps still evenly spaced Interpolation control does not cancel fixed-size aggregation
Fewer stored events than buckets in the range Some buckets hold one sample or none, and the rows still do not mark change times

noInterpolation=True is worth keeping, but for a different reason: it stops the historian from inventing values between stored samples. It does nothing about the bucketing, which is why an integer tag can still come back as floats. The same aggregation machinery breaks trend queries in other ways, and fixing unequal paths and aggregates in Ignition historian queries covers that failure.

How do you request raw history without aggregation? #

Leave the fixed return size out and keep noInterpolation=True: without it the query hands back the stored samples themselves at their original timestamps, which is exactly what an event list needs. The date arguments go where the function page for your installed release documents them, since 7.9 and 8.1 describe the same function with their own argument lists.

# Illustrative inputs - declared here, not API names:
tagPaths = ["Packaging/CaseCounter"]   # list[str]: one history-enabled tag path
nNeeded = 50                            # int: stored records the list must show
windowDays = 4                          # int: width of each query window
cutoff = system.date.now()              # the fixed end time, held for every window

windowStart = system.date.addDays(cutoff, -windowDays)
rawData = system.tag.queryTagHistory(tagPaths, windowStart, cutoff, noInterpolation=True)
# rawData holds the stored samples inside [windowStart, cutoff]

Prove the call is raw before trusting it, because this is the step that fails silently:

  1. Compare the returned timestamps with the change times you see when you browse the tag's history: they must match one for one and be irregularly spaced.
  2. Check the data type: an integer tag must still return integers; floats mean an aggregation is still running.
  3. Widen the window and query again: the row count must grow with the actual number of stored events, not stay pinned at a fixed number of rows.

Hold the cutoff for the whole retrieval. Every window you fetch later ends where the previous one started, so a list assembled from several queries still describes one consistent moment in time.

How do you step back through windows until you have N records? #

Fix the cutoff time once, query the newest window, count its rows, and while the count is below N subtract another window of the same width and accumulate, stopping when N is reached or the retention boundary ends the search. The loop, once the raw query is confirmed:

  1. Record N and the cutoff time before any data is fetched; the cutoff never moves during the retrieval.
  2. Query the raw window from cutoff minus windowDays to cutoff and count its stored rows; if the first timestamp precedes the window start, treat it as a range anchor and leave it out of the count.
  3. If the count is at least N, sort the rows newest first and keep the newest N; you are done.
  4. If the count is below N, set the next window to end where this one started, query it, and add its rows to the accumulation.
  5. Repeat step 4 until the accumulated count reaches N.
  6. Stop early if windows come back empty all the way to the retention boundary: the accumulated rows are then the complete history and the list is simply shorter than N. Where that boundary sits is decided by setting historian pruning and retention for Ignition tag history.

One wide query and several backward queries are both valid; the backward loop is preferable because the common case then moves the least data, and the rare sparse tag costs one or two extra queries instead of making every retrieval wide.

How large should the first query window be? #

Size the first window to hold about twice the expected number of events: divide N by the tag's observed events per day, double the result, and round up, so one query usually suffices and the step-back loop stays the exception. Worked example with the numbers from the code above, on a counter tag that has averaged 25 stored events per day:

  • Expected span for N = 50: 50 / 25 = 2 days.
  • Doubled for headroom: 2 x 2 = 4 days, so windowDays = 4.
  • The raw query over the four days ending at the cutoff returns 71 rows. 71 is at least 50, so the list is the newest 50 of those 71, fetched in one query.

Now the same tag during a week when the machine idled, storing closer to 8 events per day:

  • First four-day window: 21 rows. 21 is below 50, so step back.
  • Second four-day window: 24 rows. 21 + 24 = 45. Still short.
  • Third four-day window: 23 rows. 45 + 23 = 68, which is at least 50. Keep the newest 50 of the 68 accumulated rows.

Three queries instead of one is the cost of a stale rate estimate, and the loop absorbs it without ever returning an aggregated row. If a tag's rate is unknown, start with one day, read the count, and size the next window from the measured rate.

Should you read the historian's partitioned SQL tables directly? #

No: the history tables are partitioned by month, so direct SQL has to work out which partition holds the newest rows and stitch across month boundaries, while the history query resolves the partitions for you and returns the same stored events. A last-N retrieval is the worst case for direct SQL, because the answer usually lives in the newest partition but can straddle the boundary at the start of a month, and the partition layout is an implementation detail of the storage mode rather than a contract you can build on. In flat-file storage there are no SQL tables to query at all, which is one more reason to stay on the query interface; using flat files as the Ignition tag historian back end describes that mode.

Reserve direct SQL for cases that genuinely need database-level rows, such as an external report joining history against business tables, and then read the storage mode's documentation for the partition scheme rather than inferring it from one month's table names. For the display side, the raw window query is the supported path and returns identical events.

Why can a healthy change-only tag return fewer than N records? #

Change-based recording stores a sample only when the value moves, so a tag that has sat stable for two days contributes one row or none no matter how the query is written, and a short list can be the correct answer. Before blaming the query, separate the cases:

  • The live tag is valid and unchanged: the sparse result is correct; extend the window or accept the shorter list.
  • The live tag changes but no row appears: history is not being stored for that change, so work the storage path — history enabled on the tag, the selected history provider, deadband and history filtering — the failure mode why an Ignition historian logs memory tags but not OPC tag changes walks through.
  • The live tag is stale or bad quality: fix acquisition first; the historian can only store what the gateway actually receives.

A deadband also means small changes never become rows, so recorded on change really means recorded on a change large enough to pass the filter. If operators need a stable value to reappear periodically, the tag's history configuration carries a max time between records setting that forces a heartbeat sample; setting it changes future collection only, cannot create past rows, grows storage volume, and turns the list from pure change events into changes plus heartbeats. Set it deliberately, not by accident.

How do you get the last N records for several tags? #

Decide first whether N counts per tag or across all tags: for a per-tag list run one raw query per tag with its own count and stop condition, and for one merged event sequence query all paths together and sort the combined rows by timestamp. The subtlety is what a record is in a multi-path dataset: one row carries a value for every requested tag, but the tags changed at different times, so a row is not one stored event.

  • Per-tag last N, an event list per device: run the step-back loop once per tag; each count and stop condition is independent, and one quiet tag does not shorten another tag's list.
  • Combined last N events across tags: query all paths in one raw call, split the result into per-tag timestamp-and-value pairs, sort the merged list newest first, and keep N.
  • A wide table for a report rather than an event list: the row-per-timestamp layout is fine, but do not call its row count a number of events.

The sizing rule carries over. Three tags at 25 stored events per day each produce 75 events per day combined, so a combined N = 50 spans about 50 / 75 = 0.67 days; doubled and rounded up, a first window of 2 days covers it. For a last-N event list the decision is per-tag raw queries with the step-back loop; for a trend across a time range, bucketed aggregation is the right tool. Never confuse the two.

Questions asked

How do you sort the raw rows newest first?

The query returns rows in time order, oldest first, so do the ordering in the script: copy each row's timestamp and value into a list of pairs, sort it by timestamp in descending order, and keep the first N entries. Sorting the accumulated rows once, after all windows are fetched, keeps the logic identical whether one query or three were needed.

Does widening the window change rows already returned?

No. Stored samples are fixed rows with fixed timestamps, so a wider raw window only adds older rows to what you already hold; nothing already fetched moves or changes value. Only interpolated or aggregated output depends on the window's shape, which is one more reason the raw mode is the safe choice for an event list.

What if the first returned timestamp is before the window start?

Treat that row as a range anchor, not an in-window event: compare every window's first timestamp with the window start and exclude the anchor from the count. Counting it once per window overcounts by one each time, and after a three-window retrieval your newest-N list would run one row past the true N at the old end.

How do you keep the list updating on an operator display?

Run each refresh as a new bounded retrieval with a new cutoff, and swap the finished list into the display in one update. The fixed cutoff matters only within a single retrieval, where it stops rows from shifting while earlier windows are still being fetched; between refreshes a fresh cutoff is exactly what you want.

Keep reading

  • Troubleshooting

    Query tag history from a remote tag provider

    Yes: Tag Historian is one module with two jobs — storage and retrieval — so the gateway where system.tag.queryTagHistory runs must license it too. Install and license the module on the querying gateway; from 8.1 a read-only license covers a gateway that only consumes history. Prove the fix by matching row counts between the two gateways.

    Edge computing and IIoT

  • Troubleshooting

    Why an Easy Chart pen shows no historian data

    A live tag with an empty Easy Chart pen is a historian write-path fault, not a tag fault. Clear the SQL Server no count option first; if it is already off, remove the trigger or procedure statement that makes the update return a result set, then let the store-and-forward cache drain.

    Edge computing and IIoT

  • Troubleshooting

    Why Ignition tag history records only every 10 seconds

    History that lands only every 10 seconds, dropping peaks shorter than that, is the historical scan class at work: in the case traced here the Default Historical scan class sat at a 10-second interval while 1 second was expected. SQL Express, Windows 7 and the hardware were not involved. Read the interval on the tag's assigned scan class, set it to the rate your data needs, and prove the fix with a brief test peak in a history query.

    Edge computing and IIoT