ServiceNow Scripting Scenario Based Interview Questions 2026
How the scripting round usually works: the interviewer asks you to share your screen and write the script live, either in your own PDI (Personal Developer Instance), usually in Scripts - Background, or in a plain notepad or shared document. They watch how you approach the problem as much as the final script, so explain your thinking as you type.
Before the interview: be ready for both. Log in to your PDI an hour early: a PDI goes to sleep when it isn't used, and waking it up can take several minutes you won't have during the call. For a notepad round there is no autocomplete and no way to run the script, so practise writing the common GlideRecord and GlideAggregate patterns from memory.
Best practices interviewers look for:
- Meaningful variable names. Use
incidentGroractiveUsers, notgr. A genericgrcan also clash with other scripts running in the same scope. - Filter in the query, not in the loop. Put every condition in
addQuery(), or copy the filter from a list (right-click the breadcrumb, Copy query) and use oneaddEncodedQuery(). - Never query inside a loop. Dot-walk (
caller_id.email) or collect the sys_ids and query once. - Count with GlideAggregate, not by looping a GlideRecord or calling
getRowCount(). - Use
getValue()andsetValue()instead of reading fields directly, so you work with plain strings, not field objects. - Be careful with bulk updates. Try the query on a few records with
setLimit()first, and decide whether Business Rules and notifications should run (setWorkflow(false)).
New: practise these scripts right here
Each scenario below has a Practice this in the sandbox button. Write your script, run it against realistic practice data and get it checked, with an interviewer's review of how it is written. No PDI needed. Nothing you run touches a real instance, and the data resets on every run.
Rehearse the real round: the Job Switch Kit has timed mock scripting rounds with random scenarios, no hints, PDI or notepad mode, and a score for every script.
Just want to code? Open the ServiceNow Script Editor: pick any question, let it ask you one at random, or try your own scripts in a free sandbox.
📘 Supported APIs and methods Tap to see what you can use in the practice editor
Scripts run as server-side background scripts, written in plain JavaScript the way ServiceNow expects (var, functions, arrays, JSON, Math). Press Ctrl+Space in the editor for suggestions.
GlideRecord also GlideRecordSecure
Query: addQuery, addEncodedQuery, addActiveQuery, addInactiveQuery, addNullQuery, addNotNullQuery, orderBy, orderByDesc, setLimit, getEncodedQuery, query, next, hasNext, get, getRowCount
Read: getValue, getDisplayValue, getUniqueValue, getTableName, getRecordClassName, isValid, isValidRecord, isNewRecord, isValidField, getLimit, getLastErrorMessage
Write: initialize, newRecord, setValue, setDisplayValue, insert, update, updateMultiple, deleteRecord, deleteMultiple, setWorkflow, autoSysFields, setForceUpdate, setUseEngines, setNewGuidValue
Security: canRead, canWrite, canCreate, canDelete
Or conditions: var qc = gr.addQuery(...); qc.addOrCondition(...)
GlideAggregate
addAggregate, getAggregate, groupBy, setGroup, orderByAggregate, addHaving, plus the GlideRecord query methods
Aggregates: COUNT, SUM, MIN, MAX, AVG
Fields gr.field, dot-walking
getValue, getDisplayValue, nil, getName, getLabel, getTableName, getReferenceTable, getRefRecord, setValue, changes, changesTo, changesFrom. Dot-walk references: gr.caller_id.email
gs
Logging: info, warn, error, debug, print, log, addInfoMessage, addErrorMessage
User and system: getUserID, getUserName, getUserDisplayName, hasRole, getProperty, setProperty, getMessage, nil, eventQueue
Dates: now, nowDateTime, nowNoTZ, daysAgo, daysAgoStart, daysAgoEnd, hoursAgo, minutesAgo, monthsAgo, beginningOfToday, endOfToday, beginningOfYesterday, beginningOfThisMonth, beginningOfLast7Days, beginningOfLast30Days, beginningOfThisYear, dateDiff and more
GlideDateTime and GlideDuration
GlideDateTime: getValue, getDisplayValue, setValue, getNumericValue, isValid, addSeconds, add, addDaysUTC / addDaysLocalTime, addWeeksUTC, addMonthsUTC, addYearsUTC, compareTo, before, after, onOrBefore, onOrAfter, equals, getDate, getLocalDate, getYearUTC, getMonthUTC, getDayOfMonthUTC, getDayOfWeekUTC
GlideDuration: getValue, getDisplayValue, getNumericValue, getDayPart, getRoundedDayPart
Query operators
= != < <= > >= IN, NOT IN, LIKE, NOTLIKE, STARTSWITH, ENDSWITH, ISEMPTY, ISNOTEMPTY, ANYTHING, ON, NOTON, and javascript:gs.daysAgoStart(7) style date values in encoded queries
Not available in the practice editor: chooseWindow, addJoinQuery, applyEncodedQuery, getLink, setAbortAction, getElements, gs.getSession, setting a field with field.setDisplayValue() (use gr.setDisplayValue('field', value) instead), Script Includes, GlideAjax and client-side APIs (g_form, g_user).
We can use GlideAggregate API to achieve this scenario:
Script :
gs.print('State\\tIncident Count');
var grIncident=new GlideAggregate('incident');
grIncident.addEncodedQuery(' sys_updated_onONToday@javascript: gs.beginningOfToday()@javascript: gs.endOfToday()');
grIncident.addAggregate('COUNT','state');
grIncident.query();
while(grIncident.next()){
gs.print(grIncident.state. getDisplayValue()+'\t'+grIncident. getAggregate('COUNT','state'));
}
Output :

