You get the sys_id by calling the getUniqueValue() method on the GlideRecord object after a successful query. The most common mistake is trying to access the field directly as a property, which returns undefined because the record data is not loaded into memory until you fetch it.
This approach works for any table in ServiceNow, whether you are looking up a single user or a specific change request. You do not need to know the internal structure of the database table; the framework handles the mapping between your code and the stored data. Below is the exact pattern you should use to retrieve this identifier reliably.
The Correct Code Pattern
To retrieve a sys_id, you must first create a GlideRecord instance for the target table. Then, add a query filter to narrow down the results to the single record you want. Finally, call query() to execute the search against the database. If the query returns at least one row, you can immediately access the sys_id using the built-in method designed for this purpose.
Here is the standard script structure:
var gr = new GlideRecord('incident');
gr.addQuery('number', 'INC0010010');
gr.query();
if (gr.next()) {
var mySysId = gr.getUniqueValue();
gs.info('Found sys_id: ' + mySysId);
}
The next() method moves the cursor to the first matching record. Without this step, the object exists but contains no data from the database. The getUniqueValue() method specifically targets the sys_id field, regardless of what other fields you might have queried. This is safer than guessing the column name or relying on position-based indexing.
Why Direct Access Fails
Many developers try to write code like gr.sys_id before calling next(). This will always return null or undefined. The GlideRecord object is a container that holds metadata about the query, not the actual row data. The database does not send the row content until you explicitly ask for it with next(). Always verify that next() returns true before attempting to read any field values.
Handling Multiple Results
Sometimes your query might match more than one record. In these cases, you need to loop through all matches to collect their sys_ids. The while loop combined with next() is the standard way to process multiple rows efficiently.
Use this pattern when you expect a list rather than a single item:
var gr = new GlideRecord('sys_user');
gr.addQuery('active', true);
gr.query();
while (gr.next()) {
var userId = gr.getUniqueValue();
// Process each ID here
}
This approach ensures you do not miss any records. It is particularly useful for background jobs or bulk processing tasks where you need to map external identifiers to internal ServiceNow IDs. Remember that getUniqueValue() works inside the loop just as well as outside it, provided the cursor is positioned on a valid record.
Performance Considerations
Retrieving a sys_id is generally fast, but how you write the query affects performance significantly. Avoid querying large tables without specific filters. If you search the entire sys_user table without a query, the system must scan millions of rows. Always include an indexed field in your addQuery() call.
The number field in tables like Incident or Problem is indexed and provides quick lookups. User names or email addresses may also be indexed depending on your instance configuration. If you are unsure if a field is indexed, check the table schema in the Application Navigator. Queries on non-indexed fields can cause timeouts or slow down the application for other users.
Also, consider using getValue() instead of getUniqueValue() only if you have a specific reason. The latter is optimized for the primary key and is slightly faster. For all other fields, use getValue() with the exact column name. Mixing these methods incorrectly can lead to unexpected null results.
Common Errors and Debugging
If you receive a “No Query Specified” error, it means you called query() without adding any conditions. ServiceNow requires at least one query clause to prevent accidental full-table scans. Add a dummy query like gr.addEncodedQuery('1=1') if you truly need all records, though this is rarely necessary for getting a single sys_id.
Another frequent issue is the “Invalid Table Name” error. Ensure you are using the correct table API name. For example, use ‘cmdb_ci_server’ for servers, not ‘server’. You can find the correct API name by hovering over the table link in the Application Navigator or checking the list view URL.
If the sys_id comes back empty, double-check that your query actually matched a record. Use gs.info(gr.getRowCount()) after the query to see how many rows were returned. If it is zero, your filter criteria are too strict or the data does not exist yet. Adjust your query parameters accordingly.
Using the ID Elsewhere
Once you have the sys_id string, you can use it to reference the record in other parts of your script. You can create a new GlideRecord for a different table and set a reference field to this ID. This is common when linking related records, such as assigning a specific incident to a change request.
You can also pass the sys_id to UI scripts or client-side code via AJAX. This allows you to update the user interface dynamically based on the specific record selected. Always validate the sys_id format before passing it externally. A valid sys_id is a thirty-two character hexadecimal string. If it is shorter or longer, something went wrong during retrieval.
For debugging purposes, you can construct a direct URL to the record using the sys_id. Append the ID to the table’s list view URL. This opens the record form in the browser, allowing you to visually verify that the ID corresponds to the correct data. This manual check is invaluable when automated scripts behave unexpectedly.