Skip to the content.

Inserting

To create a InsertDataset you can use

goqu.Insert

When you just want to create some quick SQL, this mostly follows the Postgres with the exception of placeholders for prepared statements.

ds := goqu.Insert("user").Rows(
    goqu.Record{"first_name": "Greg", "last_name": "Farley"},
)
insertSQL, _, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" ("first_name", "last_name") VALUES ('Greg', 'Farley')

SelectDataset.Insert

If you already have a SelectDataset you can invoke Insert() to get a InsertDataset

NOTE This method will also copy over the WITH clause as well as the FROM

ds := goqu.From("user")

ds := ds.Insert().Rows(
    goqu.Record{"first_name": "Greg", "last_name": "Farley"},
)
insertSQL, _, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" ("first_name", "last_name") VALUES ('Greg', 'Farley')

DialectWrapper.Insert

Use this when you want to create SQL for a specific dialect

// import _ "github.com/doug-martin/goqu/v9/dialect/mysql"

dialect := goqu.Dialect("mysql")

ds := dialect.Insert().Rows(
    goqu.Record{"first_name": "Greg", "last_name": "Farley"},
)
insertSQL, _, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO `user` (`first_name`, `last_name`) VALUES ('Greg', 'Farley')

Database.Insert

Use this when you want to execute the SQL or create SQL for the drivers dialect.

// import _ "github.com/doug-martin/goqu/v9/dialect/mysql"

mysqlDB := //initialize your db
db := goqu.New("mysql", mysqlDB)

ds := db.Insert().Rows(
    goqu.Record{"first_name": "Greg", "last_name": "Farley"},
)
insertSQL, _, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO `user` (`first_name`, `last_name`) VALUES ('Greg', 'Farley')

Examples

For more examples visit the Docs

Insert with Cols and Vals

ds := goqu.Insert("user").
	Cols("first_name", "last_name").
	Vals(
		goqu.Vals{"Greg", "Farley"},
		goqu.Vals{"Jimmy", "Stewart"},
		goqu.Vals{"Jeff", "Jeffers"},
	)
insertSQL, args, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" ("first_name", "last_name") VALUES ('Greg', 'Farley'), ('Jimmy', 'Stewart'), ('Jeff', 'Jeffers') []

Insert goqu.Record

ds := goqu.Insert("user").Rows(
	goqu.Record{"first_name": "Greg", "last_name": "Farley"},
	goqu.Record{"first_name": "Jimmy", "last_name": "Stewart"},
	goqu.Record{"first_name": "Jeff", "last_name": "Jeffers"},
)
insertSQL, args, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" ("first_name", "last_name") VALUES ('Greg', 'Farley'), ('Jimmy', 'Stewart'), ('Jeff', 'Jeffers') []

Insert Structs

type User struct {
	FirstName string `db:"first_name"`
	LastName  string `db:"last_name"`
}
ds := goqu.Insert("user").Rows(
	User{FirstName: "Greg", LastName: "Farley"},
	User{FirstName: "Jimmy", LastName: "Stewart"},
	User{FirstName: "Jeff", LastName: "Jeffers"},
)
insertSQL, args, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" ("first_name", "last_name") VALUES ('Greg', 'Farley'), ('Jimmy', 'Stewart'), ('Jeff', 'Jeffers') []

You can skip fields in a struct by using the skipinsert tag

type User struct {
	FirstName string `db:"first_name" goqu:"skipinsert"`
	LastName  string `db:"last_name"`
}
ds := goqu.Insert("user").Rows(
	User{FirstName: "Greg", LastName: "Farley"},
	User{FirstName: "Jimmy", LastName: "Stewart"},
	User{FirstName: "Jeff", LastName: "Jeffers"},
)
insertSQL, args, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" ("last_name") VALUES ('Farley'), ('Stewart'), ('Jeffers') []

If you do not want to set the database field when the struct field is a nil pointer you can use the omitnil tag.

