How to get row count in groovy sql

To get the count or size of the records returned used data.size().


Here is the code to get the count of rows in grails. Firstly autowire the datasource in your service and create an Sql object from that as shown.This Sql should be imported from groovy.sql.Sql

Sql sql = new Sql(datasource)   

Then with the code below u can get the count as long.

def result = sql.firstRow('select count(*) as cont from <table>')
long count = result.cont

There is no need to fetch complete records from the database


sql.firstRow() is good to execute single-row SQL statements. Elvis operator helps if SQL result has no rows.

def cnt = SQL
     .firstRow('SELECT COUNT(*) AS cnt FROM form_tbl WHERE form_id=:id', id:1)
     ?.cnt

Tags:

Groovy