Note: This scripting question is common. However, they might ask for different table or different field. The primary learning here is whenever there is question related to finding count of the records, we are supposed to use GlideAggregate API. Do not use GlideRecord API with getRowCount method, it is not considered as best practice. Also make sure you understand how addAggregate, getAggregate and groupBy works in GlideAggregate API.
We can use GlideAggregate API to achieve this scenario:
Script :
gs.print('State\\tIncident Count');
var grIncident=new GlideAggregate('incident');
grIncident.addEncodedQuery(' sys_updated_onONToday@javascript: gs.beginningOfToday()@javascript: gs.endOfToday()');
grIncident.addAggregate('COUNT','state');
grIncident.query();
while(grIncident.next()){
gs.print(grIncident.state. getDisplayValue()+'\t'+grIncident. getAggregate('COUNT','state'));
}
Output :

Note: This scripting question is common. However, they might ask for different table or different field. The primary learning here is whenever there is question related to finding count of the records, we are supposed to use GlideAggregate API. Do not use GlideRecord API with getRowCount method, it is not considered as best practice. Also make sure you understand how addAggregate, getAggregate and groupBy works in GlideAggregate API.
Script :

Output :

Note: Many of you must already be knowing how GlideRecord works but here interviewer checks if you know how setLimit, orderBy or orderByDesc can be used for such scenarios.
Script :
Output :
Note: Many of you must already be knowing how GlideRecord works but here interviewer checks if you know how setLimit, orderBy or orderByDesc can be used for such scenarios.
We need to use GlideAggregate as we need to get count of incidents. Since, we need incidents Category and sub cateory wise, we need to apply grouping on 2 fields as shown below :
Script :

Output :

Note: Take away from this scenario is to understand how grouping on multiple fields can be used. Interviewer might change question to include 3-4 grouping fields so you should understand how grouping on multiple fields can be done via GlideAggregate API. Such multiple grouping logic is also quite useful if you want to do analysis on existing data.
We need to use GlideAggregate as we need to get count of incidents. Since, we need incidents Category and sub cateory wise, we need to apply grouping on 2 fields as shown below :
Script :
Output :
Note: Take away from this scenario is to understand how grouping on multiple fields can be used. Interviewer might change question to include 3-4 grouping fields so you should understand how grouping on multiple fields can be done via GlideAggregate API. Such multiple grouping logic is also quite useful if you want to do analysis on existing data.
1. You have to create one script inlcude with two function getIncidentDetails and sendDataToBackgroundScript.
2. getIncidentDetails should fetch first incident resolved today, this function should send Incident number, assignee user, resolved date and created date to sendDatToBackgroundScript function which is in the same script include.
3. sendDataToBackgroundScript function should calculate duration between created date and resolved date and return difference and Incident Number, Assignee User.
4. sendDataToBackgroundScript shoudl be called from background script and all data should be printed.
Background Script :

Script Include :

Output :

