SQL Statements
DROP statement
Overview
In this section, we will learn how to delete the data from a table using the DROP
statement.
Running a
DROP
statement will also delete all existing records from the table.Syntax
The basic syntax for the DROP
statement is as follows:
In this syntax:
table_name
defines which table you want to remove.IF EXISTS
is an optional parameter used to ensure no error occurs if the table does not exist.
The
DROP
example below is executed in the public
schema. You can also drop a table from another specific schema. Click here for more info.Examples
Case #1: Dropping the Table
- Use the following query to create the table.
- We can then use the SELECT statement to view the data in the table:
It will generate the following result:
- To delete the warehouse table and all its data, we can use the following query:
- If the query is executed successfully, we will get the following output:
If you attempt to use the table for any operation, you will find that the table no longer exists.
Case #2: Dropping the Table using IF EXISTS
IF EXISTS can be used to prevent errors when dropping the table if the table does not exist.
Example without IF EXISTS
- First, drop the table without using the
IF EXISTS
option.
Output:
- If you attempt to drop the table again without using IF EXISTS, it will result in an error.
Output:
Example with IF EXISTS
Now, drop the table using the IF EXISTS.
The drop operation proceeds without errors even if the table doesn’t exist.