GlideRecord - Scoped

Scoped GlideRecord is used for database operations.

A GlideRecord contains both records and fields. For information about GlideRecordSecure, which is a class inherited from GlideRecord that performs the same functions as GlideRecord, and also enforces ACLs, see the GlideRecordSecure documentation.

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

You can set the glide.invalid_query.returns_no_rows system property to true to have queries with invalid encoded queries return no records.

Scoped GlideRecord - addActiveQuery()

Adds a filter to return active records.

Table 1. Parameters
Name Type Description
None
Table 2. Returns
Type Description
QueryCondition Filter to return active records
var inc = new GlideRecord('incident');
inc.addActiveQuery();
inc.query();

Scoped GlideRecord - addEncodedQuery(String query)

Adds an encoded query to other queries that may have been set.

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

You can set the glide.invalid_query.returns_no_rows system property to true to have queries with invalid encoded queries return no records.

Table 3. Parameters
Name Type Description
query String An encoded query string.
Table 4. Returns
Type Description
void
var queryString = "priority=1^ORpriority=2";
var gr = new GlideRecord('incident');
gr.addEncodedQuery(queryString);
gr.query();
while (gr.next()) {
  gs.addInfoMessage(gr.number);
}

Output:

Scoped GlideRecord - addJoinQuery(String joinTable, Object primaryField, Object joinTableField)

Adds a filter to return records based on a relationship in a related table.

You can use this method to find all the users that are in the database group via the [sys_user_grmember] table, or to find all problems that have an assigned incident via the incident.problem_id relationship.

This is not a true database join; rather, addJoinQuery adds a subquery. So, while the result set is limited based on the join, the only fields that you have access to are those on the base table (those which are in the table with which the GlideRecord was initialized).

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

You can set the glide.invalid_query.returns_no_rows system property to true to have queries with invalid encoded queries return no records.

Table 5. Parameters
Name Type Description
joinTable String Table name
primaryField Object (Optional) If other than sys_id, the primary field
joinTableField Object (Optional) If other than sys_id, the field that joins the tables.
Table 6. Returns
Type Description
GlideQueryCondition A filter that lists records where the relationships match.

Find problems that have an incident attached. This example returns problems that have associated incidents. However, it won't pull values from the incidents that are returned as a part of the query.

var prob = new GlideRecord('problem');
prob.addJoinQuery('incident');
prob.query();

Output:

Find inactive problems with associated incidents

// Look for Problem records that have associated Incident records
var gr = new GlideRecord('problem');
var grSQ = gr.addJoinQuery('incident');
 
// Where the Problem records are "active=false"
gr.addQuery('active', 'false');
 
// And the Incident records are "active=true"
grSQ.addCondition('active', 'true');
 
// Query
gr.query();
 
// Iterate and output results
while (gr.next()) {
    gs.info(gr.getValue('number'));
}

Find problems that have incidents associated where the incident caller_id field value matches that of the problem opened_by field.

var gr = new GlideRecord('problem'); 
gr.addJoinQuery('incident', 'opened_by', 'caller_id'); 
gr.query();

Scoped GlideRecord - addNotNullQuery(String fieldName)

A filter that specifies records where the value of the field passed in the parameter is not null.

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

You can set the glide.invalid_query.returns_no_rows system property to true to have queries with invalid encoded queries return no records.

Table 7. Parameters
Name Type Description
fieldName String The name of the field to be checked.
Table 8. Returns
Type Description
GlideQueryCondition A filter that specifies records where the value of the field passed in the parameter is not null.
var target = new GlideRecord('incident'); 
target.addNotNullQuery('short_description');
target.query();   // Issue the query to the database to get all records where short_description is not null
while (target.next()) {   
     // add code here to process the incident record
}

Scoped GlideRecord - addNullQuery(String fieldName)

Adds a filter to return records where the value of the specified field is null.

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

You can set the glide.invalid_query.returns_no_rows system property to true to have queries with invalid encoded queries return no records.

