Get Count of Records Matching a Search Condition

The sample script shows how to retrieve the count of Opportunity records with the name 'Pinnacle Systems'. You can place the script in the Before Insert section in the Database trigger event of the Opportunity object.

def v = newView('OpportunityVO')   // VO can be changed according to the Object used for counting the records
def vc = newViewCriteria(v)
def vcr = vc.createRow()
def vciName = vcr.ensureCriteriaItem("Name")  // Field name of the View Object used for the Criteria
vciName.setOperator('=')
vciName.setValue("Pinnacle Systems")
vc.insertRow(vcr)
v.appendViewCriteria(vc)
long count = 0;
v.executeQuery()
count = v.getEstimatedRowCount()
println('Opportunities found: ' + count)
Note:

The getEstimatedRowCount() function returns an estimate. You can't use it in places where accurate values are expected all the time.