Example 1
Example 1
If you want to count the number of unique values in a specific column, say EmployeeID, you can use:
FROM Employee;
If you want to count the unique combinations of values in multiple columns (e.g., EmployeeID and
Salary), you can use:
FROM Employee;
Explanation:
COUNT(DISTINCT column_name): This counts the number of distinct (unique) values in the
specified column.
If you use multiple columns inside COUNT(DISTINCT ...), it will count unique combinations of
the values from those columns.
SELECT COUNT(*)
Order_id CUSTOMER_id
1 101
2 102
3 101
4 103
5 102
6 102
from Orders
Group by Customer_id
Having count(order_id)>=3
UPDATE SYNTAX
UPDATE table_name
WHERE condition;
Suppose you want to update the salary of employees in Department 3 who are older than 30:
UPDATE Employee
------------------------------------------------------------------------------------------------
set different salary increases based on performance ratings, you can use the CASE statement within
the SET clause.
UPDATE Employee
ELSE Salary
END;
---------------------------------------------------------------------------------------------------
set the salary of employees based on the average salary in their department:
UPDATE Employee e SET e.Salary = ( SELECT AVG(Salary) FROM Employee WHERE DepartmentID =
e.DepartmentID ) WHERE e.DepartmentID IN (1, 2);
------------------------------------------------------------------------------------------------------
UPDATE Employee
WHERE DepartmentID = 3;
Example 1: BEFORE INSERT Trigger
Let's say you want to check the age of an employee before inserting the record to make sure the age
is valid (e.g., must be greater than or equal to 18).
BEGIN
END IF;
END;
NEW.Age: Refers to the value that is about to be inserted into the Age column.
SIGNAL SQLSTATE: Raises an error if the condition is not met, preventing the insertion.
This trigger will prevent the insertion if the employee's age is below 18.
Suppose you want to log the details of any new employee that has been inserted into the Employee
table. You can create an AFTER INSERT trigger to insert a log record into a separate Employee_Log
table.
BEGIN
END;
NEW.EmployeeID: Refers to the value that was just inserted into the EmployeeID column.
This trigger logs the insertion of a new employee into the Employee_Log table after the record has
been successfully inserted.
BEGIN
END IF;
END;
This trigger prevents the salary from being decreased by raising an error if the new salary is less than
the old salary.
You can use an AFTER DELETE trigger to, for example, log the deletion of an employee into an
Employee_Delete_Log table after the employee record is deleted.
BEGIN
END;
OLD.EmployeeID: Refers to the value of the EmployeeID column before the deletion.
This trigger logs the deleted employee’s information after the employee record is deleted from the
Employee table.
BEGIN
END IF;
END;