Table 9. Parameters
Name Type Description
fieldName String The name of the field to be checked.
Table 10. Returns
Type Description
GlideQueryCondition The query condition added to the GlideRecord.
var target = new GlideRecord('incident'); 
target.addNullQuery('short_description');
target.query();   // Issue the query to the database to get all records where short_description is null
while (target.next()) {   
   // add code here to process the incident record
}

Scoped GlideRecord - addQuery(String query)

Adds a filter to return records using an encoded query string.

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

You can set the glide.invalid_query.returns_no_rows system property to true to have queries with invalid encoded queries return no records.

Table 11. Parameters
Name Type Description
query String An encoded query string.
Table 12. Returns
Type Description
GlideQueryCondition The query condition added to the GlideRecord.
var rec = new GlideRecord('incident');
rec.addQuery('active=true');
rec.query();
while (rec.next()) { 
  rec.active = false;
  gs.info('Active incident ' + rec.number + ' closed');
  rec.update();
}

Output:

Scoped GlideRecord - addQuery(String name, Object value)

Provides the ability to build a request, which when executed, returns the rows from the specified table, that match the request.

If you are familiar with SQL, this method is similar to the "where" clause. One or more addQuery() calls can be made in a single query; in this case the queries are AND'ed. If any of the query statements need to be OR'ed, use the GlideQueryCondition method Scoped GlideQueryCondition - addOrCondition(String name, String oper, Object value).

When addQuery() is called with only two parameters, table field and comparison value, such as myObj.addQuery('category','Hardware');, the operator in this case is assumed to be "equal to".

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

You can set the glide.invalid_query.returns_no_rows system property to true to have queries with invalid encoded queries return no records.

Table 13. Parameters
Name Type Description
name String Table field name.
value Object Value on which to query (not case-sensitive).
Table 14. Returns
Type Description
GlideQueryCondition The query condition added to the GlideRecord.
var rec = new GlideRecord('incident');
rec.addQuery('active', true);
rec.query();
while (rec.next()) { 
  rec.active = false;
  gs.info('Active incident ' + rec.number + ' closed');
  rec.update();
}

Output:

Scoped GlideRecord - addQuery(String name, String operator, Object value)

Provides the ability to build a request, which when executed, returns the rows from the specified table, that match the request.

If you are familiar with SQL, this method is similar to the "where" clause. One or more addQuery() calls can be made in a single query; in this case the queries are AND'ed. If any of the query statements need to be OR'ed, use the GlideQueryCondition method addOrCondition().

Always test queries on a sub-production instance prior to deploying them on a production instance. An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

You can set the glide.invalid_query.returns_no_rows system property to true to have queries with invalid encoded queries return no records.

Table 15. Parameters
Name Type Description
name String Table field name.
operator String Query operator. The available values are dependent on the data type of the value parameter.
Numbers:
  • =
  • !=
  • >
  • >=
  • <
  • <=
Strings (must be in upper case):
  • =
  • !=
  • IN
  • NOT IN
  • STARTSWITH
  • ENDSWITH
  • CONTAINS
  • DOES NOT CONTAIN
  • INSTANCEOF
value Object Value on which to query (not case-sensitive).
Table 16. Returns
Type Description
GlideQueryCondition The query condition that was added to the GlideRecord.
var rec = new GlideRecord('incident');
rec.addQuery('active',true);
rec.addQuery('sys_created_on', ">", "2010-01-19 04:05:00");
rec.query();
while (rec.next()) { 
  rec.active = false;
  gs.info('Active incident ' + rec.number + ' closed');
  rec.update();
}

Output:

Using the IN operator.

var gr = new GlideRecord('incident');
gr.addQuery('number','IN','INC00001,INC00002');
gr.query();
while(gr.next()) {
  //do something....
}

Output:

Scoped GlideRecord - canCreate()

Determines if the Access Control Rules, which include the user's roles, permit inserting new records in this table.

Table 17. Parameters
Name Type Description
None
Table 18. Returns
Type Description
Boolean True if the user's roles permit creation of new records in this table.
var gr = new GlideRecord('incident');
gs.info(gr.canCreate());

Output:

Scoped GlideRecord - canDelete()

