GlideQuery is a server-side API that wraps GlideRecord and lets you build a query as one chain of calls: where to filter, select or selectOne to read, and insert, update or updateMultiple to write. It checks field names before running, returns plain JavaScript objects, and throws readable errors instead of failing quietly.
What GlideQuery is and where it fits
GlideQuery sits on top of GlideRecord and covers the same ground: server-side scripts that read and change records. Its design rests on three ideas: fail fast, use native JavaScript, and stay expressive.
The fail-fast idea targets a familiar bug. With GlideRecord, an addQuery call that names a misspelled field can lead the script to return far more records than intended. GlideQuery checks the fields you reference before it runs. If a field such as priority or opened_at does not exist on the table, you get an error with a readable stack trace, not a silent wrong result.
The native JavaScript idea shows up in the results. Rows come back as plain objects holding the fields you asked for, and the primary key (usually sys_id) is included even when you do not request it. You are not holding a GlideRecord cursor that you advance with next().
One scoping detail matters in scoped applications. GlideQuery is a global-scope script include, so inside a scoped app you write new global.GlideQuery('sys_user'). The same prefix applies to Stream and Optional, the two companion types you will meet in the next sections. The GlideQuery script include requires the GlideQuery plugin, com.sn_glidequery.
Reading rows with where, select and forEach
The basic read has three parts: a table name, one or more filters, and the fields to return.
new GlideQuery('task')
.where('priority', 1)
.select('short_description', 'opened_at')
.forEach(function (t) {
gs.info(t.short_description + ' opened ' + t.opened_at);
});
where plays the part of addQuery, but it returns a new GlideQuery object, which is why calls chain. select returns a Stream, a sequence type with methods that resemble a JavaScript Array. forEach replaces the while (gr.next()) loop.
Reading one record with selectOne and Optional
When you expect a single row, use selectOne. It does not return a record. It returns an Optional, and it returns one whether or not a row matched. An empty Optional means nothing matched.
var user = new GlideQuery('sys_user')
.where('user_name', 'abel.tuter')
.selectOne('name', 'email')
.orElse({ name: 'unknown' });
The Optional offers three calls in practice:
| Call | Behaviour |
|---|---|
orElse(default) |
Returns your default object when no record was found |
get() |
Returns the record, and throws an error if there is none |
isPresent() |
Returns true or false |
Use selectOne for single-row lookups or to test whether a record exists. When several records may match, use select instead.
Because a lookup returns an Optional rather than a bare null, the script has to say what happens when nothing is found: supply a default, or call get() and accept the thrown error.
Building filters with OR, nulls and grouping
Plain where calls give you AND logic. For OR, GlideQuery provides orWhere, and it has two siblings, orWhereNull and orWhereNotNull. Null checks have their own methods, whereNull and whereNotNull.
var numBigCompanies = new GlideQuery('core_company')
.whereNotNull('parent')
.orWhere('num_employees', '>', 5000)
.count();
Two rules keep these chains valid. The first orWhere has to follow a where, whereNull or whereNotNull. And no where clause can come after an orWhere. A chain such as where('priority', 1).orWhere('urgency', 1).where('escalation', 3) is ambiguous and throws an error.
Grouping has to be stated explicitly, so the chain does not depend on which precedence rule a reader assumes.
You state it by passing a nested GlideQuery into where or orWhere. The nested query behaves like a set of parentheses.
// (priority = 1 OR urgency = 1) AND escalation = 3
new GlideQuery('task')
.where(new GlideQuery()
.where('priority', 1)
.orWhere('urgency', 1))
.where('escalation', 3)
See also encoded queries. A nested GlideQuery created without a table name runs against the parent’s table. A query can also be stored in a variable and passed into another query’s where, which lets you reuse a filter across scripts.
Dotwalking and field flags
Dotwalking works in both select and where.
In a select, dotwalked values arrive as nested objects. Pairing the select with whereNotNull on the reference field means each row you read has a reference to follow.
new GlideQuery('sys_user')
.whereNotNull('company')
.select('name', 'company.city')
.forEach(function (user) {
gs.info(user.name + ' works in ' + user.company.city);
});
Flags are the second feature here. Adding a dollar sign and a flag name to a field name returns metadata in place of the raw value. DISPLAY returns the display value, the equivalent of getDisplayValue. Three further flags cover currency code, currency display value and currency string, and each one applies to currency fields. Because the flag lives in the field name, you can select a raw value and its flagged version in one call.
Writing records safely
GlideQuery writes are checked as well as reads. On insert and update, the API verifies that the fields exist on the table, that the values match the field types, and that a choice field receives an allowed choice. Passing an unknown field, such as name on the task table, throws an error that lists the known fields.
var created = new GlideQuery('task')
.insert({ priority: 1, description: 'Please help!' })
.get();
insert returns an Optional, so get() reads back the new record including its sys_id. Business rules run on the inserted record unless you skip them with disableWorkflow, which is covered further down.
For a single-record change, update needs a where clause that picks out one record, such as one matched on sys_id. It returns an Optional holding the updated record.
updateMultiple applies a change to every row matching the where clauses. It returns an object whose rowCount key gives the number of rows it changed. Treat the two update calls differently when you write error handling, because one returns the updated record and the other returns a count.
There is no separate single-record delete. To remove one record, use deleteMultiple with a where on a primary key.
To skip business rules for a query, call disableWorkflow() before the rest of the chain, for instance ahead of an updateMultiple on users matching an email. Because it bypasses the rules attached to the table, use it deliberately, and note that it only works on tables in the global scope.
Aggregates, grouping and having
For a total row count, count() returns a JavaScript number.
sum, avg, max and min return an Optional, which is empty when no rows match. That lets a script tell no rows apart from a total of zero.
var profits = new GlideQuery('core_company').sum('profits').orElse(0);
sum and avg only accept numeric fields. These simple aggregates work on one field with one function and do not group.
When you need grouping or several aggregations, use aggregate and groupBy. Both return a new GlideQuery, so you can stack several of each. The Stream from select holds one item per group, with a group object and the aggregate values.
having filters the groups. This example keeps countries with a positive total market cap.
new GlideQuery('core_company')
.aggregate('sum', 'market_cap')
.groupBy('country')
.having('sum', 'market_cap', '>', 0)
.select()
Filtering groups in JavaScript remains an option for conditions that having does not express.
Streams: map, filter, limit and laziness
A Stream carries intermediate methods, which return another Stream, and terminal methods, which end the chain. map, filter and limit are intermediate. forEach, find and reduce are terminal. select and selectOne on a GlideQuery are terminal, while where and orderBy are intermediate.
Intermediate methods are lazy. Nothing runs, and the database is not queried, until a terminal method completes the chain. If a script seems to do nothing, check that the chain ends with a terminal call.
Two performance points follow. For better performance, put conditions in where rather than a Stream filter whenever the condition fits. See slow queries and indexing. And call GlideQuery’s own limit before select, since it limits inside the SQL query, whereas the Stream version is less efficient.
For reducing a Stream to one value, reduce takes a reducer function and an initial value. For a count, max, min, average or sum on one field, use the built-in aggregate methods instead. flatMap expects a function that returns a Stream and flattens the result, which suits nested queries but can produce the N+1 query problem, one query per parent row. chunk batches a Stream into arrays; paired with the IN operator it cuts the number of nested queries, because each batch of IDs runs as one child query instead of one query per parent row.
Frequently asked questions
What does GlideQuery return when I call select?
A Stream of plain JavaScript objects holding the requested fields, with the primary key included. You process it with methods such as forEach and map.
How do I get one record, and what if none matches?
Call selectOne. It returns an Optional. Use orElse for a default, isPresent to test, or get, which throws when the Optional is empty.
Why does my OR query throw an error?
The first orWhere must follow a where, whereNull or whereNotNull, and no where can follow an orWhere. Group mixed AND and OR logic by passing a nested GlideQuery.
How do I use GlideQuery inside a scoped application?
Add the global. prefix, as in new global.GlideQuery('sys_user'). The same prefix applies to Stream and Optional.
How do I skip business rules?
Call disableWorkflow() at the start of the chain before the query or update.