SQL Assertions
SQL ASSERTIONS
1. AIM
To study Assertions in SQL and implement integrity constraints using assertions.
2. THEORY
✔ What is an Assertion?
An Assertion is a schema-level integrity constraint in SQL that ensures a certain condition always holds true for the entire database.
Assertions:
-
Are general constraints applied across multiple tables.
-
Are more powerful than CHECK constraints (which apply only row-wise on one table).
-
Are used when constraints involve multiple rows or multiple tables.
-
Are rarely implemented in MySQL (MySQL does NOT support CREATE ASSERTION).
-
Supported in SQL standard, Oracle partially, PostgreSQL using triggers.
✔ General Syntax (SQL Standard)
Example:
This assertion ensures no employee has a negative salary.
❗ Important Note (MySQL Limitation)
MySQL does NOT support CREATE ASSERTION.
Instead, MySQL implements assertions using:
-
CHECK constraints (from MySQL 8.0+)
-
Triggers
-
Stored procedures
So for teaching labs, we explain standard SQL assertions and provide MySQL alternative.
3. EXAMPLES USING SQL STANDARD ASSERTIONS
Example 1: Ensuring No Employee Has Negative Salary
Example 2: Ensuring Total Salary Budget Does Not Exceed 200000
Example 3: Ensuring Every Course Has at Least One Student Enrolled
Example 4: Prevent Insert if Stock Goes Below Zero
4. MYSQL ALTERNATIVES (FOR LAB USE)
Because MySQL doesn’t support assertions, we use triggers to simulate them.
Example 1: Assertion to Ensure Salary > 0 in MySQL Using Trigger
Example 2: Assertion to Prevent Budget Overflow
6. PRACTICE QUESTIONS
-
Write an assertion to ensure no student's marks exceed 100.
-
Write an assertion to ensure at least one teacher is assigned to every department.
-
Write an assertion to ensure a project always has at least one employee assigned.
-
Simulate an assertion in MySQL to prevent product quantity from going negative.
-
Simulate an assertion to ensure library book count never becomes zero.
7. RESULT
The concept of SQL Assertions was studied and simulated using MySQL Triggers. Students learned how global constraints are enforced in database systems.
Comments
Post a Comment