Determines if the Access Control Rules, which include the user's roles, permit deleting records in this table.

Table 19. Parameters
Name Type Description
None
Table 20. Returns
Type Description
Boolean True if the user's roles permit deletions of records in this table.
var att = new GlideRecord('sys_attachment');
gs.info(att.canDelete());

Output:

Scoped GlideRecord - canRead()

Determines if the Access Control Rules, which include the user's roles, permit reading records in this table.

Table 21. Parameters
Name Type Description
None
Table 22. Returns
Type Description
Boolean True if the user's roles permit reading records from this table.
var gr = new GlideRecord('incident');
gs.info(gr.canRead());

Output:

Scoped GlideRecord - canWrite()

Determines if the Access Control Rules, which include the user's roles, permit editing records in this table.

Table 23. Parameters
Name Type Description
None
Table 24. Returns
Type Description
Boolean True if the user's roles permit writing to records from this table.
var gr = new GlideRecord('incident');
gs.info(gr.canWrite());

Output:

Scoped GlideRecord - chooseWindow(Number firstRow, Number lastRow, Boolean forceCount)

Sets a range of rows to be returned by subsequent queries.

Table 25. Parameters
Name Type Description
firstRow Number The first row to include.
lastRow Number The last row to include.
forceCount Boolean If true, the getRowCount() method will return all possible records.
Table 26. Returns
Type Description
void
var gr = new GlideRecord('incident');
gr.orderBy('number');
gr.chooseWindow(2, 4);
gr.query();
if (gr.next()) { 
  gs.info(gr.number + ' is within window');
}

Output:

Scoped GlideRecord - deleteMultiple()

Deletes multiple records that satisfy the query condition.

This method does not delete attachments.

Do not use deleteMultiple() on tables with currency fields. Always delete each record individually. Also, do not use this method with the chooseWindow() or setLimit() methods when working with large tables.

Table 27. Parameters
Name Type Description
None
Table 28. Returns
Type Description
void
var gr = new GlideRecord('incident')
gr.addQuery('active','false'); //to delete all inactive incidents
gr.deleteMultiple();

Output:

Scoped GlideRecord - deleteRecord()

Deletes the current record.

Table 29. Parameters
Name Type Description
None
Table 30. Returns
Type Description
Boolean True if the record was deleted; false if no record was found to delete.
var gr = new GlideRecord('incident')
gr.addQuery('sys_id','99ebb4156fa831005be8883e6b3ee4b9'); //to delete one record
gr.query();
gr.next();
gr.deleteRecord();

Output:

Scoped GlideRecord - get(Object name, Object value)

Defines a GlideRecord based on the specified expression of 'name = value'.

This method is expected to be used to query for single records, so a 'next' operation on the recordset is performed by this method before returning.

Table 31. Parameters
Name Type Description
name Object Column name
value Object Value to match. If value is not specified, then the expression used is 'sys_id = name'.
Table 32. Returns
Type Description
Boolean True if one or more matching records was found. False if no matches found.
var gr = new GlideRecord('incident');
gr.get('99ebb4156fa831005be8883e6b3ee4b9');
gs.info(gr.number);

Output:

Scoped GlideRecord - getAttribute(String fieldName)

Returns the dictionary attributes for the specified field.

Table 33. Parameters
Name Type Description
fieldName String Field name for which to return the dictionary attributes
Table 34. Returns
Type Description
String Dictionary attributes

doit();
function doit() {
  var gr = new GlideRecord('sys_user');
  gr.query("user_name","admin");
  if (gr.next()) {
    gs.print("we got one");
    gs.print(gr.location.getAttribute("tree_picker"));
  }
}

Scoped GlideRecord - getClassDisplayValue()

Returns the table's label.

Table 35. Parameters
Name Type Description
None
Table 36. Returns
Type Description
String Table's label

Scoped GlideRecord - getDisplayValue()

Retrieves the display value for the current record.

Table 37. Parameters
Name Type Description
None
Table 38. Returns
Type Description
String The display value for the current record.
var gr =new GlideRecord('incident')
gr.query('sys_id','ef43c6d40a0a0b5700c77f9bf387afe3');
gr.next();
gs.info(gr.getDisplayValue());

