Introducing Chaos Genius for Databricks Cost Optimization

Get started

HOW TO: Clear Table Data with Snowflake TRUNCATE TABLE (2024)

TRUNCATE TABLE is a really powerful command that's used in a lot of different database systems. It gets the job done fast—wiping out all the table data without actually deleting the table and keeping the structure of the table intact. This comes in handy when you need to reset a table's data without messing with its schema, constraints, or other behind-the-scenes stuff. Snowflake takes the classic TRUNCATE TABLE command and adds some cool features to make it even more useful and efficient.

In this article, we're going to deep dive into every nook and cranny of the Snowflake TRUNCATE TABLE command. We'll cover its syntax, what it does, how to use it, and why you might choose it over other options like Snowflake DELETE or Snowflake DROP. Plus, we'll also walk you through the process step-by-step, and share some tips and best practices.

What Does TRUNCATE TABLE Do in Snowflake?

Snowflake TRUNCATE TABLE command is designed to wipe out all the data in a table without getting rid of the table itself. This way, the table's structure stays intact—we're talking schemas, constraints, and privileges—making it perfect for resetting table data without messing with the setup.

But here's where it gets interesting. Snowflake TRUNCATE TABLE is particularly useful in development and testing environments where data needs to be reset frequently. It's way faster than Snowflake DELETE, which can take forever on large tables. That's because Snowflake TRUNCATE TABLE doesn't bother with individual rows—it just wipes the whole table clean.

Also note that Snowflake TRUNCATE TABLE is different from Snowflake DROP TABLE—TRUNCATE TABLE deletes all data but keeps the table structure, while DROP TABLE removes the table completely but retains a version for possible recovery, including its load history.

Remember, though, that Snowflake TRUNCATE TABLE is a powerful command. It's irreversible (well, mostly—we'll talk about Time Travel later), so you want to be absolutely sure you want to remove all the data before you use it.

Syntax and Basic Usage of Snowflake TRUNCATE TABLE

Now that we understand what Snowflake TRUNCATE TABLE does, let's look at how to actually use it in Snowflake.

Basic Syntax

The basic syntax is straightforward:

TRUNCATE [ TABLE ] [ IF EXISTS ] <table_name>;
Snowflake TRUNCATE Table syntax

Let's break this down:

Parameter

  • TRUNCATE TABLE: This is the main command. It tells Snowflake that you want to remove all rows from a table.
  • IF EXISTS (optional): This clause prevents errors by only attempting to truncate the table if it already exists.
  • <table_name>: This is where you specify the name of the table you want to truncate.

Want to take Chaos Genius for a spin?

It takes less than 5 minutes.

Enter your work email
Enter your work email
Snowflake Logo

What Is the Difference Between TRUNCATE and DROP in Snowflake?

Now, you might be thinking, hold up, if Snowflake TRUNCATE TABLE gets rid of everything, isn't it just like Snowflake DROP? Not exactly. Sure, they both end up with an empty table, but the way they get there is totally different.

Let's break it down in a table:

Snowflake TRUNCATE TABLE Snowflake DROP TABLE
Snowflake TRUNCATE TABLE removes all rows from a table while retaining the table structure, including columns, privileges, and constraints. Snowflake DROP TABLE removes the table and its structure, including all data, columns, and constraints.
Snowflake TRUNCATE TABLE is faster than Snowflake DELETE as it does not log individual row deletions and does not scan each row. Snowflake DROP TABLE is generally quick but depends on the existence of foreign key references and the table's size.
Snowflake TRUNCATE TABLE deletes all rows but does not log individual row deletions. Snowflake DROP TABLE deletes the entire table and all its data.
Snowflake TRUNCATE TABLE resets any auto-increment counters (e.g., IDENTITY columns) to their starting values. Snowflake DROP TABLE does not have auto-increment counters since the entire table is removed.
Rows deleted by Snowflake TRUNCATE TABLE can be recovered using Time Travel within the retention period. The table can be recovered using the UNDROP TABLE command within the Time Travel retention period.
Snowflake TRUNCATE TABLE cannot truncate a table that is referenced by a foreign key constraint. Snowflake DROP TABLE can drop a table even if it is referenced by foreign keys (using CASCADE).
Snowflake TRUNCATE TABLE requires “TRUNCATE” privilege. Snowflake DROP TABLE requires “DROP” privilege.
Snowflake TRUNCATE TABLE triggers are not activated by this operation. Snowflake DROP TABLE triggers are not activated by this operation.
Snowflake TRUNCATE TABLE is useful for quickly deleting all data in a table without removing the table itself, often used in ETL processes where table structure needs to be preserved. Snowflake DROP TABLE is used when the table itself needs to be removed entirely, such as when cleaning up the database or when the table is no longer needed.
Syntax: TRUNCATE TABLE [IF EXISTS] <table_name> Syntax: DROP TABLE [IF EXISTS] <table_name>

