Skip to content

Delete Builder

The delete builder allows you to create DELETE queries, to delete a set of rows from your database.

.delete(tableName: pointer)

The delete builder takes as argument the name of the table items will be deleted from, eventually with an alias.

sh.delete('users').build();

//> { text: 'DELETE FROM "users"', values: [] }
// clear the table users !

.using(...pointers[])

The using method allows you to use others table columns in the where clause of your delete query.

sh
    .delete('users')
    .using('posts')
    .where('users.user_id', '"posts"."user_id"')
    .and('posts.published_at', '<', new Date(2000))
    .build();

// { text:
//    `DELETE FROM "users" USING "posts" WHERE
//      "users"."user_id" = "posts"."user_id" AND "posts"."published_at" < '1970-01-01T00:00:02.000Z'`,
//   values: [] }

.where(leftOperand, ?operator, ?rightOperand)

This method returns a proxy of a conditions builder which will be revoked whenever you call a method which does not belong to that conditions builder. See conditions builder for more details. You use it to create where clause in your delete query

sh
    .delete('posts')
    .where('posts.user_id', 42)
    .and('published_at', '<', new Date(2015))
    .build();

// >  { text:
//    `DELETE FROM "posts" SET WHERE
//     "posts"."user_id" = 42 AND "published_at" < '1970-01-01T00:00:02.015Z'`,
//   values: [] }

.returning(...properties: pointers[])

Specify a returning close to your delete query. It is useful if you want to get back the freshly deleted rows (to archive in other table for example)

sh
    .delete('posts')
    .where('posts.user_id', 42)
    .returning('*')
    .build();

// > { text:
//    `DELETE FROM "posts" WHERE "posts"."user_id" = 42 RETURNING *`,
//   values: [] }

You can use the '*' character if you wish to return all the columns the deleted rows.