type item struct {
    FirstName string  `db:"first_name" goqu:"omitnil"`
    LastName  string  `db:"last_name" goqu:"omitnil"`
    Address1  *string `db:"address1" goqu:"omitnil"`
    Address2  *string `db:"address2" goqu:"omitnil"`
    Address3  *string `db:"address3" goqu:"omitnil"`
}
address1 := "111 Test Addr"
var emptyString string
i := item{
    FirstName: "Test First Name",
    LastName:  "",
    Address1:  &address1,
    Address2:  &emptyString,
    Address3:  nil, // will omit nil pointer
}

insertSQL, args, _ := goqu.Insert("items").Rows(i).ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "items" ("address1", "address2", "first_name", "last_name") VALUES ('111 Test Addr', '', 'Test First Name', '') []

If you do not want to set the database field when the struct field is a zero value (including nil pointers) you can use the omitempty tag.

Empty embedded structs implementing the Valuer interface (eg. sql.NullString) will also be omitted.

type item struct {
    FirstName string  `db:"first_name" goqu:"omitempty"`
    LastName  string  `db:"last_name" goqu:"omitempty"`
    Address1  *string `db:"address1" goqu:"omitempty"`
    Address2  *string `db:"address2" goqu:"omitempty"`
    Address3  *string `db:"address3" goqu:"omitempty"`
}
address1 := "112 Test Addr"
var emptyString string
i := item{
    FirstName: "Test First Name",
    LastName:  "", // will omit zero field
    Address1:  &address1,
    Address2:  &emptyString,
    Address3:  nil, // will omit nil pointer
}
insertSQL, args, _ := goqu.Insert("items").Rows(i).ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "items" ("address1", "address2", "first_name") VALUES ('112 Test Addr', '', 'Test First Name') []

If you want to use the database DEFAULT when the struct field is a zero value you can use the defaultifempty tag.

type User struct {
	FirstName string `db:"first_name" goqu:"defaultifempty"`
	LastName  string `db:"last_name"`
}
ds := goqu.Insert("user").Rows(
	User{LastName: "Farley"},
	User{FirstName: "Jimmy", LastName: "Stewart"},
	User{LastName: "Jeffers"},
)
insertSQL, args, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" ("first_name", "last_name") VALUES (DEFAULT, 'Farley'), ('Jimmy', 'Stewart'), (DEFAULT, 'Jeffers') []

goqu will also use fields in embedded structs when creating an insert.

NOTE unexported fields will be ignored!

type Address struct {
	Street string `db:"address_street"`
	State  string `db:"address_state"`
}
type User struct {
	Address
	FirstName string
	LastName  string
}
ds := goqu.Insert("user").Rows(
	User{Address: Address{Street: "111 Street", State: "NY"}, FirstName: "Greg", LastName: "Farley"},
	User{Address: Address{Street: "211 Street", State: "NY"}, FirstName: "Jimmy", LastName: "Stewart"},
	User{Address: Address{Street: "311 Street", State: "NY"}, FirstName: "Jeff", LastName: "Jeffers"},
)
insertSQL, args, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" ("address_state", "address_street", "firstname", "lastname") VALUES ('NY', '111 Street', 'Greg', 'Farley'), ('NY', '211 Street', 'Jimmy', 'Stewart'), ('NY', '311 Street', 'Jeff', 'Jeffers') []

NOTE When working with embedded pointers if the embedded struct is nil then the fields will be ignored.

type Address struct {
	Street string
	State  string
}
type User struct {
	*Address
	FirstName string
	LastName  string
}
ds := goqu.Insert("user").Rows(
	User{FirstName: "Greg", LastName: "Farley"},
	User{FirstName: "Jimmy", LastName: "Stewart"},
	User{FirstName: "Jeff", LastName: "Jeffers"},
)
insertSQL, args, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" ("firstname", "lastname") VALUES ('Greg', 'Farley'), ('Jimmy', 'Stewart'), ('Jeff', 'Jeffers') []

You can ignore an embedded struct or struct pointer by using db:"-"

type Address struct {
	Street string
	State  string
}
type User struct {
	Address   `db:"-"`
	FirstName string
	LastName  string
}

