Skip to content

Truncate table with Prisma Client like prisma.account.truncate() #5063

Open

Description

@tomdohnal

Problem

I want to delete all the data in a given table. In order to do that, I have to do something like this:

await prisma.account.deleteMany({where: {}})

The problem with that is that it does not communicate the intent really clearly and feels like a workaround rather than the canonical solution.

Suggested solution

I'd suggest creating a new method truncate which would truncate all the data in a table

await prisma.account.truncate()

Alternatives

Using

await prisma.account.deleteMany({where: {}})

or raw SQL queries.

Activity

  1. transferred this issue fromprisma/ormon Aug 10, 2020
  2. added
    kind/feature
    on Jan 13, 2021
  3. Jolg42 commented on Mar 24, 2021

    @Jolg42
    Contributor

    As a potential workaround, here is an example of doing a truncate on PostgreSQL manually using $queryRaw
    Copied from #742 (comment)

    Here is a manual truncate example that could help for now for PostgreSQL (example from Keystone):

            // Special fast path to drop data from a postgres database.
            // This is an optimization which is particularly crucial in a unit testing context.
            // This code path takes milliseconds, vs ~7 seconds for a migrate reset + db push
            for (const { tablename } of await this.prisma.$queryRaw(
              `SELECT tablename FROM pg_tables WHERE schemaname='${this.dbSchemaName}'`
            )) {
              await this.prisma.$queryRaw(
                `TRUNCATE TABLE \"${this.dbSchemaName}\".\"${tablename}\" CASCADE;`
              );
            }
            for (const { relname } of await this.prisma.$queryRaw(
              `SELECT c.relname FROM pg_class AS c JOIN pg_namespace AS n ON c.relnamespace = n.oid WHERE c.relkind='S' AND n.nspname='${this.dbSchemaName}';`
            )) {
              await this.prisma.$queryRaw(
                `ALTER SEQUENCE \"${this.dbSchemaName}\".\"${relname}\" RESTART WITH 1;`
              );
            }
  4. arenddeboer commented on Jul 3, 2021

    @arenddeboer

    Another + for truncate is that it will free up data, at least on PostgreSQL. A deleteMany({where: {}}) will not.

  5. timvandam commented on Jul 10, 2021

    @timvandam

    This would be great to have. deleteMany uses two queries: one that determines which rows to delete, and one that does the actual deleting. This is much slower than a good old TRUNCATE TABLE.

    A truncate() method that uses TRUNCATE TABLE would be more ideal

  6. Jolg42 commented on Jul 13, 2021

    @Jolg42
    Contributor

    @timvandam Note: an issue was created recently for the deleteMany optimisation here
    Edit: that is now optimized since 5.4.0

  7. calidion commented on Oct 7, 2023

    @calidion

    how is this issue going?

  8. Jolg42 commented on Oct 9, 2023

    @Jolg42
    Contributor

    @calidion There is no news about this issue.

    Though, there is good news about deleteMany() 🎊

    The optimization is now available since 5.4.0, for more details check out the bottom part of the release notes:
    https://github.com/prisma/prisma/releases/tag/5.4.0

    Screenshot 2023-10-09 at 10 33 07

    Originally posted by @Jolg42 in #8239 (comment)

  9. changed the title [-]Truncate table[/-] [+]Truncate table with Prisma Client like `prisma.account.truncate()`[/+] on Oct 9, 2023
  10. calidion commented on Oct 10, 2023

    @calidion

    @Jolg42
    It is confusing that is feature is so hard to be realized.

  11. janpio commented on Oct 12, 2023

    @janpio
    Contributor

    It's not hard. It's just not urgent as there is a workaround with deleteMany(). If for some reason that does not work for you, please explain why. Both comments from earlier that do so only have minimal number of 👍 - so this does not seem to be a very common problem.

  12. 1 remaining item

  13. janpio commented on Oct 13, 2023

    @janpio
    Contributor

    Yes. This issue does not have super high priority, so although that is correct we will not jump on implementing this soon. We are busy.

    You could probably create a Client Extension to add the method to all models and then execute a raw SQL command under the hood: https://www.prisma.io/docs/concepts/components/prisma-client/client-extensions

    (PRs welcome for the full implementation as well of course, but I realize that this is quite a big ask)

  14. Karl-Styner commented on Nov 10, 2023

    @Karl-Styner

    It's not hard. It's just not urgent as there is a workaround with deleteMany(). If for some reason that does not work for you, please explain why. Both comments from earlier that do so only have minimal number of 👍 - so this does not seem to be a very common problem.

    1. deleteMany function is slower than truncate query.
    2. deleteMany is not following reset incremental index.

    why is not first priority..?

  15. ilyaskarim commented on Jun 11, 2024

    @ilyaskarim

    Is there any updates on this?

  16. janpio commented on Jun 11, 2024

    @janpio
    Contributor

    Question to everyone who 👍 or commented here:

    What would be your use cases to want to fully truncate a table in an environment that uses Prisma Client?

  17. dahaupt commented on Jun 12, 2024

    @dahaupt

    We import external data into a table, which must be empty before each import. The data is not related to any other model.

    We currently call deleteMany as the auto-incremented id is not relevant within our business logic.

  18. ilyaskarim commented on Jun 12, 2024

    @ilyaskarim

    @dahaupt Yes id increment was not an issue for us too so I decided to write a script to truncate tables.

  19. kshitijkurandwad211 commented on Jul 16, 2024

    @kshitijkurandwad211

    Hi,
    We work on excel and csv which we import externally. As they are heavy if we directly try to upsert its very slow and will go at row level so we create a raw table where we dump all data and upsert using joins in raw query this is almost 10x faster as measured. In raw table delete many will not set auto increment id back to 0 and delete many is slow as compared to truncate.

  20. dave-addition commented on Aug 21, 2024

    @dave-addition

    Question to everyone who 👍 or commented here:

    What would be your use cases to want to fully truncate a table in an environment that uses Prisma Client?

    We'd use this to clear tables in the beforeEach & afterEach blocks of our integration tests (more efficiently than deleteMany() would, as noted by #5063 (comment)).

    Definitely not a big deal, but it's a nice-to-have.

  21. Tobbe commented on Aug 24, 2024

    @Tobbe

    This worked for me with sqlite to truncate the table and reset the auto increment counter

    await prisma.$queryRaw`DELETE FROM "MyTableName";`
    await prisma.$queryRaw`DELETE FROM sqlite_sequence WHERE name="MyTableName";`
  22. Karl-Styner commented on Sep 3, 2024

    @Karl-Styner

    This worked for me with sqlite to truncate the table and reset the auto increment counter

    await prisma.$queryRaw`DELETE FROM "MyTableName";`
    await prisma.$queryRaw`DELETE FROM sqlite_sequence WHERE name="MyTableName";`

    Almost everyone knows that raw queries can be used. But if you were to do that, why would you use ORM when you could just use raw queries for all the features?

  23. akbatra567 commented on Nov 25, 2024

    @akbatra567

    Found a new Issue created around this as well : #24744

  24. mba8487143 commented on Jan 16, 2025

    @mba8487143

    Here is the solution that worked for me for PostgreSQL.

    `async truncate(tableName) {
    try {

      // Replace TRUNCATE with DELETE if truncation is unsupported
      await prisma.$queryRawUnsafe(`TRUNCATE TABLE "${tableName}" RESTART IDENTITY CASCADE;`);
      console.log(`Table "${tableName}" truncated successfully.`);
    } catch (error) {
      console.error(`Error truncating table "${tableName}":`, error);
      throw error;
    }
    

    }`

    And Here is my environment.

    • prisma : 5.22.0
    • @prisma/client : 5.22.0
    • Node.js : v22.11.0
  25. Strae commented on Feb 19, 2026

    @Strae

    So, are there any plans to implement this? I know $query/executeRaw will works but this mean we must hardcode the table name in the sql, bypassing all the logic and ts validation from the prisma schema making our code more prone to "bad errors" (the ones hard to catch with tests and usually spotted directly in production after something break)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/featuretopic: client api

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions