SQL provides several Data Manipulation Language (DML) commands to interact with and manipulate the data in a database. These commands include SELECT, INSERT, UPDATE, and DELETE. Below are the basic SQL commands for data manipulation, along with examples.
The SELECT statement is used to query data from one or more tables. You can specify the columns you want to retrieve, apply filters, and sort the results.
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column1 ASC|DESC;
Retrieve the first name and last name of employees who were hired after 2020.
SELECT FirstName, LastName
FROM Employees
WHERE HireDate > '2020-01-01'
ORDER BY LastName ASC;
The INSERT statement is used to add new rows of data into a table. You can insert values for all columns or only specific columns.
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
Add a new employee record.
INSERT INTO Employees (EmployeeID, FirstName, LastName, HireDate, DepartmentID)
VALUES (1, 'John', 'Doe', '2023-05-10', 101);
INSERT INTO table_name
VALUES (value1, value2, ...);
Insert data for specific columns only (e.g., ignoring DepartmentID).
INSERT INTO Employees (EmployeeID, FirstName, LastName, HireDate)
VALUES (2, 'Jane', 'Smith', '2023-06-15');
The UPDATE statement is used to modify existing records in a table. You can update one or multiple columns, and the WHERE clause specifies which rows should be updated.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Update the hire date of an employee with EmployeeID = 1.
UPDATE Employees
SET HireDate = '2024-01-01'
WHERE EmployeeID = 1;
Always include the WHERE clause when using UPDATE to avoid modifying all rows in the table unintentionally.
The DELETE statement is used to remove one or more rows from a table based on a condition.
DELETE FROM table_name
WHERE condition;
Delete an employee record with EmployeeID = 2.
DELETE FROM Employees
WHERE EmployeeID = 2;
The TRUNCATE command is used to quickly remove all rows from a table, but unlike DELETE, it cannot be rolled back (in most cases).
TRUNCATE TABLE table_name;
Remove all employee records from the table.
TRUNCATE TABLE Employees;
Example:
SELECT * FROM Employees WHERE DepartmentID = 101;
Example:
SELECT * FROM Employees ORDER BY HireDate DESC;
Example:
SELECT DepartmentID, COUNT(*) AS TotalEmployees
FROM Employees
GROUP BY DepartmentID;
Example:
SELECT DepartmentID, COUNT(*) AS TotalEmployees
FROM Employees
GROUP BY DepartmentID
HAVING COUNT(*) > 10;