ds := goqu.Insert("user").Rows(
	User{Address: Address{Street: "111 Street", State: "NY"}, FirstName: "Greg", LastName: "Farley"},
	User{Address: Address{Street: "211 Street", State: "NY"}, FirstName: "Jimmy", LastName: "Stewart"},
	User{Address: Address{Street: "311 Street", State: "NY"}, FirstName: "Jeff", LastName: "Jeffers"},
)
insertSQL, args, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" ("firstname", "lastname") VALUES ('Greg', 'Farley'), ('Jimmy', 'Stewart'), ('Jeff', 'Jeffers') []

Insert map[string]interface{}

ds := goqu.Insert("user").Rows(
	map[string]interface{}{"first_name": "Greg", "last_name": "Farley"},
	map[string]interface{}{"first_name": "Jimmy", "last_name": "Stewart"},
	map[string]interface{}{"first_name": "Jeff", "last_name": "Jeffers"},
)
insertSQL, args, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" ("first_name", "last_name") VALUES ('Greg', 'Farley'), ('Jimmy', 'Stewart'), ('Jeff', 'Jeffers') []

Insert Slices As Arrays

With the postgres dialect a slice used as an insert (or update) value is written as an array. Set SliceAsArray in the SQLDialectOptions of another dialect to get the same behavior. []byte, json.RawMessage, driver.Valuers (e.g. pq.Array) and expressions are written as before. An empty slice is written as '{}' and a nil slice as NULL.

The array is written as one array text literal, the same value pq.Array produces, so it takes the type of the column (text[], integer[], uuid[], …) and prepared statements bind it as a single argument.

ds := goqu.Dialect("postgres").Insert("posts").Rows(
    goqu.Record{"title": "New Post", "tags": []string{"a", "b"}},
)
insertSQL, _, _ := ds.ToSQL()
fmt.Println(insertSQL)

Output:

INSERT INTO "posts" ("tags", "title") VALUES ('{"a","b"}', 'New Post')

Slices in predicates (e.g. In) keep rendering as a list. Use goqu.Array where an array value is needed elsewhere:

sql, _, _ := goqu.Dialect("postgres").From("posts").
    Where(goqu.C("tags").Eq(goqu.Array([]string{"a"}))).ToSQL()
fmt.Println(sql)

Output:

SELECT * FROM "posts" WHERE ("tags" = '{"a"}')

Elements are written like the same value outside of an array: times use the time location (goqu.SetTimeLocation) and the dialect’s TimeFormat, and byte slices (e.g. json.RawMessage, or the []byte a driver.Valuer returns) are text unless they are binary, which are written in the hex form of a bytea.

Nested slices are multi dimensional arrays (a [][]int with the rows 1, 2 and 3, 4 is written as the rows {1,2} and {3,4} inside one more pair of braces). Postgres only stores rectangular arrays and cannot store empty sub arrays, so sub arrays with different lengths are an error (sqlgen.ErrRaggedArray) and so is a nil or empty sub array (sqlgen.ErrEmptyNestedArray). Elements that cannot be written in the text form, such as goqu.L("now()"), make the array render as ARRAY[now(), 'a'] instead.

goqu.Array is meant for Postgres (or databases with the same array literal). A column of a composite (row) type that was written with a slice, e.g. []interface{}{1, "x"}, now needs goqu.L("ROW(?, ?)", 1, "x") or a driver.Valuer when the dialect has SliceAsArray.

Scanning text[] columns is up to the driver: scan into pq.StringArray (github.com/lib/pq) or a pgtype type.

Insert from query

ds := goqu.Insert("user").Prepared(true).
	FromQuery(goqu.From("other_table"))
insertSQL, args, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" SELECT * FROM "other_table" []

You can also specify the columns

ds := goqu.Insert("user").Prepared(true).
	Cols("first_name", "last_name").
	FromQuery(goqu.From("other_table").Select("fn", "ln"))
insertSQL, args, _ := ds.ToSQL()
fmt.Println(insertSQL, args)

Output:

INSERT INTO "user" ("first_name", "last_name") SELECT "fn", "ln" FROM "other_table" []

On Conflict Clause

You can handle conflicts using the OnConflict clause. For example, to ignore conflicts, you can use DoNothing().

sql, _, _ := goqu.Insert("test").
	Rows(goqu.Record{"a": "a", "b": "b"}).
	OnConflict(goqu.DoNothing()).
	ToSQL()
