Delete rows [PostgreSQL MySQL]
API
For the full list of supported methods, see DeleteQuery
open in new window.
1. db.NewDelete().
2. With("cte_name", subquery).
4. Model(&strct).
5. Model(&slice).
7. Table("table1", "table2"). // quotes table names
8. TableExpr("table1 AS t1"). // arbitrary unsafe expression
9. TableExpr("(?) AS alias", subquery).
10. ModelTableExpr("table1 AS t1"). // overrides model table name
12. WherePK(). // where using primary keys
13. Where("id = ?", 123).
14. Where("name LIKE ?", "my%").
15. Where("? = 123", bun.Ident("id")).
16. Where("id IN (?)", bun.In([]int64{1, 2, 3})).
17. Where("id IN (?)", subquery).
18. Where("FALSE").WhereOr("TRUE").
19. WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery {
20. return q.WhereOr("id = 1").
21. WhereOr("id = 2")
22. }).
24. Returning("*").
25. Returning("col1, col2").
26. Returning("NULL"). // don't return anything
28. Exec(ctx)
Example
To delete a row, define a model and use DeleteQuery
open 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
