Count number of rows in golang

I want to display the number of rows from database using Go. How do I display number of rows?

count, err := db.Query("SELECT COUNT(*) FROM main_table")

Upvotes: 16

Views: 32386

Answers (2)

RN Timpko
RN Timpko

Reputation: 1

I signed up just to share this as my large datasets were slowing down the program with the constant appends. I wanted to put the rowcount in the rows and figured that something like that must exist, just had to find it.

SELECT 
count(1) OVER(PARTITION BY domain_id) AS rowcount,
subscription_id,
domain_id,
...
FROM mytable 
WHERE domain_id = 2020

Never used this command before, but it will add the count of the result set that share this parameter. Setting it to one of the query WHERE's makes it the total rows.

Upvotes: 0

chanioxaris
chanioxaris

Reputation: 1006

The query will return a row into the variable count. So the next you have to do is to read this row and assign the result into a new variable, using the function Scan(). This is how it works.

rows, err := db.Query("SELECT COUNT(*) FROM main_table")
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

var count int

for rows.Next() {   
    if err := rows.Scan(&count); err != nil {
        log.Fatal(err)
    }
}

fmt.Printf("Number of rows are %s\n", count)

The best option thought would be to use QueryRow() as you expect to read just one row. The code then will be.

var count int

err := db.QueryRow("SELECT COUNT(*) FROM main_table").Scan(&count)
switch {    
case err != nil:
    log.Fatal(err)
default:
    fmt.Printf("Number of rows are %s\n", count)
}

Upvotes: 35

Related Questions