0% found this document useful (0 votes)
17 views2 pages

DBMS Unit2

SQL constraints are rules that govern the data in a table, ensuring data integrity and enforcing business rules. Common types of constraints include NOT NULL, UNIQUE, PRIMARY KEY, and FOREIGN KEY, each serving specific purposes to maintain data accuracy and relationships. Additionally, views and indexes are utilized to simplify queries and enhance data retrieval performance, while stored procedures encapsulate complex operations for efficiency.

Uploaded by

prafull.barathe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views2 pages

DBMS Unit2

SQL constraints are rules that govern the data in a table, ensuring data integrity and enforcing business rules. Common types of constraints include NOT NULL, UNIQUE, PRIMARY KEY, and FOREIGN KEY, each serving specific purposes to maintain data accuracy and relationships. Additionally, views and indexes are utilized to simplify queries and enhance data retrieval performance, while stored procedures encapsulate complex operations for efficiency.

Uploaded by

prafull.barathe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

SQL Constraints: SQL constraints are used to specify rules for the data in a table.

Constraints, Not-Null Constraints, Entity integrity Constraints, Key Constraints,


Constraints are used to limit the type of data that can go into a table. Constraints can Primary Key Constrains, Referential integrity constraints
be column level or table level. Column level constraints apply to a column, and table
Entity Integrity Constraints: Entity integrity constraints state that primary key can
level constraints apply to the whole table.The following constraints are commonly used
never contain null value because primary key is used to determine individual rows in
in SQL: NOT NULL - Ensures that a column cannot have a NULL value. UNIQUE -
a relation uniquely, if primary key contains null value then we cannot identify those
Ensures that all values in a column are different PRIMARY KEY - A combination of
rows. A table can contain null value in it except primary key field.
a NOT NULL and UNIQUE. Uniquely identifies each row in a table FOREIGN KEY -
Prevents actions that would destroy links between tables CHECK - Ensures that the Example: It is not allowed because it is containing primary key as NULL value.
values in a column satisfies a specific condition DEFAULT - Sets a default value for a
column if no value is specified CREATE INDEX - Used to create and retrieve data from Student_id Name Semester Age
the database very quickly
Importance of Creating Constraints: 1) Constraints ensure that only valid data is 21CSE101 Ramesh 5th 20
entered into the database, maintaining the accuracy and consistency of data. 2)
Constraints help enforce business rules at the database level, such as requiring that
certain fields must not be left blank. 3) Constraints like unique constraints prevent 21CSE102 Kamlesh 5th 21
duplicate entries, ensuring each record is unique where necessary. 4) Constraints like
foreign keys ensure proper relationships between tables, maintaining referential
integrity across the database. Examples of 4 common constraints in a database 21CSE103 Aakash 5th 22
table:
PRIMARY KEY Constraint: Mukesh 5th 20
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50)
); Referential integrity constraints: It can be specified between two tables. In case of
FOREIGN KEY Constraint: referential integrity constraints, if a Foreign key in Table 1 refers to Primary key of
CREATE TABLE Enrollments ( Table 2 then every value of the Foreign key in Table 1 must be null or available in Table
EnrollmentID INT PRIMARY KEY, 2.
StudentID INT,
Example: Here, in below example Block_No 22 entry is not allowed because it is not
FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
); present in 2nd table.
UNIQUE Constraint:
CREATE TABLE Users ( Student_id Name Semester Block_No
UserID INT PRIMARY KEY,
Email VARCHAR(100) UNIQUE
); 22CSE101 Ramesh 5th 20
NOT NULL Constraint:
CREATE TABLE Orders (
OrderID INT PRIMARY KEY, 21CSE105 Kamlesh 6th 21
OrderDate DATE NOT NULL
);
Integrity Constraints : Integrity constraints are the set of predefined rules that are 22CSE102 Aakash 5th 20
used to maintain the quality of information. Integrity constraints ensure that the data
insertion, data updating, data deleting and other processes have to be performed in
such a way that the data integrity is not affected. They act as guidelines ensuring that 23CSE106 Mukesh 2nd 22
data in the database remain accurate and consistent. So, integrity constraints are
used to protect databases. The various types of integrity constraints are Domain

