Querying with GlideQuery
Posted on 16 Nov 2022 · 1 min read
I've been using GlideRecord for the past nine years. The time has come to move on and experiment with GlideQuery. This post will show you how to run a query using GlideQuery.
The goal
Return all incident numbers with a high priority (P1).
With GlideRecord
var gr = new GlideRecord('incident');
gr.addQuery('priority', 1);
gr.query();
while (gr.next()) {
gs.info(gr.number);
}
This works, but it's verbose and imperative — you're telling the platform how to do it rather than what you want.
With GlideQuery
What I like about GlideQuery is that it reads more like SQL. If I wanted to express the same query in SQL it would look like this:
SELECT number
FROM incident
WHERE priority = 1
Here is the equivalent in GlideQuery:
new GlideQuery('incident')
.where('priority', 1)
.select('number')
.forEach(function(incident) {
gs.info(incident.number);
});
Why GlideQuery is better
- Readable — the intent is clear at a glance
- Chainable — conditions and projections are composed fluently
- Safer — it avoids some of the common GlideRecord pitfalls (like forgetting
.query()) - SQL-like — if you know SQL, the mental model transfers immediately
GlideQuery is available from the Orlando release onwards. If you're still writing GlideRecord for every query, it's worth making the switch.