You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Truncate table with Prisma Client like prisma.account.truncate() #5063
I want to delete all the data in a given table. In order to do that, I have to do something like this:
awaitprisma.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
awaitprisma.account.truncate()
Alternatives
Using
awaitprisma.account.deleteMany({where: {}})
or raw SQL queries.
Reacted by Matt Lim, Anthony Garcia, qsona, Kai Rollmann, Carlos Florêncio, Takahashi, Marouane Fazouane, Gonzalo Tixilima, andrewtheskills, kangsan Kim and 47 more
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 pushfor(const{ tablename }ofawaitthis.prisma.$queryRaw(`SELECT tablename FROM pg_tables WHERE schemaname='${this.dbSchemaName}'`)){awaitthis.prisma.$queryRaw(`TRUNCATE TABLE \"${this.dbSchemaName}\".\"${tablename}\" CASCADE;`);}for(const{ relname }ofawaitthis.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}';`)){awaitthis.prisma.$queryRaw(`ALTER SEQUENCE \"${this.dbSchemaName}\".\"${relname}\" RESTART WITH 1;`);}
Reacted by Boštjan Biber
Reacted by Pablo Leone, Sean Anderson, Suhadak Akbar, Unintended, Tim Samuel and GermanoB
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
Reacted by Josh Strobel, WayneEllery, Will Tachau and Cory Logan
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.
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.
deleteMany function is slower than truncate query.
deleteMany is not following reset incremental index.
why is not first priority..?
Reacted by jdion84, Pavel Baranov, devon-pl, Claudio Bredfeldt, Mario Montano, Yevgeny Medvedev, Zoltán Lehoczky, electrovir, Mateusz Anioła, Andrea and 2 more
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.
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.
This worked for me with sqlite to truncate the table and reset the auto increment counter
awaitprisma.$queryRaw`DELETE FROM "MyTableName";`awaitprisma.$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?
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)
Activity
Jolg42 commentedon Mar 24, 2021
As a potential workaround, here is an example of doing a truncate on PostgreSQL manually using $queryRaw
Copied from #742 (comment)
arenddeboer commentedon Jul 3, 2021
Another + for truncate is that it will free up data, at least on PostgreSQL. A
deleteMany({where: {}})will not.timvandam commentedon Jul 10, 2021
This would be great to have.
deleteManyuses two queries: one that determines which rows to delete, and one that does the actual deleting. This is much slower than a good oldTRUNCATE TABLE.A
truncate()method that usesTRUNCATE TABLEwould be more idealJolg42 commentedon Jul 13, 2021
@timvandam Note: an issue was created recently for the
deleteManyoptimisation hereEdit: that is now optimized since
5.4.0calidion commentedon Oct 7, 2023
how is this issue going?
Jolg42 commentedon Oct 9, 2023
@calidion There is no news about this issue.
Though, there is good news about
deleteMany()🎊[-]Truncate table[/-][+]Truncate table with Prisma Client like `prisma.account.truncate()`[/+]calidion commentedon Oct 10, 2023
@Jolg42
It is confusing that is feature is so hard to be realized.
janpio commentedon Oct 12, 2023
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 remaining item
janpio commentedon Oct 13, 2023
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)
Karl-Styner commentedon Nov 10, 2023
why is not first priority..?
ilyaskarim commentedon Jun 11, 2024
Is there any updates on this?
janpio commentedon Jun 11, 2024
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?
dahaupt commentedon Jun 12, 2024
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
deleteManyas the auto-incrementedidis not relevant within our business logic.ilyaskarim commentedon Jun 12, 2024
@dahaupt Yes
idincrement was not an issue for us too so I decided to write a script to truncate tables.kshitijkurandwad211 commentedon Jul 16, 2024
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.
dave-addition commentedon Aug 21, 2024
We'd use this to clear tables in the
beforeEach&afterEachblocks of our integration tests (more efficiently thandeleteMany()would, as noted by #5063 (comment)).Definitely not a big deal, but it's a nice-to-have.
Tobbe commentedon Aug 24, 2024
This worked for me with sqlite to truncate the table and reset the auto increment counter
Karl-Styner commentedon Sep 3, 2024
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?
akbatra567 commentedon Nov 25, 2024
Found a new Issue created around this as well : #24744
mba8487143 commentedon Jan 16, 2025
Here is the solution that worked for me for PostgreSQL.
`async truncate(tableName) {
try {
}`
And Here is my environment.
Strae commentedon Feb 19, 2026
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)