Home > Article > Backend Development > How to sort database records in Golang?
In Golang, query results can be sorted by using the ORDER BY clause in the database/sql package. Syntax: func (db *DB) Query(query string, args ...interface{}) (*Rows, error) Sorting example: SELECT * FROM users ORDER BY name ASC Other sorting options: DESC (descending), multiple columns (Comma separated), NULL value sort order (NULLS FIRST or NULLS LAST) Practical case: Sort orders in descending order by "order_date": SELECT * FROM orders ORDER BY order_date DESC.
When using the database/sql package to operate the database in Golang, you can use the ORDER BY
clause to sort the query results.
Syntax:
func (db *DB) Query(query string, args ...interface{}) (*Rows, error)
Sort example:
The following example shows how to sort the Records sorted by "name" column in ascending order:
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { // 连接到数据库 db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database") if err != nil { panic(err) } defer db.Close() // 构建查询 query := `SELECT * FROM users ORDER BY name ASC` // 执行查询 rows, err := db.Query(query) if err != nil { panic(err) } defer rows.Close() // 遍历结果 for rows.Next() { var id int var name, email string if err := rows.Scan(&id, &name, &email); err != nil { panic(err) } fmt.Printf("%d %s %s\n", id, name, email) } }
Other sorting options:
ORDER BY name DESC, age ASC
NULLS FIRST
or NULLS LAST
Specifies whether to place NULL values at the beginning or end of the result setPractical case:
Suppose we have an "orders" table with columns "order_id", "customer_id" and "order_date". We can write a Golang program to sort orders by "order_date" in descending order:
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { // 连接到数据库 db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database") if err != nil { panic(err) } defer db.Close() // 构建查询 query := `SELECT * FROM orders ORDER BY order_date DESC` // 执行查询 rows, err := db.Query(query) if err != nil { panic(err) } defer rows.Close() // 遍历结果 for rows.Next() { var orderID, customerID int var orderDate string if err := rows.Scan(&orderID, &customerID, &orderDate); err != nil { panic(err) } fmt.Printf("%d %d %s\n", orderID, customerID, orderDate) } }
The above is the detailed content of How to sort database records in Golang?. For more information, please follow other related articles on the PHP Chinese website!