Most developers instinctively call next() when checking if records exist, which forces ServiceNow to hydrate the entire GlideRecord object with field data you'll never use. The hasNext() method only checks if results exist without loading field values, making it significantly faster for existence checks. The real trap is forgetting setLimit(1) β without it, ServiceNow still prepares the entire result set even though you only care about existence.
When to use this pattern
- Business Rules that need to validate related record existence before processing
- Script Includes performing duplicate detection or conflict checking
- Scheduled Jobs that need to skip processing when prerequisite records don't exist
- Fix Scripts checking data integrity before bulk operations
When NOT to use this pattern
- Don't use in Client Scripts β use GlideAjax with a Script Include instead
- Don't use when you need a count β use
GlideAggregatewithaddAggregate('COUNT') - Don't use inside a loop over another GlideRecord β you'll create N+1 query performance problems
- Don't use when you actually need field values β just use
next()and process the data
Key behaviors and gotchas
- Always call
setLimit(1)β without it, the database still processes the full result set hasNext()respects ACLs and will returnfalseif records exist but the user can't read them- State values in queries must be integers:
addQuery('state', '1')notaddQuery('state', 'New') - Query performance depends heavily on indexed fields β always include indexed fields in your
addQuery()conditions - Domain separation affects results β records in different domains may not be visible
Never call next() after hasNext() in the same query execution. Once hasNext() returns true, calling next() will advance to the second record, not the first. You'd need to re-query to access the actual matching record.
Enjoying this? Get one deep-dive per week.
Join 1,000+ ServiceNow pros β scripts, GlideRecord patterns, Flow Designer techniques, and career moves. Free.