Docsity

SQL Constraints, Primary Keys & Foreign Keys — DBMS Practical Notes, Exercises of Database Management Systems (DBMS)

Toggle sidebar
bg1
DATABASE SYSTEMS LAB MANUAL
1 | P a g e
Keys & Constraints
Topic: Primary Key, Foreign Key, UNIQUE, NOT NULL, and Data Integrity
1. Objective:
By the end of this lab, you will be able to:
Understand the purpose of keys and constraints in relational databases.
Explain the concept of a Primary Key.
Explain the concept of a Foreign Key.
Understand the purpose of the UNIQUE constraint.
Understand the purpose of the NOT NULL constraint.
Understand entity integrity and referential integrity.
Create tables with appropriate constraints using SQL.
Implement Primary Key and Foreign Key relationships.
Apply UNIQUE and NOT NULL constraints.
Test valid and invalid data using MySQL Workbench.
Analyze constraint violations and explain why they occur.
2. HARDWARE AND SOFTWARE REQUIRED :
Hardware
PC or Laptop
Keyboard and Mouse
Minimum 4 GB RAM
Internet connection
Software
MySQL Server
MySQL Workbench
Windows / Linux / macOS
Other Requirements
Access to LMS
Previous Lab database knowledge
Folder for saving screenshots
Basic SQL knowledge
3. INTRODUCTION
In a relational database, data is stored in tables.
For example, a university database may contain:
Students
Courses
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c

Partial preview of the text

Download SQL Constraints, Primary Keys & Foreign Keys — DBMS Practical Notes and more Exercises Database Management Systems (DBMS) in PDF only on Docsity!

1 | P a g e

Keys & Constraints

Topic: Primary Key, Foreign Key, UNIQUE, NOT NULL, and Data Integrity

1. Objective:

By the end of this lab, you will be able to:  Understand the purpose of keys and constraints in relational databases.  Explain the concept of a Primary Key.  Explain the concept of a Foreign Key.  Understand the purpose of the UNIQUE constraint.  Understand the purpose of the NOT NULL constraint.  Understand entity integrity and referential integrity.  Create tables with appropriate constraints using SQL.  Implement Primary Key and Foreign Key relationships.  Apply UNIQUE and NOT NULL constraints.  Test valid and invalid data using MySQL Workbench.  Analyze constraint violations and explain why they occur.

2. HARDWARE AND SOFTWARE REQUIRED:

Hardware  PC or Laptop  Keyboard and Mouse  Minimum 4 GB RAM  Internet connection Software  MySQL Server  MySQL Workbench  Windows / Linux / macOS Other Requirements  Access to LMS  Previous Lab database knowledge  Folder for saving screenshots  Basic SQL knowledge

3. INTRODUCTION

In a relational database, data is stored in tables. For example, a university database may contain: Students Courses

2 | P a g e Departments Teachers Enrollments When data is stored in multiple tables, we need rules to make sure that the data remains:  Correct  Valid  Consistent  Unique where required  Properly connected between tables These rules are implemented using keys and constraints.

4. WHAT IS A KEY?

A key is an attribute or a set of attributes used to identify records or establish relationships between tables. For example: Student_ID Student_Name Program 101 Ali BSCS 102 Sara BSAI 103 Ahmed BSSE

Here, Student_ID can be used to uniquely identify each student.

5. PRIMARY KEY

A Primary Key is a column or combination of columns that uniquely identifies each record in a table. A Primary Key:  Must contain unique values.  Cannot contain NULL.  Identifies each record.  A table normally has one Primary Key definition. Example: CREATE TABLE Students ( Student_ID INT PRIMARY KEY, Student_Name VARCHAR(50), Program VARCHAR(50) ); Here: “Student_ID” is the Primary Key.

4 | P a g e Enrollments.Student_ID This relationship can be implemented using a Foreign Key.

8. REFERENTIAL INTEGRITY

