Delete rows [PostgreSQL MySQL]

API

For the full list of supported methods, see DeleteQueryDELETE - 图1open in new window.

  1. db.NewDelete().
  2. With("cte_name", subquery).
  3. Model(&strct).
  4. Model(&slice).
  5. Table("table1", "table2"). // quotes table names
  6. TableExpr("table1 AS t1"). // arbitrary unsafe expression
  7. TableExpr("(?) AS alias", subquery).
  8. ModelTableExpr("table1 AS t1"). // overrides model table name
  9. WherePK(). // where using primary keys
  10. Where("id = ?", 123).
  11. Where("name LIKE ?", "my%").
  12. Where("? = 123", bun.Ident("id")).
  13. Where("id IN (?)", bun.In([]int64{1, 2, 3})).
  14. Where("id IN (?)", subquery).
  15. Where("FALSE").WhereOr("TRUE").
  16. WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery {
  17. return q.WhereOr("id = 1").
  18. WhereOr("id = 2")
  19. }).
  20. Returning("*").
  21. Returning("col1, col2").
  22. Returning("NULL"). // don't return anything
  23. Exec(ctx)

Example

To delete a row, define a model and use DeleteQueryDELETE - 图2open in new window:

  1. res, err := db.NewDelete().Where("id = ?", 123).Exec(ctx)

Bulk-delete

To bulk-delete books by a primary key:

  1. books := []*Book{book1, book2} // slice of books with ids
  2. res, err := db.NewDelete().Model(&books).WherePK().Exec(ctx)
  1. DELETE FROM "books" WHERE id IN (1, 2)

DELETE … USING

To delete rows using another table:

  1. res, err := db.NewDelete().
  2. Model((*Book)(nil)).
  3. TableExpr("archived_books AS src").
  4. Where("book.id = src.id").
  5. Exec(ctx)
  1. DELETE FROM "books" AS book
  2. USING archived_books AS src
  3. WHERE book.id = src.id