What Is the Difference Between TRUNCATE and DELETE in Snowflake?

Alright, we've covered Snowflake TRUNCATE TABLE vs DROP TABLE, but what about Snowflake TRUNCATE TABLE vs Snowflake DELETE? These two are often confused because they both remove data from a table. But they work quite differently, especially in Snowflake.

Let's compare them:

Snowflake TRUNCATE TABLE Snowflake DELETE
Snowflake TRUNCATE TABLE removes all rows from a table but preserves the table structure. Snowflake DELETE removes specific rows based on the condition specified in the WHERE clause.
Snowflake TRUNCATE TABLE is generally faster because it deallocates data pages instead of scanning individual rows. Snowflake DELETE processes rows individually, which can be slower for large tables.
Snowflake TRUNCATE TABLE does not allow the use of a WHERE clause; it affects all rows in the table. Snowflake DELETE allows the use of a WHERE clause to specify which rows to remove.
Snowflake TRUNCATE TABLE retains the table structure, constraints, and privileges after execution. Snowflake DELETE also retains the table structure, constraints, and privileges after execution.
Snowflake TRUNCATE TABLE does not reset AUTO_INCREMENT counters, which can affect the data model. Snowflake DELETE also does not reset AUTO_INCREMENT counters.
Snowflake TRUNCATE TABLE deletes metadata. Snowflake DELETE does not delete metadata.
Snowflake TRUNCATE TABLE operations can be rolled back. Snowflake DELETE operations can also be rolled back.
Snowflake TRUNCATE TABLE is useful for quickly removing all data in a table, often in development or testing scenarios. Snowflake DELETE is useful for removing specific rows based on conditions, allowing for more granular data management.
Syntax: TRUNCATE TABLE my_table; Syntax: DELETE FROM my_table WHERE condition;

Step-by-Step Guide: How to TRUNCATE TABLE in Snowflake

Now that we've covered the theory, let's get practical. Here's a step-by-step guide on how to use TRUNCATE TABLE in Snowflake:

Step 1—Login, Navigate to Worksheet, Select Database and Schema

First things first, you need to log into your Snowflake account and open a worksheet. Once you're in, make sure you're in the right context by selecting the database and schema where your table lives.

USE DATABASE <your_database>;
USE SCHEMA <your_schema>;
Selecting Database and Schema

Or create a new one.

CREATE DATABASE <your_new_database>;
USE DATABASE <your_new_database>;

CREATE SCHEMA <your_new_schema>;
USE SCHEMA <your_new_schema>;
Creating Database and Schema

Step 2—Create a Table and Insert Sample Data (or Select the Table to TRUNCATE)

If you're just testing things out, you might want to create a sample table and populate it with some data. Here's an example:

CREATE TABLE top_billionaires (
    id INT,
    name STRING,
    created_date DATE
);
Creating Table and inserting sample data
Creating a Table and inserting sample data -  Snowflake TRUNCATE TABLE - Snowflake TRUNCATE - Truncate Table in Snowflake - Snowflake DROP TABLE - Snowflake DELETE
Creating a Table and inserting sample data - Snowflake TRUNCATE Table
INSERT INTO top_billionaires VALUES
(1, 'Elon', CURRENT_DATE()),
(2, 'Mark', CURRENT_DATE()),
(3, 'Jeff', CURRENT_DATE()),
(4, 'Bill', CURRENT_DATE()),
(5, 'Warren', CURRENT_DATE()),
(6, 'Larry', CURRENT_DATE()),
(7, 'Sergey', CURRENT_DATE()),
(8, 'Steve', CURRENT_DATE()),
(9, 'Mukesh', CURRENT_DATE()),
(10, 'Bernard', CURRENT_DATE());
Creating Table and inserting sample data - Snowflake TRUNCATE Table
Creating a Table and inserting sample data - Snowflake TRUNCATE Table - Snowflake TRUNCATE - Truncate Table in Snowflake - Snowflake DROP TABLE - Snowflake DELETE
Creating a Table and inserting sample data - Snowflake TRUNCATE Table

If you're working with an existing table, you can skip this step.

Step 3—Verify Table Existence

Before we truncate, let's make sure our table exists and has data:

SHOW TABLES LIKE 'top_billionaires';
Verifying table existence
Verifying table existence using ‘SHOW TABLES’ - Snowflake TRUNCATE TABLE - Snowflake TRUNCATE - Truncate Table in Snowflake - Snowflake DROP TABLE - Snowflake DELETE
Verifying table existence using ‘SHOW TABLES’ - Snowflake TRUNCATE Table

This command will show you details about the table if it exists.

Step 4—Check Table Data

Let's take a look at the data in our table:

SELECT * FROM top_billionaires;
Checking table data
Checking table data - Snowflake TRUNCATE TABLE - Snowflake TRUNCATE - Truncate Table in Snowflake - Snowflake DROP TABLE - Snowflake DELETE
Checking table data - Snowflake TRUNCATE Table

This will show you all the rows currently in the table.

Step 5—Truncate the Table Using Snowflake TRUNCATE TABLE Command

Now for the main event! Let's truncate the table in Snowflake using Snowflake TRUNCATE TABLE command :

TRUNCATE TABLE top_billionaires;
Truncating table using Snowflake TRUNCATE TABLE Command
Truncating table using Snowflake TRUNCATE TABLE Command - Snowflake TRUNCATE TABLE - Snowflake TRUNCATE - Truncate Table in Snowflake - Snowflake DROP TABLE - Snowflake DELETE
Truncating table using Snowflake TRUNCATE TABLE Command

As you can see, this command will remove all the data from top_billionaires.

Step 6—Conditional Table Truncate with Snowflake TRUNCATE TABLE [IF EXISTS]

If you're not sure whether the table exists, you can use the IF EXISTS clause to avoid errors:

TRUNCATE TABLE IF EXISTS top_billionaires;
Truncating table using Snowflake TRUNCATE TABLE Command
Truncating table using Snowflake TRUNCATE TABLE Command - Snowflake TRUNCATE TABLE - Snowflake TRUNCATE - Truncate Table in Snowflake - Snowflake DROP TABLE - Snowflake DELETE
Truncating table using Snowflake TRUNCATE TABLE Command

This command will truncate the table if it exists, and do nothing (without throwing an error) if it doesn't.

Step 7—Confirm the Table is Empty (Verify Truncation)

After truncating, it's a good idea to verify that the table is indeed empty:

SELECT COUNT(*) FROM top_billionaires;
Confirming if the Table is Empty - Snowflake TRUNCATE TABLE - Snowflake TRUNCATE - Truncate Table in Snowflake - Snowflake DROP TABLE - Snowflake DELETE
Confirming if the Table is Empty

This should return 0 if the truncate operation was successful.

Optional—Rollback Data with Time Travel (if necessary)

If you need to recover the truncated data, utilize the Snowflake Time Travel feature. However, note that load metadata cannot be recovered:

First—Identify the Query ID

