Example of SQL Server DELETE and DROP TABLE Commands
Let’s start by creating a sample products table in SQL Server and then performing the DELETE and DROP TABLE tasks.
-- Create the products table
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(100),
price DECIMAL(10, 2),
quantity INT
);
-- Insert sample data into the products table
INSERT INTO products (product_id, product_name, price, quantity)
VALUES
(1, 'Laptop', 999.99, 10),
(2, 'Smartphone', 699.99, 20),
(3, 'Tablet', 399.99, 15),
(4, 'Headphones', 99.99, 30);
product_id | product_name | price | quantity |
---|---|---|---|
1 | Laptop | 999.99 | 10 |
2 | Smartphone | 699.99 | 20 |
3 | Tablet | 399.99 | 15 |
4 | Headphones | 99.99 | 30 |
This SQL script creates a products table with columns for product_id, product_name, price, and quantity, and inserts some sample data into the table.
Example Using the DELETE Command
-- Delete all products with a price less than 500
DELETE FROM products
WHERE price < 500;
Output:
product_id | product_name | price | quantity |
---|---|---|---|
1 | Laptop | 999.99 | 10 |
2 | Smartphone | 699.99 | 20 |
In this example, the DELETE command removes all rows from the orders table where the total_amount column is less than 500.
Example Using the DROP TABLE Command
-- Drop the products table
DROP TABLE products;
In this example, the DROP TABLE command deletes the products table from the database, including all its columns and data.
SQL Server DELETE and DROP TABLE Commands
In SQL Server, managing data involves not only inserting and updating records but also removing them when they’re no longer needed. Two important commands for data removal are DELETE and DROP TABLE. These commands play crucial roles in maintaining database integrity and managing database structures.
In this article, we’ll learn about the DELETE and DROP TABLE commands in SQL Server, exploring their syntax, use cases, and so on.