Referential integrity ensures that a Foreign Key value refers to a valid record in the referenced table. For example, if the Students table contains: 101 102 103 an enrollment should not normally refer to: 999 if student 999 does not exist. The Foreign Key constraint helps prevent such invalid relationships.

9. UNIQUE CONSTRAINT

The UNIQUE constraint ensures that values in a column are not duplicated. For example, university email addresses should normally be unique. Email VARCHAR(100) UNIQUE Example: Student_ID Email 101 [email protected] 102 [email protected] The same email value cannot be entered again when the UNIQUE constraint is enforced. Primary Key vs UNIQUE PRIMARY KEY UNIQUE Identifies records Prevents duplicate values Cannot contain NULL NULL handling differs depending on DBMS One Primary Key definition per table Multiple UNIQUE constraints can be defined Used as the main identifier Used for additional uniquenes

10.NOT NULL CONSTRAINT

The NOT NULL constraint requires a column to contain a value. Example: Student_Name VARCHAR(50) NOT NULL This means a student record cannot be created without a student name. Example Student_ID → Required Student_Name → Required Program → Optional The database can therefore enforce important data requirements.

5 | P a g e

11.DATA INTEGRITY:

Data integrity means maintaining the accuracy, consistency, and validity of data in a database. Important types discussed in this lab include: Entity Integrity: Ensures that each record can be uniquely identified. A Primary Key supports entity integrity. Referential Integrity: Ensures that relationships between tables remain valid. A Foreign Key supports referential integrity. Domain/Column-Level Integrity: Ensures that values follow defined rules such as:  NOT NULL  UNIQUE  Appropriate data types

12.CONSTRAINTS IN SQL

A constraint is a rule applied to data in a table. Common constraints include:  PRIMARY KEYFOREIGN KEYUNIQUENOT NULL Example: CREATE TABLE Students ( Student_ID INT PRIMARY KEY, Student_Name VARCHAR(50) NOT NULL, Email VARCHAR(100) UNIQUE ); This table applies three constraints:  Student_ID → PRIMARY KEY  Student_Name → NOT NULL  Email → UNIQUE

PRACTICAL ACTIVITY 1

CREATE DATABASE

Objective: To create a database that will be used throughout this lab. Open MySQL Workbench and connect to your MySQL Server. Execute: CREATE DATABASE UniversityDB; Select the database: USE UniversityDB; Verify the selected database: SELECT DATABASE(); Task Take a screenshot showing:  Database creation

7 | P a g e

PRACTICAL ACTIVITY 2

CREATE TABLE WITH PRIMARY KEY

Objective: To create a table using a Primary Key. Execute: CREATE TABLE Students ( Student_ID INT PRIMARY KEY, Student_Name VARCHAR(50), Program VARCHAR(50) ); Observe The Student_ID column is defined as: “PRIMARY KEY” This means it must uniquely identify every student record. Verify the structure Execute: DESCRIBE Students; Task Identify:  Primary Key column Ans: Student_ID column was Primary key column.  Data type of each column Ans: Data-type of columns is mentioned below: Student_ID  INT STUDENT_NAME  VARCHAR

8 | P a g e PROGRAM VARCHAR  Which column can uniquely identify a student Ans: Student_iD was the unique column. Screenshot: Students Table with Primary Key

PRACTICAL ACTIVITY 3

TEST PRIMARY KEY UNIQUENESS

Objective: To observe how a Primary Key prevents duplicate identifiers. Insert a valid record: INSERT INTO Students VALUES (101, 'Ali', 'BSCS'); Insert another valid record: INSERT INTO Students VALUES (102, 'Sara', 'BSAI'); Now attempt to insert another record using an already existing Student ID. INSERT INTO Students VALUES (101, 'Ahmed', 'BSSE'); Observe the result. Do not simply record whether an error appeared. Read the error message and identify what constraint caused the problem. Task Take a screenshot of:  Valid insertion