Output:

Scoped GlideRecord - getED()

Returns the element's descriptor.

Table 39. Parameters
Name Type Description
None
Table 40. Returns
Type Description
GlideElementDescriptor Element's descriptor

var totalCritical  = 0;
var filledCritical = 0;
var fields         = current.getFields();
 
gs.print(fields);
 
for (var num = 0; num < fields.size(); num++) {
 
	gs.print("RUNNING ARRAY VALUE " + num);
 
	var ed = fields.get(num).getED();
 
	if(ed.hasAttribute("tiaa_critical")) {
		gs.print("CRITICAL FIELD FOUND");
		totalCritical ++;
 
		if (!fields.get(num).isNil()) {
			filledCritical ++;
		}
	}
 
}
 
var answer = 0;
gs.print("TOTAL - " + totalCritical);
gs.print("FILLED - " + filledCritical);
 
if (filledCritical > 0 && totalCritical > 0) {
 
	var pcnt = (filledCritical/totalCritical)*100;
	answer = pcnt.toFixed(2);;
 
}
 
answer;

Scoped GlideRecord - getElement(String columnName)

Retrieves the GlideElement object for the specified field.

Table 41. Parameters
Name Type Description
columnName String Name of the column to get the element from.
Table 42. Returns
Type Description
GlideElement The GlideElement for the specified column of the current record.
var elementName = 'short_description'; 
var gr = new GlideRecord('incident'); 
gr.initialize(); 
gr.setValue(elementName, "My DB is not working");
gr.insert();
gs.info(gr.getElement('short_description'));

Output:

Scoped GlideRecord - getEncodedQuery()

Retrieves the query condition of the current result set as an encoded query string.

Table 43. Parameters
Name Type Description
None
Table 44. Returns
Type Description
String The encoded query as a string.
var gr = new GlideRecord('incident'); 
gr.addQuery('active', true);
gr.addQuery('priority', 1); 
gr.query(); 
var encodedQuery = gr.getEncodedQuery(); 
gs.info(encodedQuery);

Output: active=true^priority=1

Scoped GlideRecord - getLabel()

Returns the field's label.

Table 45. Parameters
Name Type Description
None
Table 46. Returns
Type Description
String Field's label

template.print("Summary of Requested items:\n");  
var gr = new GlideRecord("sc_req_item");
gr.addQuery("request", current.sysapproval);
gr.query();
while(gr.next()) {
    var nicePrice = gr.price.toString();
    if (nicePrice != '') {
        nicePrice = parseFloat(nicePrice);
        nicePrice = nicePrice.toFixed(2);
    }
    template.print(gr.number + ":  " + gr.quantity + " X " + gr.cat_item.getDisplayValue() 
                     + " at $" + nicePrice + " each \n");
    template.print("    Options:\n");
    for (key in gr.variables) {
      var v = gr.variables[key];
      if(v.getGlideObject().getQuestion().getLabel() != '') {
         template.space(4);
         template.print('     ' +  v.getGlideObject().getQuestion().getLabel() + " = " 
                     + v.getDisplayValue() + "\n");  
      }
    }
}

Scoped GlideRecord - getLastErrorMessage()

Retrieves the last error message. If there is no last error message, null is returned.

Table 47. Parameters
Name Type Description
None
Table 48. Returns
Type Description
String The last error message as a string.
// Setup a data policy where short_description field in incident is mandatory
var gr = new GlideRecord('incident');
gr.insert(); // insert without data in mandatory field
var errormessage = gr.getLastErrorMessage(); 
gs.info(errormessage);

Output: Data Policy Exception: Short description is mandatory

Scoped GlideRecord - getRecordClassName()

Retrieves the class name for the current record.

Table 51. Parameters
Name Type Description
None
Table 52. Returns
Type Description
String The class name.
var gr = new GlideRecord('incident'); 
var recordClassName = gr.getRecordClassName(); 
gs.info(recordClassName);

Output: incident

