How to execute a Query using N/Query module

Query Execution

Once the query is defined, you can execute it to retrieve the data. Execution can be synchronous or asynchronous, depending on your needs.

Here’s how to execute the query synchronously:

define(['N/query'], function(query) {

  var myQuery = query.create({

    type: query.Type.CUSTOMER

  });




  myQuery.columns = [

    myQuery.createColumn({ fieldId: 'entityid' }),

    myQuery.createColumn({ fieldId: 'email' })

  ];




  myQuery.condition = myQuery.createCondition({

    fieldId: 'email',

    operator: query.Operator.ISNOTEMPTY

  });




  var resultSet = myQuery.run();

  var results = resultSet.results;

  log.debug('Query Results', results);

});

Query Results

The results of a query are returned as a `ResultSet` object, which contains an array of `Result` objects. Each `Result` object represents a row of data.

Here’s an example of processing the query results:

define(['N/query'], function(query) {

  var myQuery = query.create({

    type: query.Type.CUSTOMER

  });




  myQuery.columns = [

    myQuery.createColumn({ fieldId: 'entityid' }),

    myQuery.createColumn({ fieldId: 'email' })

  ];




  myQuery.condition = myQuery.createCondition({

    fieldId: 'email',

    operator: query.Operator.ISNOTEMPTY

  });




  var resultSet = myQuery.run();

  resultSet.results.forEach(function(result) {

    log.debug('Customer ID', result.getValue({ fieldId: 'entityid' }));

    log.debug('Customer Email', result.getValue({ fieldId: 'email' }));

  });

});

This example demonstrates how to define a query, execute it, and process the results to log customer IDs and emails

Leave a comment

Your email address will not be published. Required fields are marked *