Home >Backend Development >Golang >How to Count Rows in a Go Database?
Counting Rows in Go
Retrieving the count of rows from a database is a fundamental operation in Go applications. One approach is to use the db.Query function to execute a raw SQL query. By setting the query to SELECT COUNT(*) FROM you can fetch the row count.
<code class="go">count, err := db.Query("SELECT COUNT(*) FROM main_table")</code>
However, you'll need to scan the returned row to access the actual count value.
<code class="go">var rowCount int if err := rows.Scan(&rowCount); err != nil { log.Fatal(err) }</code>
You can then print the rowCount:
<code class="go">fmt.Printf("Number of rows are %s\n", rowCount)</code>
For simplicity, it's recommended to use db.QueryRow instead of db.Query in this scenario, as you expect only one row to be returned.
<code class="go">var rowCount int err := db.QueryRow("SELECT COUNT(*) FROM main_table").Scan(&rowCount)</code>
By using QueryRow(), you can avoid closing the result and handle the error gracefully using switch:
<code class="go">switch { case err != nil: log.Fatal(err) default: fmt.Printf("Number of rows are %s\n", rowCount) }</code>
This provides a concise and efficient way to retrieve row counts from a database in Go.
The above is the detailed content of How to Count Rows in a Go Database?. For more information, please follow other related articles on the PHP Chinese website!