1 2

Non-Updatable Views: A view is not updatable if it involves complex SQL operations


Block_No Block Location
such as joins, aggregations, or grouping. This is because the update operation cannot
be directly mapped to the base tables.
20 Chandigarh  Reason: The database does not know how to distribute changes across the
involved tables or how to handle computed or derived values.
21 Punjab  Example of a Non-Updatable View:
CREATE VIEW StudentSummary AS
25 Delhi SELECT Status, COUNT(*) AS Total

FROM Students
GROUP BY Status;
Views in SQL : A view is a virtual table in a database that represents the result of a
stored query. It does not store data itself but provides a way to simplify complex You cannot update this view since it involves aggregation (COUNT and GROUP BY).
queries, encapsulate query logic, and present data in a specific format or subset. Views
are created using the SELECT statement to display data from one or more tables.
How to Create a View: To create a view, use the CREATE VIEW statement followed
by the view name and the SELECT query that defines the data the view will display. SQL Indexes : An index is a database object that improves the speed of data retrieval
operations on a table. It is a data structure (often a B-tree or hash table) that stores a
CREATE VIEW ActiveStudents AS
sorted version of the values in one or more columns of a table, along with pointers to
SELECT StudentID, Name the corresponding rows. Indexes make searching, sorting, and querying data faster,
but they come with some trade-offs.
FROM Students
Advantages: Faster Queries: Speeds up data retrieval. Efficient
WHERE Status = 'Active';
Sorting/Searching: Improves performance for ORDER BY and GROUP BY. Better
This creates a view named ActiveStudents that shows only students with a status of Join Performance: Accelerates JOIN operations. Enforces Uniqueness: Supports
"Active." unique constraints.

Can You Update a View?: Yes, you can update a view, but with limitations. Disadvantages: More Storage: Requires additional disk space. Slower Data
Modifications: INSERT, UPDATE, and DELETE operations can be slower. Maintenance
1. Updatable Views: A view is updatable if it directly references columns from one
Needed: Requires regular upkeep. Not Always Effective: Can degrade performance
base table and does not contain any of the following:
if misused.
 Aggregate functions (SUM, AVG, etc.)
Indexes are useful for speeding up queries but can have drawbacks like extra storage
 DISTINCT keyword and slower data updates.

 GROUP BY clause Stored Procedure: A stored procedure is a precompiled collection of one or more
SQL statements stored in the database. It can be executed as a single unit and is often
 JOIN statements (in most cases)
used to perform repetitive tasks, complex operations, or encapsulate business logic.
 Subqueries or derived columns Stored procedures can accept input parameters, return output parameters, and provide
better performance and security compared to executing individual SQL queries.
UPDATE ActiveStudents
Example of creating and calling a stored procedure:
SET Name = 'Jane Doe'
Creating a Stored Procedure: Create a procedure named GetEmployeeByID to fetch
WHERE StudentID = 1; employee details by EmployeeID:

