Select Queries

Selecting single rows or multiple rows is easy.

This type is used in the examples on this page.

type User struct {
    ID       int `gosql:"primary"`
    Email    string
    IsActive bool
}

When building queries with GoSQL, remember to use the table column names (snake case).

Single Row

To select a single row, pass a reference to a struct toGet() :

var user User
db.Select("*").Get(&user)

Get() returns an error that should be checked. This guide does not check for errors.

Selecting some fields only:

var user User
db.Select("id", "is_active").Get(&user)

Select with a where clause:

var user User
db.Select("id", "is_active").
    Where("is_active = ?", true).
    Get(&user)

Multiple Rows

To select multiple rows, it is best to pass a reference to a slice of structs toGet() :

var users []User
db.Select("*").Limit(100).Get(&users)

When selecting multiple rows, you must set the limit with Limit(). If you don't, an error will be returned.

Sorting results:

var users []User
db.Select("*").
    Limit(100).
    OrderBy("email ASC").
    Get(&users)

Use offset to get paginated results. This would be page 2 with a page size of 10:

var users []User
db.Select("*").
    Limit(10).
    Offset(10).
    Get(&users)

Last updated