alter and update
alter and update
ALTER Statement
The ALTER statement is used to modify an existing database table structure. You can add, delete, or
modify columns in an existing table.
2. UPDATE Statement
UPDATE Employees
SET Salary = 70000.00
WHERE EmployeeID = 2;
UPDATE Employees
SET Salary = Salary * 1.10;
3. DELETE Statement
Dropping a Column
To delete all records from the Employees table (but keep the table structure):
(Note: TRUNCATE is faster but less flexible compared to DELETE. TRUNCATE also resets any auto-
increment counters.)
Summary
We'll enhance the Employees table by adding constraints, renaming columns, and modifying
multiple columns.
Suppose we want to add a unique constraint on the Email column and rename the Position column
to JobTitle.
We want to link the Employees table to the Departments table via a foreign key.
Suppose we have a table Bonuses that records bonus percentages for different job titles.
Update the Salary in the Employees table based on the BonusPercentage from the Bonuses table.
UPDATE Employees
SET Salary = Salary + (Salary * BonusPercentage / 100)
FROM Employees e
JOIN Bonuses b ON e.JobTitle = b.JobTitle;
UPDATE Employees
SET DepartmentID = (
SELECT TOP 1 DepartmentID
FROM Employees AS e
GROUP BY DepartmentID
ORDER BY AVG(Salary) DESC
);
Assume we have another table Projects that lists projects employees are working on.
DELETE e
FROM Employees e
LEFT JOIN Projects p ON e.EmployeeID = p.EmployeeID
WHERE p.EmployeeID IS NULL;
ALTER: Added constraints, renamed columns, and added foreign key relationships.
UPDATE: Updated records using joins and subqueries.
DELETE: Deleted records using joins and subqueries