Make sure you have the correct query ID before which you want to recover the data. To find this:

  • Navigate to the Query History in the Snowflake web interface.
  • Hover over the relevant query to see its details.
  • Note down the Query ID you need for the recovery.

For example, this is our query ID “01b5e234-0206-8ed7-0007-2a4b00029096”.

Retrieving Snowflake Query ID

Second—Clone the Table Using Time Travel with BEFORE Clause

Create a new table that contains the data from just before the specified query was executed.

CREATE TABLE top_billionaires_recovered CLONE top_billionaires BEFORE (STATEMENT => '01b5e234-0206-8ed7-0007-2a4b00029096');
Cloning table using Snowflake time travel
Cloning table using Snowflake time travel - Snowflake TRUNCATE Table

Third—Verify the Recovered Data

Check the contents of the recovered table to ensure it has the correct data.

SELECT * FROM top_billionaires_recovered;
Verifying the recovered data
Verifying the recovered data - Snowflake TRUNCATE Table
Verifying the recovered data - Snowflake TRUNCATE Table

Fourth—Merge Recovered Data Back into the Original Table

If the recovered data is correct, you can merge it back into the original table.

INSERT INTO top_billionaires
SELECT * FROM top_billionaires_recovered
WHERE NOT EXISTS (
    SELECT 1
    FROM top_billionaires
    WHERE top_billionaires_recovered.id = top_billionaires.id
);
Merging recovered data back to the original table
Merging recovered data back to the original table - Snowflake TRUNCATE TABLE - Snowflake TRUNCATE - Truncate Table in Snowflake - Snowflake DROP TABLE - Snowflake DELETE
Merging recovered data back to the original table - Snowflake TRUNCATE Table

Fifth—Clean Up (Optional)

If you no longer need the recovered table, you can drop it.

DROP TABLE top_billionaires_recovered;
Dropping recovered table
Dropping recovered table - Snowflake TRUNCATE TABLE - Snowflake TRUNCATE - Truncate Table in Snowflake - Snowflake DROP TABLE - Snowflake DELETE
Dropping recovered table - Snowflake TRUNCATE Table

Boom! That's how you fix a truncated table in Snowflake. If you truncate a table by mistake, don't panic. Just follow these above steps and you'll have it back in a flash.

Snowflake TRUNCATE TABLE—Considerations and Best Practices

Now that you know how to use Snowflake TRUNCATE TABLE, let's talk about when and how to use it responsibly. Here are some best practices and considerations:

1) Use in Development and Testing Environments

Snowflake TRUNCATE TABLE is perfect for resetting test data or clearing out development environments. It's fast and efficient, making it ideal for these scenarios where you often need to start fresh.

2) Avoid in Production Unless Necessary

Be very careful about using TRUNCATE TABLE in production environments. Because it's so fast and irreversible (except for Time Travel), it's easy to accidentally wipe out important data. Always make sure to double-check that you're truncating the right table!

3) Always Make Sure to Backup and Use Time Travel for Recovery

Before performing a Snowflake TRUNCATE TABLE operation, make sure you have a recent backup. Snowflake Time Travel feature is also a great safety net, but remember it has time limitations.

4) Setting Up Alerts for TRUNCATE TABLE Operations

Set up alerts to keep an eye on Snowflake TRUNCATE TABLE commands. This way, you'll know when someone runs one of these commands, and you can make sure it's only when needed and by people who have permission.

5) Restrict TRUNCATE TABLE Permissions

Limit permissions for executing the Snowflake TRUNCATE TABLE command to prevent accidental data loss. Ensure that only authorized users have the necessary privileges.

6) Consider using DELETE for partial data removal

If you only need to remove some of the data in a table, DELETE is usually a better choice than Snowflake TRUNCATE TABLE.

7) Leverage clone and Time Travel for safe testing

If you need to test a Snowflake TRUNCATE TABLE operation, consider cloning the table first or using Time Travel to create a point-in-time copy. This allows you to test safely without risking your actual data.