This will update the Name column in the underlying Students table for StudentID 1. CREATE PROCEDURE GetEmployeeByID
@EmployeeID INT
3 4
AS
BEGIN Problem 2: Consider following schema Student_fee_details (rollno, name,
fee_deposited, date) Write a trigger to preserve old values of student fee details before
SELECT * FROM Employees WHERE EmployeeID = @EmployeeID;
updating in the table.
END;
Answer: CREATE TABLE StudentFeeAudit (
Calling the Stored Procedure: Execute the stored procedure with an EmployeeID of
rollno INT,
101:
name VARCHAR(100),
EXEC GetEmployeeByID @EmployeeID = 101;
fee_deposited DECIMAL(10, 2),
Problem 1: Consider the following schemas
date DATE,
Emp(Emp_no, Emp_name, Dept_no)
old_fee_deposited DECIMAL(10, 2),
Dept(Dept_no, Dept_name)
old_date DATE,
Address(Dept_name, Dept_location)
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
Write SQL queries for the following
);
i) Display the location of department where employee ‘Ram’ is working.
CREATE TRIGGER BeforeFeeUpdate
ii) Create a view to store total no of employees working in each
ON Student_fee_details
department in ascending order.
AFTER UPDATE
iii) Find the name of the department in which no employee is working.
AS
Answer:
BEGIN
i) SELECT A.Dept_location
INSERT INTO StudentFeeAudit (rollno, name, fee_deposited, date,
FROM Emp E
old_fee_deposited, old_date)
JOIN Dept D ON E.Dept_no = D.Dept_no
SELECT d.rollno, d.name, d.fee_deposited, d.date, i.fee_deposited, i.date
JOIN Address A ON D.Dept_name = A.Dept_name
FROM deleted d
WHERE E.Emp_name = 'Ram';
JOIN inserted i ON d.rollno = i.rollno;
ii) CREATE VIEW DeptEmployeeCount AS
END;
SELECT D.Dept_no, D.Dept_name, COUNT(E.Emp_no) AS
TotalEmployees
FROM Dept D
LEFT JOIN Emp E ON D.Dept_no = E.Dept_no
GROUP BY D.Dept_no, D.Dept_name
ORDER BY TotalEmployees ASC;
iii) SELECT D.Dept_name
FROM Dept D
LEFT JOIN Emp E ON D.Dept_no = E.Dept_no
Problem 3: Write a PL/SQL block of code which accepts the rollno from user. The
WHERE E.Emp_no IS NULL;
attendance of rollno entered by user will be checked instudent_attendance(RollNo,
Attendance) table and display on the screen.
Answer: DECLARE
5 6

-- Variable to store the user input FROM Shipments SH


v_rollno student_attendance.RollNo%TYPE; JOIN Supplier S ON SH.SNO = S.SNO
-- Variable to store the attendance result JOIN Parts P ON SH.PNO = P.PNO
v_attendance student_attendance.Attendance%TYPE; WHERE SH.QTY < 157;
BEGIN ii) SELECT DISTINCT S.SNO, S.Sname, P.PNO, P.Pname
-- Accept user input for roll number FROM Shipments SH
v_rollno := &rollno; -- Prompt the user to enter the roll number JOIN Supplier S ON SH.SNO = S.SNO
-- Query the attendance based on the entered roll number JOIN Parts P ON SH.PNO = P.PNO

SELECT Attendance WHERE SH.QTY > (SELECT AVG(QTY) FROM Shipments);


INTO v_attendance iii)
FROM student_attendance SELECT SUM(SH.QTY) AS TotalQuantity
WHERE RollNo = v_rollno; FROM Shipments SH
-- Display the attendance JOIN Parts P ON SH.PNO = P.PNO
DBMS_OUTPUT.PUT_LINE('Attendance for RollNo ' || v_rollno || ': ' || JOIN Supplier S ON SH.SNO = S.SNO
v_attendance);
WHERE P.PNO = 1692 AND P.Color = 'green' AND S.City = 'Mumbai';
EXCEPTION
-- Handle cases where the roll number is not found
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No attendance record found for RollNo ' ||
v_rollno);
-- Handle any other exceptions
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
END;
/
Problem 4: Consider the following schemes Supplier(SNO, Sname, Status, City) Parts
(PNO, Pname, Color, Weight, City) Shipments(SNO,PNO,QTY)
Write SQL queries for the following: i) Find shipment information (SNO, Sname, PNO,
Pname, QTY) for
those having quantity less than 157. ii) List SNO, Sname, PNO, Pname for those
suppliers who made shipments of parts whose quantity is larger than the average
quantity iii) Find aggregate quantity of PNO 1692 of color green for which shipments
made by supplier number who residing Mumbai
Answer: i) SELECT S.SNO, S.Sname, P.PNO, P.Pname, SH.QTY
7 8

You might also like