Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get count of sql.Rows without using Next()?

Tags:

I need to get the length of *sql.Rows before I begin my Next() loop to get the values out. One way is to create a slice of rows by looping over Next() twice, getting the count, and then looping over that new slice to pull the values out, but that seems really inefficient so I'm hoping there is a better way to do this.

Looking at the docs, I see no mention of a Count function or Length function that I can use: https://golang.org/pkg/database/sql/#Rows

Looking at the Go code, I can't see anything in the struct that would help me (although I could be missing something, so would appreciate a second pair of eyes here): https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1714

Surely there is some way to do this that is better than just looping over Next() twice?

I realize I could do a separate count query as well, or even include a count(*) in my other select, but I'd rather avoid this too. This is for a Go ORM project, and I don't want to overcomplicate the select statement, and I'd rather avoid tampering with their built-up request as much as possible.

Thanks.

like image 472
b0xxed1n Avatar asked Jun 04 '16 10:06

b0xxed1n


People also ask

How do I count specific rows in SQL?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).


1 Answers

You basically listed your options. There is no hidden feature that would supply you the rows count.

Note that some db-specific driver might support this, but the general interface does not.

Also note that if you plan to iterate over the rows and read them anyway, this means negligible overhead which you should not be concerned about. If the rows count is really big and the query returns many data and you want to avoid allocating memory for all, then execute a SELECT COUNT(*) query beforehand so you'll know the number of results (but know that it might change for the next query if records are inserted or updated meanwhile).

like image 81
icza Avatar answered Oct 09 '22 12:10

icza