Note: Here interviewer tries to test your basic scripting knowledge, like calling script include from another script, sending multiple values from one function to another, finding date difference, basic usage of GlideRecord with setLimit and orderBy method. Interviewer might change scenarios to introduce more ServiceNow API's so prepare yourself with these all basic scripting knowledge.
Background Script :
Script Include :
Output :
Note: Here interviewer tries to test your basic scripting knowledge, like calling script include from another script, sending multiple values from one function to another, finding date difference, basic usage of GlideRecord with setLimit and orderBy method. Interviewer might change scenarios to introduce more ServiceNow API's so prepare yourself with these all basic scripting knowledge.
There are two methods to verify users access for any glide record.
1. Use GlideRecordSecure API while creating security incident. This API implicitly verifies if user passes ACL access on table.
2. Use canRead or canWrite function. These functions implicitly verifies if logged in user satisfies ACL access.
There are two methods to verify users access for any glide record.
1. Use GlideRecordSecure API while creating security incident. This API implicitly verifies if user passes ACL access on table.
2. Use canRead or canWrite function. These functions implicitly verifies if logged in user satisfies ACL access.
Counting means GlideAggregate, but there is a catch: GlideAggregate only returns groups that actually have incidents. To also show groups with 0, query the active groups separately and look up each count, defaulting to 0. That keeps it to two queries however many groups exist.
Script :
// 1. Count active incidents per group in ONE aggregate query
var counts = {};
var incAgg = new GlideAggregate('incident');
incAgg.addActiveQuery();
incAgg.addNotNullQuery('assignment_group');
incAgg.addAggregate('COUNT');
incAgg.groupBy('assignment_group');
incAgg.query();
while (incAgg.next()) {
counts[incAgg.getValue('assignment_group')] = parseInt(incAgg.getAggregate('COUNT'), 10);
}
// 2. Walk every active group and print its count (0 when missing)
var groupGr = new GlideRecord('sys_user_group');
groupGr.addActiveQuery();
groupGr.orderBy('name');
groupGr.query();
while (groupGr.next()) {
gs.info(groupGr.getValue('name') + ': ' + (counts[groupGr.getUniqueValue()] || 0));
}
Note: Interviewers use the "include zero" twist to see whether you understand what GlideAggregate returns. Looping over groups and calling getRowCount() for each one gives the same output but runs one query per group, which is the answer they are hoping you will not give.
Dot-walk to the assignee's user record inside the incident query: assigned_to.active=false. One query finds every affected incident; there is no need to loop over users first.
Script :
var count = 0;
var incidentGr = new GlideRecord('incident');
incidentGr.addEncodedQuery('active=true^assigned_to.active=false');
incidentGr.query();
while (incidentGr.next()) {
incidentGr.setValue('assigned_to', '');
incidentGr.update();
count++;
}
gs.info('Unassigned ' + count + ' incident(s)');
Note: This is a common real-world clean-up. Keep the assignment group so the ticket goes back to the team's queue, and say why you let Business Rules run (no setWorkflow(false)) - the reassignment is a genuine change people should see.
Reference fields store sys_ids, but you don't need a separate query to find them: setDisplayValue() sets a reference by its display value (the name) on the incident itself. Check that both were found, then set the other values and insert(). On a real instance, priority is calculated from impact and urgency, so set those two.
Script :
var incidentGr = new GlideRecord('incident');
incidentGr.initialize();
// setDisplayValue() finds the reference by its display value (the name) and stores its sys_id
incidentGr.setDisplayValue('caller_id', 'Anita Desai');
incidentGr.setDisplayValue('assignment_group', 'Database');
if (incidentGr.caller_id.nil() || incidentGr.assignment_group.nil()) {
gs.error('Caller or group not found');
} else {
incidentGr.setValue('short_description', 'Production database is down');
incidentGr.setValue('category', 'database');
incidentGr.setValue('impact', 1);
incidentGr.setValue('urgency', 1);
incidentGr.insert();
gs.info('Created ' + incidentGr.getValue('number'));
}
Note: setValue('caller_id', 'Anita Desai') is a classic mistake: setValue() expects the sys_id, so it stores a broken reference. setDisplayValue() is the one that takes the name. Dot-walking (caller_id.name) only reads through a reference and can't set one. Display values aren't unique either, so when two users can share a name, look the user up by user ID instead. And never hard-code sys_ids: they are different on every instance.
^OR binds to the condition right before it, so (P1 OR P2) AND (Network OR Database) is written as below. An IN list is a shorter alternative: active=true^priorityIN1,2^assignment_group.nameINNetwork,Database.
Script :
var incidentGr = new GlideRecord('incident');
incidentGr.addEncodedQuery('active=true^priority=1^ORpriority=2^assignment_group.name=Network^ORassignment_group.name=Database');
incidentGr.query();
while (incidentGr.next()) {
gs.info(incidentGr.getValue('number') + ' | ' + incidentGr.priority.getDisplayValue() + ' | ' + incidentGr.assignment_group.getDisplayValue());
}
Note: The trap is ^NQ: it does not mean "or" between two conditions, it starts a completely separate query. With ^NQ in the middle, every Database incident matches regardless of priority. Build the filter in a list view and use Copy query if you are unsure.
Query the membership table sys_user_grmember and dot-walk to the group's active flag. One query answers the question.
Script :
var memberGr = new GlideRecord('sys_user_grmember');
memberGr.addQuery('group.active', false);
memberGr.query();
while (memberGr.next()) {
gs.info(memberGr.user.getDisplayValue() + ' -> ' + memberGr.group.getDisplayValue());
}
Note: Knowing that sys_user_grmember is the many-to-many table between users and groups is the real test here. In an actual clean-up you would also remove these memberships, because users keep the roles inherited from the group.
Script :
var userGr = new GlideRecord('sys_user');
userGr.addActiveQuery();
userGr.addNullQuery('email');
userGr.orderBy('name');
userGr.query();
while (userGr.next()) {
gs.info(userGr.getValue('name') + ' (' + userGr.getValue('user_name') + ')');
}
addNullQuery('email')filters empty values in the database, so only the matching users are loaded.- Checking
email == ''inside the loop gives the same output but reads every user in the table first. On a real instance with thousands of users, that difference matters. addActiveQuery()is shorthand foraddQuery('active', true).
Script :
var agg = new GlideAggregate('incident');
agg.addActiveQuery();
agg.addQuery('priority', 1);
agg.addAggregate('COUNT');
agg.query();
var count = 0;
if (agg.next()) {
count = parseInt(agg.getAggregate('COUNT'), 10);
}
gs.info('Active P1 incidents: ' + count);
GlideAggregateasks the database for the count, so no records are loaded at all.getRowCount()on a GlideRecord loads every matching record just to count them, and a counting loop does the same with extra work.getAggregate()returns a string, so convert it withparseInt()before doing maths with it.
Script :
var agg = new GlideAggregate('sys_user');
agg.addActiveQuery();
agg.addAggregate('COUNT');
agg.groupBy('department');
agg.query();
while (agg.next()) {
var dept = agg.getDisplayValue('department') || '(no department)';
gs.info(dept + ': ' + agg.getAggregate('COUNT'));
}
- Grouping on a reference field groups by its sys_id, so print
getDisplayValue()to show the name. - Users with no department form their own group with an empty value. Handling it explicitly is the detail interviewers look for.
- One aggregate query covers every department, however many there are.
Script :
var agg = new GlideAggregate('incident');
agg.addQuery('opened_at', '>=', gs.daysAgoStart(7));
agg.addAggregate('COUNT');
agg.groupBy('priority');
agg.orderBy('priority');
agg.query();
while (agg.next()) {
gs.info(agg.getDisplayValue('priority') + ': ' + agg.getAggregate('COUNT'));
}
gs.daysAgoStart(7)is midnight at the start of the day 7 days ago, which is what people mean by "the last 7 days".gs.daysAgo(7)keeps the current time of day, so anything opened earlier that morning drops out of the report.orderBy('priority')sorts on the stored value, so 1 - Critical comes first.
Script :
var grp = new GlideRecord('sys_user_group');
if (grp.get('name', 'Software')) {
var managerId = grp.getValue('manager');
var inc = new GlideRecord('incident');
inc.addActiveQuery();
inc.addQuery('assignment_group', grp.getUniqueValue());
inc.addNullQuery('assigned_to');
inc.query();
var count = 0;
while (inc.next()) {
inc.setValue('assigned_to', managerId);
inc.update();
count++;
}
gs.info('Reassigned ' + count + ' incidents');
}
- Read the manager once, outside the loop, instead of looking it up for every incident.
addNullQuery('assigned_to')plusaddActiveQuery()limits the update to exactly the records that need it. Closed Software incidents stay as they are.- Looking the manager up from the group keeps the script correct when the manager changes. A hard-coded sys_id silently goes stale.
Script :
var ids = [];
var inc = new GlideRecord('incident');
inc.addActiveQuery();
inc.addQuery('assignment_group.name', 'Network');
inc.query();
while (inc.next()) {
ids.push(inc.getUniqueValue());
}
gs.info(ids.join(','));
inc.sys_idis a GlideElement, not a string. The same object is reused asnext()moves, so pushing it fills the array with references to one object, and every entry ends up as the last record's sys_id.getUniqueValue()(orgetValue('sys_id')) returns a plain string copy, which is what you want to store.- The same trap applies to any field: always store
getValue()results, never the field objects.
Script :
var agg = new GlideAggregate('incident');
agg.addQuery('state', 6);
agg.addAggregate('AVG', 'reassignment_count');
agg.groupBy('assignment_group');
agg.query();
while (agg.next()) {
var avg = parseFloat(agg.getAggregate('AVG', 'reassignment_count'));
gs.info(agg.getDisplayValue('assignment_group') + ': ' + avg.toFixed(1));
}
AVGworks likeCOUNT, but needs the field name both when you add it and when you read it.- Aggregate results come back as strings, so convert with
parseFloat()before rounding. - One aggregate query gives every group's average, with no loop over the incidents.
Script :
var agg = new GlideAggregate('incident');
agg.addActiveQuery();
agg.addNotNullQuery('problem_id');
agg.addAggregate('COUNT');
agg.groupBy('problem_id');
agg.query();
while (agg.next()) {
gs.info(agg.problem_id.getDisplayValue() + ': ' + agg.getAggregate('COUNT'));
}
GlideAggregatewithgroupBy('problem_id')returns one row per problem, with the count calculated by the database.addNotNullQuery('problem_id')leaves out the many incidents that are not linked to any problem.getDisplayValue()on the grouped reference gives the problem number, not its sys_id.- A problem's own state does not matter here: a closed problem with an incident still open is exactly what this report should surface.
Script :
var inc = new GlideRecord('incident');
inc.addQuery('caused_by.close_code', 'unsuccessful');
inc.orderBy('caused_by');
inc.orderBy('number');
inc.query();
while (inc.next()) {
gs.info(inc.caused_by.getDisplayValue() + ': ' + inc.getValue('number'));
}
- Start from the table that holds the link. Every incident has a caused_by reference, so one incident query answers the question.
- Dot-walking inside
addQuery()filters on the change's close code without loading any change records. - Starting from change_request and querying incidents per change works, but runs one extra query for every failed change.
- In a post-incident review this is the first report people ask for: which change broke what.
Script :
var kb = new GlideRecord('kb_knowledge');
kb.addQuery('workflow_state', 'published');
kb.addQuery('valid_to', '>=', gs.daysAgoStart(-7));
kb.addQuery('valid_to', '<=', gs.daysAgoEnd(-7));
kb.query();
while (kb.next()) {
// parm1 = who gets the email, parm2 = the expiry date for the message
gs.eventQueue('kb.article.expiring', kb, kb.getValue('author'), kb.getValue('valid_to'));
gs.info(kb.getValue('number') + ' -> ' + kb.getDisplayValue('author'));
}
- "Exactly 7 days" means the whole day 7 days from now:
gs.daysAgoStart(-7)togs.daysAgoEnd(-7). Comparing with a single timestamp would miss articles that expire at any other time that day. - Because the job runs every day, each article falls in that one-day window exactly once, so every owner gets one reminder, never two.
gs.eventQueue()only fires the event. A Notification on kb_knowledge, sent when kb.article.expiring fires, with Event parm 1 contains recipient ticked, sends the email. Register the event in the Event Registry first.- Firing an event instead of sending email from the script keeps the wording editable by admins and puts every reminder in the email log.
- Only published articles need a reminder: drafts and articles in review are not visible to users anyway.
While you're deciding, someone else applying for the same role already started their 15-day plan.
No countdown, no gimmick, just a head start you can still catch up on.
🔒 Secure payment via Razorpay · Instant access after payment
Real Interview Questions & Answers
Questions shared by ServiceNow professionals and reviewed for clarity, relevance, and interview usefulness.
🚀 Power Up Your ServiceNow Career
Join a growing community of smart ServiceNow professionals to stay ahead in interviews, sharpen your development skills, and accelerate your career.