fmt.Println(sql)

Output:

INSERT INTO "test" ("a", "b") VALUES ('a', 'b') ON CONFLICT DO NOTHING

To specify the conflict target columns, use TargetCols (or SetCols). This is supported by dialects that support a conflict target (Postgres, SQLite3). Using it with a dialect that does not (MySQL, SQL Server) returns an error instead of silently ignoring the target.

sql, _, _ := goqu.Insert("test").
	Rows(goqu.Record{"a": "a", "b": "b"}).
	OnConflict(goqu.DoNothing().TargetCols("a", "b")).
	ToSQL()
fmt.Println(sql)

Output:

INSERT INTO "test" ("a", "b") VALUES ('a', 'b') ON CONFLICT ("a", "b") DO NOTHING

TargetCols, SetCols, OnConstraint and TargetWhere are available on both DoNothing() and DoUpdateSet() (as well as DoUpdate()).

To update rows on conflict across multiple columns, or on a named constraint (Postgres), pair DoUpdateSet with TargetCols or OnConstraint. Constraint names are quoted as identifiers and cannot be combined with TargetCols.

sql, _, _ := goqu.Insert("test").
	Rows(goqu.Record{"a": "a", "b": "b"}).
	OnConflict(goqu.DoUpdateSet(goqu.Record{"b": goqu.L("EXCLUDED.b")}).OnConstraint("test_a_key")).
	ToSQL()
fmt.Println(sql)

Output:

INSERT INTO "test" ("a", "b") VALUES ('a', 'b') ON CONFLICT ON CONSTRAINT "test_a_key" DO UPDATE SET "b"=EXCLUDED.b

To target a partial unique index, add the index predicate with TargetWhere (it requires target columns). This is not the same as DoUpdateSet(...).Where(...), which filters the rows that get updated.

NOTE Values inside TargetWhere are always interpolated as SQL literals, even when Prepared(true) is set, because neither SQLite nor Postgres (once a reused statement switches to a generic plan) can match a parameterized predicate to a partial index definition. Only pass static schema constants to TargetWhere — never untrusted user input.

sql, _, _ := goqu.Insert("test").
	Rows(goqu.Record{"a": "a", "b": "b"}).
	OnConflict(goqu.DoNothing().
		TargetCols("a").
		TargetWhere(goqu.C("deleted_at").IsNull())).
	ToSQL()
fmt.Println(sql)

Output:

INSERT INTO "test" ("a", "b") VALUES ('a', 'b') ON CONFLICT ("a") WHERE ("deleted_at" IS NULL) DO NOTHING

DoUpdate(target, update) is still accepted for a raw target string (e.g. "a" or "on constraint name"), written as is when no TargetCols/OnConstraint is set. Combining a non-empty DoUpdate target string with TargetCols, SetCols, or OnConstraint returns an error; use DoUpdateSet(update) instead.

MySQL row alias

MySQL 8.0.19 added row aliases for INSERT ... ON DUPLICATE KEY UPDATE, and 8.0.20 deprecated VALUES(col) in favor of them. Use As to name the inserted row and reference it with an identifier in the update. The alias requires MySQL 8.0.19 or later; As is rendered as written on every dialect, so older servers will reject the statement.

sql, _, _ := goqu.Dialect("mysql8").Insert("t1").
	Cols("a", "b").
	Vals([]any{1, 2}, []any{4, 5}).
	As("new").
	OnConflict(goqu.DoUpdateSet(goqu.Record{"a": goqu.I("new.a"), "b": goqu.I("new.b")})).
	ToSQL()
fmt.Println(sql)

Output:

INSERT INTO `t1` (`a`, `b`) VALUES (1, 2), (4, 5) AS `new` ON DUPLICATE KEY UPDATE `a`=`new`.`a`,`b`=`new`.`b`

Returning Clause

Returning a single column example.

sql, _, _ := goqu.Insert("test").
	Rows(goqu.Record{"a": "a", "b": "b"}).
	Returning("id").
	ToSQL()
fmt.Println(sql)

Output:

INSERT INTO "test" ("a", "b") VALUES ('a', 'b') RETURNING "id"

Returning multiple columns

sql, _, _ = goqu.Insert("test").
	Rows(goqu.Record{"a": "a", "b": "b"}).
	Returning("a", "b").
	ToSQL()
fmt.Println(sql)

Output:

INSERT INTO "test" ("a", "b") VALUES ('a', 'b') RETURNING "a", "b"

Returning all columns

sql, _, _ = goqu.Insert("test").
	Rows(goqu.Record{"a": "a", "b": "b"}).
	Returning(goqu.T("test").All()).
	ToSQL()
fmt.Println(sql)

Output:

INSERT INTO "test" ("a", "b") VALUES ('a', 'b') RETURNING "test".*

SetError

Sometimes while building up a query with goqu you will encounter situations where certain preconditions are not met or some end-user contraint has been violated. While you could track this error case separately, goqu provides a convenient built-in mechanism to set an error on a dataset if one has not already been set to simplify query building.

Set an Error on a dataset:

func GetInsert(name string, value string) *goqu.InsertDataset {

    var ds = goqu.Insert("test")

    if len(field) == 0 {
        return ds.SetError(fmt.Errorf("name is empty"))
    }

    if len(value) == 0 {
        return ds.SetError(fmt.Errorf("value is empty"))
    }

    return ds.Rows(goqu.Record{name: value})
}

This error is returned on any subsequent call to Error or ToSQL:

var field, value string
ds = GetInsert(field, value)
fmt.Println(ds.Error())

sql, args, err = ds.ToSQL()
fmt.Println(err)

Output:

name is empty
name is empty

Executing Inserts

To execute INSERTS use Database.Insert to create your dataset

Examples

Executing an single Insert

db := getDb()

insert := db.Insert("goqu_user").Rows(
	goqu.Record{"first_name": "Jed", "last_name": "Riley", "created": time.Now()},
).Executor()

if _, err := insert.Exec(); err != nil {
	fmt.Println(err.Error())
} else {
	fmt.Println("Inserted 1 user")
}

Output:

Inserted 1 user

Executing multiple inserts

db := getDb()

users := []goqu.Record{
	{"first_name": "Greg", "last_name": "Farley", "created": time.Now()},
	{"first_name": "Jimmy", "last_name": "Stewart", "created": time.Now()},
	{"first_name": "Jeff", "last_name": "Jeffers", "created": time.Now()},
}

insert := db.Insert("goqu_user").Rows(users).Executor()
if _, err := insert.Exec(); err != nil {
	fmt.Println(err.Error())
} else {
	fmt.Printf("Inserted %d users", len(users))
}

Output:

Inserted 3 users

Inserting a very large number of rows

When executing with prepared statements, every value becomes a placeholder, and databases limit the number of parameters in a single statement (for example SQLITE_MAX_VARIABLE_NUMBER in SQLite, 65535 in PostgreSQL and MySQL). Inserting many rows in one statement can fail with errors such as too many SQL variables. Interpolated SQL has no placeholders but a very large statement can still exceed the server’s maximum packet or statement size and uses a lot of memory.

goqu does not split inserts for you. Insert in batches instead, ideally inside a transaction:

const batchSize = 500

tx, err := db.Begin()
if err != nil {
	return err
}
for start := 0; start < len(users); start += batchSize {
	end := min(start+batchSize, len(users))
	if _, err := tx.Insert("goqu_user").Rows(users[start:end]).Executor().Exec(); err != nil {
		_ = tx.Rollback()
		return err
	}
}
return tx.Commit()

Choose a batch size so that rows * columns stays below your database’s parameter limit.

If you use the RETURNING clause you can scan into structs or values.

db := getDb()

insert := db.Insert("goqu_user").Returning(goqu.C("id")).Rows(
		goqu.Record{"first_name": "Jed", "last_name": "Riley", "created": time.Now()},
).Executor()

var id int64
if _, err := insert.ScanVal(&id); err != nil {
	fmt.Println(err.Error())
} else {
	fmt.Printf("Inserted 1 user id:=%d\n", id)
}

Output:

Inserted 1 user id:=5