0% found this document useful (0 votes)
7 views11 pages

Lab 6

Constraints in SQL

Uploaded by

esraa.2020501
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)
7 views11 pages

Lab 6

Constraints in SQL

Uploaded by

esraa.2020501
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/ 11

Lab 6

Created @May 8, 2025 3:39 PM

Tags

Table Constraints
Purpose: Enforce rules on columns to maintain data integrity and accuracy.

Types of Constraints:
PRIMARY KEY: Uniqueness + NOT NULL

FOREIGN KEY: Relationship between tables

UNIQUE: Distinct values (allows NULLs)

CHECK: Conditions for acceptable values

DEFAULT: Default values if none provided

NOT NULL: Disallow NULL values

Primary Key Constraint


Guarantees uniqueness and no null values.

Can be a single column or a composite key (multiple columns).

Only one primary key per table.

CREATE TABLE Departments(


DepartmentID int PRIMARY KEY,
DepartmentName varchar(100)
);

Lab 6 1
Foreign Key Constraint
Links two tables together.

Prevents invalid relationships.

Example:

CREATE TABLE Employees(


EmployeeID int PRIMARY KEY,
Age int,
EmployeeName varchar(50),
DepartmentID int,
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
ON DELETE CASCADE
);

Unique Constraint
Ensures all values are different in a column.

Allows NULL values. (but only one null because it is unique ^^)

CREATE TABLE Users(


UserID int PRIMARY KEY,
Email varchar(50) UNIQUE
);

Check Constraint
Defines a condition that must be met.

CREATE TABLE Products(


ProductID int PRIMARY KEY,
ProductName varchar(50),

Lab 6 2
UnitPrice int CHECK(UnitPrice > 0)
);

Default Constraint
Assigns a default value when none is provided.

Example: OrderDate defaults to GETDATE() , Status defaults to 'Pending' .

CREATE TABLE Orders(


OrderID int PRIMARY KEY,
OrderDate datetime DEFAULT GETDATE(),
Status varchar(50) DEFAULT('Pending')
);

Not Null Constraint


Ensures a column cannot have NULL values.

Example: CategoryName must have a value.

CREATE TABLE Categories(


CategoryID int PRIMARY KEY,
CategoryName varchar(50) NOT NULL
);

Modifying Constraints
Add a new constraint to an existing table.

ALTER TABLE Employees


ADD CONSTRAINT chk_age CHECK (AGE >= 18);

Lab 6 3
Drop an existing constraint from a table.

ALTER TABLE Employees


DROP CONSTRAINT chk_age

T-SQL Blocks Overview


Types:
Anonymous Blocks: Temporary, one-time use.

Stored Procedures: Reusable, complex operations (CRUD, transactions).

Stored Functions: Return a single value or table inside queries.

Handling Variables in T-SQL


Declare and initialize variables in the declaration section.

Assign new values during execution.

Lab 6 4
Pass parameters and use output variables for results.

Syntax:
DECLARE @identifier datatype [= expression];

DECLARE @username varchar(50);


DECLARE @userage int;

Assigning Values to Variables


Using SET:
Good for single-value assignment.

Example:

DECLARE @ProductName NVARCHAR(50);


SET @ProductName = 'Laptop';
PRINT @ProductName;

Using SELECT:
Good for query results or multiple assignments.

here we are selecting values to the variables from the result of the query

Example:

DECLARE @ProductID INT, @ProductName NVARCHAR(100), @Price MO


NEY;
SELECT @ProductID = ProductID, @ProductName = ProductName, @Pric
e = UnitPrice
FROM Products
WHERE ProductID = 1;

Lab 6 5
Commenting Code in T-SQL
Single line: - comment

Multi-line: /* comment */

Example:

/* Compute annual salary */


-- SET @v_sal = @v_sal * 12;

Flow Control in T-SQL


Controlling Execution Flow
IF...ELSE: Conditional logic.

WHILE: Looping control structure.

IF Statement
Syntax:

IF condition
statement;
[ELSE IF condition
statement;]
[ELSE
statement;]

Example:

DECLARE @Price MONEY;


SELECT @Price = UnitPrice FROM Products WHERE ProductID = 1;

Lab 6 6
IF @Price > 50
PRINT 'Expensive';
ELSE IF @Price BETWEEN 20 AND 50
PRINT 'Moderately Priced';
ELSE
PRINT 'Cheap';

WHILE Loop
Syntax:

WHILE condition
BEGIN
statement1;
statement2;
END;

Example:

DECLARE @Counter INT = 1;


WHILE @Counter <= 5
BEGIN
PRINT 'Counter: ' + CAST(@Counter AS VARCHAR);
SET @Counter = @Counter + 1;
END;

T-SQL Program Units


Types:

Lab 6 7
Procedures: Perform actions.

Functions: Return a value.

Stored Procedures
Syntax:

CREATE PROCEDURE procedure_name


(
@parameter1 datatype1,
@parameter2 datatype2 OUTPUT
)
AS
[local_variable_declarations; …]
BEGIN
-- actions
END;

Stored Procedures Examples


Without Parameters:
Retrieve all customers:

CREATE PROCEDURE GetAllCustomers


AS
BEGIN
SELECT * FROM Customers;
END;

EXEC GetAllCustomers;

Lab 6 8
//or use EXECUTE

With Input Parameters:


Retrieve customers by country:

CREATE PROCEDURE GetCustomerByCountry


@Country nvarchar(50) --input parameter
AS
BEGIN
SELECT * from Customers
WHERE Country = @Country;
END;

EXEC GetCustomersByCountry @Country = 'Germany';

With Output Parameter:


Count customers from a specific country.

CREATE PROCEDURE GetCustomerCountByCountry


@Country nvarchar(50), --input
@CustomerCount int OUTPUT --output parameter
AS
BEGIN
SELECT @CustomerCount = Count(*)
FROM Customers
WHERE Country = @Country;
END;

DECLARE @Total int;


EXEC GetCustomerCountByCountry @Country = 'USA', @CustomerCount = @To
PRINT 'Total customers in USA' + CAST(@Total as varchar);

Lab 6 9
With Multiple Parameters:
Retrieve orders within a date range.

CREATE PROCEDURE GetOrdersByDateRange


@StartDate datetime,
@EndDate datetime
AS
BEGIN
Select * FROM Orders
WHERE OrderDate BETWEEN @StartDate AND @EndDate;
END;

EXEC GetOrdersByDateRange @StartDate = '1996-12-01', @StartDate = '2000-1

Modifying and Dropping Stored Procedures


Modify:

ALTER PROCEDURE procedure_name


AS
BEGIN
--actions
END;

Drop:

DROP PROCEDURE procedure_name;

Practice Exercises
Practice 1:

Lab 6 10
Write a stored procedure to retrieve all orders for a given CustomerID .

CREATE PROCEDURE GetOrdersForCustomer


@CustomerID int
AS
BEGIN
SELECT OrderID, OrderDate, ShipCountry
FROM Orders
WHERE CustomerID = @CustomerID;
END;

Practice 2:

Write a stored procedure to calculate the total sales amount for a given
ProductID .

CREATE PROCEDURE getTotalSalesForProduct


@ProductID int
AS
BEGIN
DECLARE @TotalSales Money;
SELECT @TotalSales = SUM(UnitPrice * Quantity)
FROM OrderDetails
WHERE ProductID = @ProductID

SELECT @TotalSales as TotalSales

END;

Lab 6 11

You might also like