Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get count and result from SQL query in Go

Tags:

sql

go

I'm running a pretty straightforward query using the database/sql and lib/pq (postgres) packages and I want to toss the results of some of the fields into a slice, but I need to know how big to make the slice.

The only solution I can find is to do another query that is just SELECT COUNT(*) FROM tableName;.

Is there a way to both get the result of the query AND the count of returned rows in one query?

like image 746
Arel Avatar asked Nov 10 '22 08:11

Arel


1 Answers

Conceptually, the problem is that the database cursor may not be enumerated to the end so the database does not really know how many records you will get before you actually read all of them. The only way to count (in general case) is to go through all the records in the resultset.

But practically, you can enforce it to do so by using subqueries like

select *, (select count(*) from table) from table

and just ignore the second column for records other than first. But it is very rude and I do not recommend doing so.

like image 111
Alex Netkachov Avatar answered Nov 14 '22 22:11

Alex Netkachov