Want to Learn More?

If you want to get more info about Snowflake TRUNCATE TABLE and related Snowflake features, here are some great resources:

Save up to 30% on your Snowflake spend in a few minutes!

Enter your work email
Enter your work email
Snowflake Background Snowflake Background

Conclusion

And that's a wrap! Now you know the Snowflake TRUNCATE TABLE command, which is super handy for wiping a table clean without messing up its structure. To use it like a pro, you need to know the basics when to use it, and some smart tips. Just remember to play it super safe—backup your data and limit who can use the command, so you don't lose anything important by mistake.

In this article, we have covered:

  • What does TRUNCATE TABLE do in Snowflake?
  • Differences between TRUNCATE and DROP in Snowflake
  • Differences between TRUNCATE and DELETE in Snowflake
  • Step-by-step guide: How to TRUNCATE TABLE in Snowflake
  • Snowflake TRUNCATE TABLE—Considerations and best practices

…and more!

FAQs

What does the TRUNCATE TABLE command do in Snowflake?

Snowflake TRUNCATE TABLE removes all data/record  from a table but retains the table's structure, including all schemas, privileges, and constraints​.

How is the Snowflake TRUNCATE TABLE different from Snowflake DROP TABLE?

Snowflake TRUNCATE TABLE removes all rows but keeps the table structure intact, while DROP TABLE deletes the table and its metadata completely​.

Can you use a Snowflake TRUNCATE TABLE on a table with foreign key constraints?

No, Snowflake TRUNCATE TABLE cannot be used on tables that are referenced by foreign key constraints​.

Does Snowflake TRUNCATE TABLE affect auto-increment counters?

No, Snowflake TRUNCATE TABLE does not reset the auto-increment counters in Snowflake

Can Snowflake TRUNCATE TABLE be rolled back in a transaction?

Yes, if used within a transaction, Snowflake TRUNCATE TABLE can be rolled back.

What happens to the load metadata when a table is truncated?

The load metadata is deleted, which allows the same files to be reloaded into the table without conflicts.

Is Snowflake TRUNCATE TABLE faster than Snowflake DELETE for large tables?

Yes, Snowflake TRUNCATE TABLE is generally faster because it does not scan the table to apply row-level deletions​.

Can you use the IF EXISTS clause with TRUNCATE TABLE?

Yes, the IF EXISTS clause prevents errors by truncating the table only if it exists​​.

How does Snowflake TRUNCATE TABLE impact Time Travel?

While the data is removed, it can still be accessed using Time Travel until the data retention period expires​.

Can TRUNCATE TABLE be used on external tables?

No, Snowflake TRUNCATE TABLE cannot be used on external tables​.

Does Snowflake TRUNCATE TABLE generate undo logs?

No, Snowflake TRUNCATE TABLE does not generate undo logs, making it faster than DELETE​.

Can Snowflake TRUNCATE TABLE be used on a table with triggers?

No, TRUNCATE TABLE cannot be used on tables that have triggers associated with them​​.

What is a common use case for TRUNCATE TABLE?

It is often used to reset a table in development or testing environments without altering its structure.

Does TRUNCATE TABLE remove table partitions?

No, it does not remove partitions; it only removes the data within the partitions.

Pramit Marattha

Technical Content Lead

Pramit is a Technical Content Lead at Chaos Genius.

People who are also involved

“Chaos Genius has been a game-changer for our DataOps at NetApp. Thanks to the precise recommendations, intuitive interface and predictive capabilities, we were able to lower our Snowflake costs by 28%, yielding us a 20X ROI

Chaos Genius has given us a much better understanding of what's driving up our data-cloud bill. It's user-friendly, pays for itself quickly, and monitors costs daily while instantly alerting us to any usage anomalies.

Anju Mohan

Director, IT

Simon Esprit

Chief Technology Officer

Join today to get upto
30% Snowflake
savings

Join today to get upto 30% Snowflake savings

Unlock Snowflake Savings Join waitlist
Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.