10 | P a g e

PRACTICAL ACTIVITY 4

NOT NULL CONSTRAINT

Objective: To ensure that an important field cannot be left empty. Create another table: CREATE TABLE StudentDetails ( Student_ID INT PRIMARY KEY, Student_Name VARCHAR(50) NOT NULL, Program VARCHAR(50) ); Insert a valid record: INSERT INTO StudentDetails VALUES (201, 'Ahmed', 'BSSE'); Now attempt to insert a record without a Student Name. INSERT INTO StudentDetails VALUES (202, NULL, 'BSCS'); Observe Check the response from MySQL Workbench. Think Why did MySQL reject the second record? Ans: Cuz, we used NOT NULL and we didn’t assign that variable any value, and it violated the NOT

11 | P a g e NULL integrity. Task Take a screenshot showing the constraint behavior.

PRACTICAL ACTIVITY 5

UNIQUE CONSTRAINT

Objective To prevent duplicate values in a column. Create: CREATE TABLE StudentAccounts ( Student_ID INT PRIMARY KEY, Student_Name VARCHAR(50) NOT NULL, Email VARCHAR(100) UNIQUE ); Insert valid records: INSERT INTO StudentAccounts VALUES (301, 'Ali', '[email protected]'); INSERT INTO StudentAccounts VALUES (302, 'Sara', '[email protected]');

13 | P a g e Task Explain:  Which value was duplicated? Ans: The Email was duplicated. Same email for both Ali , and Ahmed.  Which constraint caused the problem? Ans: When we added same value in Ahmad’s email, it caused error.  Why is a UNIQUE constraint useful for email addresses? Ans: We use it if we don’t want replication in Email. Unique doesn’t allow duplicate email addresses.

PRACTICAL ACTIVITY 06

CREATE A FOREIGN KEY

Objective:

To establish a relationship between two tables using a Foreign Key. First create the parent table: CREATE TABLE Departments ( Department_ID INT PRIMARY KEY, Department_Name VARCHAR(50) NOT NULL ); Insert some departments:

14 | P a g e INSERT INTO Departments VALUES (1, 'Computer Science'); INSERT INTO Departments VALUES (2, 'Artificial Intelligence'); INSERT INTO Departments VALUES (3, 'Software Engineering'); Now create the child table: CREATE TABLE StudentsFK ( Student_ID INT PRIMARY KEY, Student_Name VARCHAR(50) NOT NULL, Department_ID INT, FOREIGN KEY (Department_ID) REFERENCES Departments(Department_ID) ); Understand the relationship Departments | |Department_ID ↓ StudentsFK Departments is the referenced/parent table. StudentsFK is the referencing/child table.

16 | P a g e

  1. Failed insertion with an invalid Foreign Key.

17 | P a g e

PRACTICAL ACTIVITY 8

VIEW TABLE RELATIONSHIP

Objective: To verify the relationship between the parent and child tables. In MySQL Workbench:

  1. Open the UniversityDB schema.
  2. Expand Tables.
  3. Locate: o Departments o StudentsFK
  4. Open the table structure.
  5. Observe the Foreign Key information. You may also inspect the table using: SHOW CREATE TABLE StudentsFK; Task Identify:  Parent table  Child table  Primary Key  Foreign Key  Referenced column

19 | P a g e

LAB TASKS: UNIVERSITY DATABASE

You must independently design and implement a small university database. Create a database named: CollegeDB Create the following tables: Departments Required:  Department ID  Department Name Apply:  PRIMARY KEY  NOT NULL Students Required:  Student ID  Student Name  Email  Department ID Apply:  PRIMARY KEY  NOT NULL  UNIQUE  FOREIGN KEY Courses Required:  Course ID  Course Name  Course Code  Credit Hours Apply appropriate constraints.

20 | P a g e You must perform the following: Task 1: Create the database. Task 2: Create the Departments table.