Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the rows count returned from db.Query postgres

Tags:

postgresql

go

I am using goLang lib/pq driver and trying to fetch rows from database.

rows, err := db.Query("select id, name from mytable limit 5")

I want to have a if else clause which checks if there are rows in result set and I did this:

if(!rows.Next()){
   log.Printf("no rows returned")
} else {
   log.Printf("rows returned")
}

but this always return me 1 record less and I assume its because of the if clause it skips one record because as soon as I remove if clause I get all records correctly. How can I know the count of rows returned from the select query without executing another query?

like image 715
codec Avatar asked Sep 30 '16 04:09

codec


People also ask

How do you count rows of a query result?

To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.

What is count (*) in PostgreSQL?

1) COUNT(*) You can use the PostgreSQL COUNT(*) function along with a SELECT statement to return the total number of rows in a table including the NULL values as well as the duplicates.

How do you get total row count?

Just click the column header. The status bar, in the lower-right corner of your Excel window, will tell you the row count. Do the same thing to count columns, but this time click the row selector at the left end of the row. If you select an entire row or column, Excel counts just the cells that contain data.

What is Reltuples in PostgreSQL?

reltuples ... Number of rows in the table. This is only an estimate used by the planner. It is updated by VACUUM , ANALYZE , and a few DDL commands such as CREATE INDEX .


1 Answers

When you work with the Rows object, there isn't any helper method that give you the total rows count in one step.

A simple but slower solution is to iterate through all the results using an incremental variable to store the amount of rows:

// error handling omitted
rows, _ := db.Query("SELECT * FROM table")
defer rows.Close()

counter := 0
for rows.Next() {
 // you can even scan+store the result if you need them later
 counter++
}

fmt.Println("we have", counter, "rows")

Otherwise, if your goal is only to "count" the amount of rows, use a more dedicated query with QueryRow

// error handling omitted
var counter int

db.QueryRow("SELECT count(*) FROM table").Scan(&counter)

fmt.Println("we have", counter, "rows")
like image 146
damoiser Avatar answered Sep 27 '22 23:09

damoiser