Scoped GlideRecord - getRowCount()

Retrieves the number of rows in the query result.

Table 53. Parameters
Name Type Description
None
Table 54. Returns
Type Description
Number The number of rows.
var gr = new GlideRecord('incident')
gr.query();
gs.info("Records in incident table: " + gr.getRowCount());

Output:

Scoped GlideRecord - getTableName()

Retrieves the name of the table associated with the GlideRecord.

Table 55. Parameters
Name Type Description
None
Table 56. Returns
Type Description
String The table name
var gr = new GlideRecord('incident');
gs.info(gr.getTableName());

Output:

Scoped GlideRecord - getUniqueValue()

Gets the primary key of the record, which is usually the sys_id unless otherwise specified.

Table 57. Parameters
Name Type Description
None
Table 58. Returns
Type Description
String The unique primary key as a String, or null if the key is null.
var gr = new GlideRecord('kb_knowledge');
gr.query();
gr.next();
var uniqueid = gr.getUniqueValue();
gs.info(uniqueid);

Output:

Scoped GlideRecord - getValue(String name)

Retrieves the string value of an underlying element in a field.

Table 59. Parameters
Name Type Description
name String The name of the field to get the value from.
Table 60. Returns
Type Description
String The value of the field.
var gr = new GlideRecord('incident'); 
gr.orderBy('number');
gr.query('active','true'); 
gr.next() ; 
gs.info(gr.getValue('number'));

Output:

Scoped GlideRecord - GlideRecord(String tableName)

Creates an instance of the GlideRecord class for the specified table.

Table 61. Parameters
Name Type Description
tableName String The table to be used.
var gr = new GlideRecord('incident');

Scoped GlideRecord - hasNext()

Determines if there are any more records in the GlideRecord object.

Table 62. Parameters
Name Type Description
None
Table 63. Returns
Type Description
Boolean True if there are more records in the query result set.
var rec = new GlideRecord('incident'); 
rec.query(); 
if (rec.hasNext()) { 
  gs.info("Table is not empty"); 
}

Output:

Scoped GlideRecord - insert()

Inserts a new record using the field values that have been set for the current record.

Table 64. Parameters
Name Type Description
None
Table 65. Returns
Type Description
String Unique ID of the inserted record, or null if the record is not inserted.
var gr = new GlideRecord('incident');
gr.initialize(); 
gr.name = 'New Incident'; 
gr.description = 'Incident description'; 
gr.insert();

Output:

Scoped GlideRecord - initialize()

Creates an empty record suitable for population before an insert.

Table 66. Parameters
Name Type Description
None
Table 67. Returns
Type Description
void
var gr = new GlideRecord('incident');
gr.initialize(); 
gr.name='New Incident'; 
gr.description='Incident description'; 
gr.insert();

Output:

Scoped GlideRecord - isActionAborted()

Checks to see if the current database action is to be aborted.

Table 68. Parameters
Name Type Description
None
Table 69. Returns
Type Description
Boolean True if the current database action is to be aborted
var gr = new GlideRecord('incident');
 
gs.info(gr.isActionAborted());

Output:

false

Scoped GlideRecord - isNewRecord()

Checks if the current record is a new record that has not yet been inserted into the database.

Table 70. Parameters
Name Type Description
None
Table 71. Returns
Type Description
Boolean True if the record is new and has not been inserted into the database.
var gr = new GlideRecord("x_app_table"); 
gr.newRecord(); // create a new record and populate it with default values
gs.info(gr.isNewRecord());

Output:

Scoped GlideRecord - isValid()

Determines if the table exists.

Table 72. Parameters
Name Type Description
None
Table 73. Returns
Type Description
Boolean True if table is valid or if record was successfully retrieved. False if table is invalid or record was not successfully retrieved.
var gr = new GlideRecord('incident');
gs.info(gr.isValid());
 
var anotherGr = new GlideRecord('wrong_table_name');
gs.info(anotherGr.isValid());

Output: true false

Scoped GlideRecord - isValidField(String columnName)

Determines if the specified field is defined in the current table.

