Unit_4 DBMS
Unit_4 DBMS
DDL Commands
● DECIMAL(p,s) or NUMERIC(p,s): Exact numeric values with precision p and scale s. Useful for
storing monetary values.
Example: Salary DECIMAL(10, 2);
Example:
CREATE TABLE Orders (
CustomerName VARCHAR(100),
● Data Type: The basic type of the column (e.g., integer, varchar, etc.)
● Range of Values: The permissible range of values (e.g., Age could be between
0 and 120).
● Format: For example, a column storing emails could specify that the values
must follow the email format.
1. NOT NULL Constraint: The NOT NULL constraint ensures that a column cannot
have a NULL value. This is useful when a column must always contain a valid
value.
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, FirstName
VARCHAR(100) NOT NULL, LastName VARCHAR(100) NOT NULL);
UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are unique across
the table.
Unlike the PRIMARY KEY, a column can accept NULL values, but all
non-NULL values must be unique.
Example:
Example:
The FOREIGN KEY constraint establishes a link between columns in two tables.
It ensures that the value in the foreign key column matches one of the values in the
referenced table’s primary key or unique key.
Example:
The CHECK constraint ensures that all values in a column satisfy a specified
condition.
Example:
The DEFAULT constraint provides a default value for a column when no value is
specified during record insertion. If no value is provided for the column, the
default value is inserted automatically.
Example:
The index doesn’t enforce data integrity like other constraints but improves
performance.
Example:
Example:
A composite key is a primary key composed of two or more columns. The combined
values in the columns must be unique.
Example:
RENAME TABLE
TRUNCATE TABLE
ORDER BY Clause
UPDATE Statement
DISTINCT Keyword
UPDATE products p
JOIN suppliers s ON p.supplier_id = s.id
SET p.price = p.price * 1.1 // price change
WHERE s.country = 'Germany'; // supplier country only Germany
Update with Subquery (Set VIP status based on total spend)
UPDATE customers
SET status = 'VIP'
WHERE id IN (
SELECT customer_id // Get customer IDs from orders and group
orders by customer, Only keep those with a total spend over 5000.
FROM orders GROUP BY customer_id HAVING
SUM(total_amount) > 5000);
Nested SELECT Queries
Subquery in the SELECT Clause: Subquery in the SELECT clause to return
calculated values or data derived from other tables.
SELECT name,
(SELECT AVG(salary) FROM employees WHERE department_id =d.id)
AS avg_salary FROM departments d;
This query calculates the average salary of each department and displays the
department name alongside it.
Subquery in the WHERE Clause (Correlated Subquery)
A correlated subquery refers to a subquery that uses values from the outer query. It’s
evaluated once for each row processed by the outer query.
This retrieves employees whose salary is greater than the average salary of
their department.
Subquery in the FROM Clause (Inline View)
A subquery can be used in the FROM clause to treat it like a temporary table.
This finds departments with total sales greater than 100,000 by first calculating
the total sales per department in a subquery.
Nested UPDATE Queries
You can use a nested query in an UPDATE statement to modify a field based on
values from another query.
UPDATE employees
SET salary = ( SELECT AVG(salary)
FROM employees WHERE department_id = 3)
WHERE department_id = 3;
Nested DELETE Queries
This deletes all employees who were hired before 2000-01-01 by selecting their IDs
from the subquery.
Nested INSERT Queries
You can insert values into a table using a subquery to select values from another table.
This inserts all employees from department 3 into the employee_backup table.
Advanced Nested Query (Using EXISTS and NOT EXISTS)
EXISTS checks if a subquery returns any rows. It’s typically used to test for existence.
SELECT name
FROM customers c
WHERE EXISTS ( SELECT *
FROM orders o WHERE o.customer_id = c.id);
This query selects all customers who have placed at least one order by
checking for the existence of related rows in the orders table.
Using NOT EXISTS in Subqueries
NOT EXISTS works similarly, but returns rows where the subquery does not return
SELECT name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.id);
This query first finds the departments located in New York and then counts the
employees in those departments.
These nested queries allows to break down complex problems into
manageable steps and help you manipulate data more flexibly.
1. List the names of employees who earn more than the average salary in their department.
2. Find the departments that have more than 5 employees.
3. Retrieve the names of customers who have not placed any orders.
4. Display the employee names who earn more than the highest salary in the HR department.
5. Find the names of employees who have been with the company for longer than the average
tenure.
6. Get the total sales for each department, and only display those departments with total
sales greater than 1,000,000.
7. Find the names of employees who work in the same department as the employee with the
highest salary.
8. Update the salary of employees in the 'Sales' department to the average salary of their
department.
9. Delete all products that have not been sold in the past 6 months.
10. Insert records into an 'archived_orders' table for orders older than 1 year.
Assertions in SQL
What is an Assertion in SQL?
● Purpose: A CHECK constraint is used to enforce a condition that must always be true for
the values in a column.
● Purpose: Ensures that all values in a column are unique across rows.
● Purpose: A BEFORE trigger can be used to prevent invalid data changes before
they are committed to the database.
Explanation: This BEFORE DELETE trigger checks if the user being deleted has the
username "admin". If it does, it raises an error, preventing the deletion from proceeding.
Triggers:
Structure:
CREATE TRIGGER trigger_name
{ BEFORE | AFTER } { INSERT | UPDATE | DELETE } ON table_name
FOR EACH ROW
BEGIN
IF <condition> THEN
<action>;
END IF;
END;
Example:
CREATE TABLE accounts (
account_id INT PRIMARY KEY, balance DECIMAL(10, 2));
Trigger:
CREATE TRIGGER prevent_negative_balance
BEFORE UPDATE ON accounts
FOR EACH ROW
BEGIN
-- Condition: if the new balance is negative
IF NEW.balance < 0 THEN
-- Action: raise error and block the operation
RAISE_APPLICATION_ERROR(-20001, 'Balance cannot be negative');
END IF;
END;
Note:
Event is always required.