Arel
Arel

Reputation: 3938

Get count and result from SQL query in 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?

Upvotes: 6

Views: 6782

Answers (3)

SoftwareCarpenter
SoftwareCarpenter

Reputation: 3923

Not sure if this is what you are asking for but you can call the @@Rowcount function to return the count of the previous select statement that has been executed.

SELECT mytable.mycol FROM mytable WHERE mytable.foo = 'bar'

SELECT @@Rowcount

If you want the row count included in your result set you can use the the OVER clause (MSDN)

SELECT mytable.mycol, count(*) OVER(PARTITION BY mytable.foo) AS 'Count' FROM mytable WHERE mytable.foo = 'bar'

You could also perhaps just separate two SQL statements with the a ; . This would return a result set of both statements executed.

Upvotes: 0

Alex Netkachov
Alex Netkachov

Reputation: 13522

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.

Upvotes: 4

Naimish Mungara
Naimish Mungara

Reputation: 237

You would used count(*)

SELECT count(distinct last)
FROM (XYZTable)
WHERE date(FROM_UNIXTIME(time)) >= '2013-10-28' AND
id = 90 ;

Upvotes: -2

Related Questions