Table 74. Parameters
Name Type Description
columnName String The name of the the field.
Table 75. Returns
Type Description
Boolean True if the field is defined for the current table.
var gr = new GlideRecord('incident'); 
gr.initialize(); 
gs.info(gr.isValidField("short_description"));

Output:

Scoped GlideRecord - isValidRecord()

Determines if current record is a valid record.

Table 76. Parameters
Name Type Description
None
Table 77. Returns
Type Description
Boolean True if the current record is valid. False if past the end of the record set.
var rec = new GlideRecord('incident');
rec.query();
while (rec.next()) { 
  gs.info(rec.number + ' exists');
}
gs.info(rec.isValidRecord());

Output:

Scoped GlideRecord - next()

Moves to the next record in the GlideRecord object.

Table 78. Parameters
Name Type Description
None
Table 79. Returns
Type Description
Boolean True if moving to the next record is successful. False if there are no more records in the result set.
var rec = new GlideRecord('incident');
rec.query();
while (rec.next()) { 
  gs.info(rec.number + ' exists');
}

Output:

Scoped GlideRecord - _next()

Moves to the next record in the GlideRecord. Provides the same functionality as next(), it is intended to be used in cases where the GlideRecord has a column named next.

Table 80. Parameters
Name Type Description
None
Table 81. Returns
Type Description
Boolean True if there are more records in the query set.
var rec = new GlideRecord('sys_template');
rec.query();
while (rec._next()) { 
  gs.print(rec.number + ' exists');
}

Scoped GlideRecord - newRecord()

Creates a new GlideRecord record, sets the default values for the fields, and assigns a unique ID to the record.

Table 82. Parameters
Name Type Description
None
Table 83. Returns
Type Description
void
var gr = new GlideRecord("x_app_table"); 
gr.newRecord(); 
gs.info(gr.isNewRecord());

Output: true

Scoped GlideRecord - operation()

Retrieves the current operation being performed, such as insert, update, or delete.

Table 84. Parameters
Name Type Description
None
Table 85. Returns
Type Description
String The current operation.
//Commonly used in a business rule, returns insert if the current operation is insert
gs.info("current operation " + current.operation());

Output:

Scoped GlideRecord - orderBy(String name)

Specifies an orderBy column.

Call this method more than once to order by multiple columns. Results are arranged in ascending order, see orderByDesc(String name) to arrange records in descending order.

Table 86. Parameters
Name Type Description
name String The column name used to order the records in this GlideRecord object.
Table 87. Returns
Type Description
void
var queryString = "priority=2"; 
var gr = new GlideRecord('incident'); 
gr.orderBy('short_description'); // Ascending Order
gr.addEncodedQuery(queryString); 
gr.query(); 
while (gr.next()) { 
    gs.info(gr.short_description); 
}

Output:

Scoped GlideRecord - orderByDesc(String name)

Specifies a decending orderBy column.

Table 88. Parameters
Name Type Description
name String The column name to be used to order the records in a GlideRecord object.
Table 89. Returns
Type Description
void
var queryString = "priority=2"; 
var gr = new GlideRecord('incident'); 
gr.orderByDesc('short_description'); //Descending Order
gr.addEncodedQuery(queryString); 
gr.query(); 
while (gr.next()) { 
    gs.info(gr.short_description); 
}

Output:

Scoped GlideRecord - query(Object field, Object value)

Runs the query against the table based on the filters specified by addQuery, addEncodedQuery, etc.

This queries the GlideRecord table as well as any references of the table. Usually this is performed without arguments. If name/value pair is specified, "name=value" condition is added to the query.

Table 90. Parameters
Name Type Description
field Object The column name to query on.
value Object The value to query for.
Table 91. Returns
Type Description
void
var rec = new GlideRecord('incident');
rec.query();
while (rec.next()) { 
  gs.info(rec.number + ' exists');
}

Output:

Scoped GlideRecord - _query(Object field, Object value)

Identical to query(). This method is intended to be used on tables where there is a column named query, which would interfere with using the query() method.

