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?
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.
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.
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.
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 .
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With