SQL DELETE FROM TABLE
SQL DELETE FROM Statement
The SQL DELETE FROM
statement is used to remove rows from an existing table. You can specify which rows to delete by using the WHERE
clause. If no condition is specified, all rows in the table will be deleted.
Syntax
DELETE FROM table_name
WHERE condition;
DELETE FROM
: This is the SQL keyword used to delete rows from a table.table_name
: This specifies the name of the table from which you want to delete rows.condition
: This specifies the condition that determines which rows 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 deleting specific rows from 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: Deleting Rows from the Table
This step involves deleting specific rows from the employees
table based on a condition.
DELETE FROM employees
WHERE last_name = 'Doe';
This command will delete all rows from the employees
table where the last_name
is 'Doe'.
If you want to delete all rows from the table, you can use the following command:
DELETE FROM employees;
This command will delete all rows from the employees
table, leaving it empty but still retaining its structure.