Runs the query against the table based on the filters specified by the addQuery() and addEncodedQuery() methods. This method queries the GlideRecord table as well as any references of the table. Typically this method is called without arguments. If a name/value pair is specified, the "name=value" condition is added to the query.

Table 92. Parameters
Name Type Description
name Object Column name on which to query
value Object Value for which to query
Table 93. Returns
Type Description
void

var rec = new GlideRecord('sys_app_module');
rec._query();
while (rec.next()) { 
 gs.print(rec.number + ' exists');
}

Scoped GlideRecord - setAbortAction(Boolean b)

Sets a flag to indicate if the next database action (insert, update, delete) is to be aborted. This is often used in business rules.

Table 94. Parameters
Name Type Description
b Boolean True to abort the next action. False if the action is to be allowed.
Table 95. Returns
Type Description
void
// Often used in business rule to check whether the current operation should be aborted.
if (current.size > 16) {
  current.setAbortAction(true);
}

Output:

Scoped GlideRecord - setLimit(Number maxNumRecords)

Sets the limit for number of records are fetched by the GlideRecord query.

Table 96. Parameters
Name Type Description
maxNumRecords Number The maximum number of records to fetch.
Table 97. Returns
Type Description
void
ar gr = new GlideRecord('incident');
gr.orderByDesc('sys_created_on');
gr.setLimit(10);
gr.query(); // this retrieves latest 10 incident records created

Output:

Scoped GlideRecord - setNewGuidValue(String guid)

Sets sys_id value for the current record.

Table 98. Parameters
Name Type Description
guid String The GUID to be assigned to the current record.
Table 99. Returns
Type Description
void
ar gr = new GlideRecord('incident');
gr.short_description='The third floor printer is broken';
gr.setNewGuidValue('eb4636ca6f6d31005be8883e6b3ee333');
gr.insert();
gs.info(gr.sys_id);

Output:

Scoped GlideRecord - setValue(String name, Object value)

Sets the value of the field with the specified name to the specified value.

Normally the script does a gr.category = value. However, if the element name is itself a variable then gr.setValue(elementName, value) can be used. When setting a value, ensure the data type of the field matches the data type of the value you enter.

Table 100. Parameters
Name Type Description
name String Name of the field.
value Object The value to assign to the field.
Table 101. Returns
Type Description
void
var elementName = 'short_description'; 
var gr = new GlideRecord('incident'); 
gr.initialize(); 
gr.setValue(elementName, "My DB is not working");
gr.insert();

Output:

Scoped GlideRecord - setWorkflow(Boolean enable)

Enables or disables the running of business rules, script engines, and audit.

Table 102. Parameters
Name Type Description
enable Boolean If true (default), enables business rules. If false, disables business rules.
Table 103. Returns
Type Description
void
//Enable business rules, scripts engines for x_app_table
var gr = new GlideRecord("x_app_table"); 
gr.setWorkflow(true);

Output:

Scoped GlideRecord - update(String reason)

Updates the GlideRecord with any changes that have been made. If the record does not already exist, it is inserted.

Table 104. Parameters
Name Type Description
reason (Optional) String The reason for the update. The reason is displayed in the audit record.
Table 105. Returns
Type Description
String Unique ID of the new or updated record. Returns null if the update fails.
var gr = new GlideRecord('incident')
gr.get('99ebb4156fa831005be8883e6b3ee4b9');
gr.short_description='Update the short description';
gr.update();
gs.info(gr.getElement('short_description'));

Output:

Scoped GlideRecord - updateMultiple()

Updates each GlideRecord in the list with any changes that have been made.

When changing field values, use setValue() instead of directly setting the field (field = something). When using updateMultiple(), directly setting the field (gr. state = 4) results in all records in the table being updated instead of just the records returned by the query.

Do not use this method with the chooseWindow() or setLimit() methods when working with large tables.

Table 106. Parameters
Name Type Description
None
Table 107. Returns
Type Description
void
/ update the state of all active incidents to 4 - "Awaiting User Info"
var gr = new GlideRecord('incident')
gr.addQuery('active', true);
gr.query();
gr.setValue('state',  4);
gr.updateMultiple();

Output: