Data Manipulation Language (DML) is a subset of SQL used to retrieve, insert, update, and delete data in a database. These commands are fundamental to interacting with and managing the data stored within your relational database systems.
SELECT
: Retrieving Data
The SELECT
statement is used to query the database and retrieve one or more records. It's the most frequently used DML statement.
SELECT * FROM Customers;
SELECT customer_name, email
FROM Customers
WHERE country = 'USA';
INSERT
: Adding New Data
The INSERT
statement is used to add new records (rows) into a table.
INSERT INTO Customers (customer_name, email, country)
VALUES ('John Doe', 'john.doe@example.com', 'Canada');
INSERT INTO Customers
VALUES ('Jane Smith', 'jane.smith@example.com', 'UK', '2023-01-15'); -- Assumes these are the columns and their order
UPDATE
: Modifying Existing Data
The UPDATE
statement is used to modify existing records in a table. You must use a WHERE
clause to specify which rows to update; otherwise, all rows will be updated.
UPDATE Customers
SET email = 'new.john.doe@example.com'
WHERE customer_name = 'John Doe';
UPDATE Customers
SET country = 'USA', last_contact_date = '2024-03-10'
WHERE customer_id = 101;
DELETE
: Removing Data
The DELETE
statement is used to remove records from a table. Like UPDATE
, a WHERE
clause is crucial to avoid deleting all records.
DELETE FROM Customers
WHERE customer_name = 'Jane Smith';
DELETE FROM Customers; -- Empties the table
WHERE
Clause: Always use the WHERE
clause with UPDATE
and DELETE
statements to target specific rows and prevent unintended data loss.TRUNCATE
vs. DELETE
: While both remove data, DELETE
removes rows one by one and can be rolled back. TRUNCATE
is a DDL command that removes all rows quickly and cannot be rolled back easily (depending on the RDBMS).DML statements often include clauses that refine the operation:
WHERE
: Filters records based on specified conditions.ORDER BY
: Sorts the result set of a SELECT
statement.GROUP BY
: Groups rows that have the same values in specified columns into summary rows.HAVING
: Filters groups created by the GROUP BY
clause.JOIN
: Combines rows from two or more tables based on a related column.LIMIT
/ TOP
: Restricts the number of rows returned by a SELECT
statement.Understanding and effectively using SQL DML statements is crucial for any developer or database administrator working with relational databases.