SQL DROP TABLE



SQL DROP TABLE Statement

The SQL DROP TABLE statement is used to delete an existing table from a database. When you drop a table, all the data in the table and the table structure are permanently removed. This operation cannot be rolled back, so use it with caution.


Syntax

DROP TABLE table_name;
  • DROP TABLE: This is the SQL keyword used to delete a table.
  • table_name: This specifies the name of the table you want to delete.

Example

Let's go through a complete example that includes creating a database, creating a table, inserting data into the table, and then dropping the table.

Step 1: Creating a Database

This step involves creating a new database where the table will be stored.

CREATE DATABASE example_db;

In this example, we create a database named example_db.

Step 2: Creating a Table

In this step, we create a table named employees within the previously created database.

USE example_db;

CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    email VARCHAR(100),
    hire_date DATE
);

Here, we define the employees table with columns for id, first_name, last_name, email, and hire_date. The id column is set as the primary key and will auto-increment.

Step 3: Inserting Data into the Table

This step involves inserting some sample data into the employees table.

INSERT INTO employees (first_name, last_name, email, hire_date) VALUES ('John', 'Doe', 'john.doe@example.com', '2023-01-01');
INSERT INTO employees (first_name, last_name, email, hire_date) VALUES ('Jane', 'Smith', 'jane.smith@example.com', '2023-02-01');

Here, we insert two rows of data into the employees table.

Step 4: Dropping the Table

This step involves deleting the employees table from the database.

DROP TABLE employees;

This command will delete the employees table and all of its data from the example_db database.