Implementation of SQL queries using,
SELECT Statements Restricting and Sorting Data, Single-Row Functions
SQL Statements
• Displaying Data from Multiple Tables,
• Aggregating Data Using Group Functions
Manipulating Data Using INSERT, DELETE, UPDATE statement
1. Data Definition Language (DDL)
DDL commands define the structure of a database, including creating, altering, and deleting tables and schemas.
• Key DDL Commands:
o CREATE: Creates a new table or database object.
o ALTER: Modifies an existing table (e.g., add a column).
o DROP: Deletes tables, views, or indexes.
o TRUNCATE: Removes all rows from a table but keeps the structure.
Lab Assessment:
• Task: Create a table Employee with fields like EmployeeID, Name, Designation, and Salary.
• Modify the table to add a new field Department.
• Drop the Department field.
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(50),
Designation VARCHAR(50),
Salary DECIMAL(10, 2)
);
ALTER TABLE Employee ADD Department VARCHAR(50);
ALTER TABLE Employee DROP COLUMN Department;
2. Data Control Language (DCL)
DCL commands control access to data within the database.
• Key DCL Commands:
o GRANT: Gives users access privileges.
o REVOKE: Removes access privileges.
Lab Assessment:
• Task: Grant SELECT and INSERT permissions to a user for the Employee table.
GRANT SELECT, INSERT ON Employee TO 'username';
REVOKE INSERT ON Employee FROM 'username';
3. Data Manipulation Language (DML) - CRUD Operations
DML commands are used to manipulate data within the database.
• CRUD Operations:
o INSERT: Adds new data to the table.
o UPDATE: Modifies existing data.
o DELETE: Removes data from the table.
o SELECT: Retrieves data from the table.
Lab Assessment:
• Task: Insert data into the Employee table, update the salary, and then delete a record.
INSERT INTO Employee (EmployeeID, Name, Designation, Salary)
VALUES (101, 'Alice', 'Developer', 60000);
UPDATE Employee SET Salary = 65000 WHERE EmployeeID = 101;
DELETE FROM Employee WHERE EmployeeID = 101;
4. Relational Operations
SQL supports several relational operations such as Select, Project, Union, Difference, Intersection, and
Cartesian Product.
• SELECT: Extracts data based on conditions.
• PROJECT: Selects specific columns.
• UNION: Combines the result of two queries (removes duplicates).
• INTERSECTION: Returns common records between two queries.
• CARTESIAN PRODUCT: Combines all rows from two tables.
Lab Assessment:
• Task: Select specific columns and perform union and intersection operations on two datasets.
-- Select specific columns
SELECT Name, Designation FROM Employee;
-- UNION operation between two tables (Combine both the coloumn)
SELECT Name FROM Employee
UNION
SELECT Name FROM Manager;
-- INTERSECTION operation (In both coloumn are common)
SELECT Name FROM Employee
INTERSECT
SELECT Name FROM Manager;
5. Aggregation Functions
Aggregation functions are used to perform calculations on sets of data, such as counting, summing, averaging,
etc.
• Key Functions: COUNT(), SUM(), AVG(), MAX(), MIN().
Lab Assessment:
• Task: Find the total salary, average salary, and maximum salary in the Employee table.
SELECT SUM(Salary) AS TotalSalary FROM Employee;
SELECT AVG(Salary) AS AverageSalary FROM Employee;
SELECT MAX(Salary) AS MaxSalary FROM Employee;
6. ORDER BY, GROUP BY, and HAVING Clauses
• ORDER BY: Sorts the result set.
• GROUP BY: Groups rows that have the same values.
• HAVING: Filters groups based on a condition.
Lab Assessment:
• Task: Group employees by designation and get the average salary, then order the result.
SELECT Designation, AVG(Salary) AS AvgSalary
FROM Employee
GROUP BY Designation
HAVING AVG(Salary) > 50000
ORDER BY AvgSalary DESC;
7. Index and View
• Index: Speeds up retrieval of data.
• View: A virtual table based on the result of an SQL query.
Lab Assessment:
• Task: Create an index on the Employee table for faster searching by Name. Create a view to show
employee details.
CREATE INDEX idx_name ON Employee(Name);
CREATE VIEW EmployeeView AS
SELECT EmployeeID, Name, Designation
FROM Employee;
8. Joins
1. INNER JOIN
An INNER JOIN returns only the rows where there is a match in both tables. For our tables, it
will return only those students who are enrolled in a course.
SELECT s.StudentID, s.FirstName, s.LastName, c.CourseName
FROM Student s
INNER JOIN Course c ON s.CourseID = c.CourseID;
Result:
This query retrieves each student's StudentID, FirstName, LastName, and
CourseName from the Course table. If a student does not have a matching CourseID in
the Course table, that student will not appear in the results.
2. LEFT JOIN (or LEFT OUTER JOIN)
A LEFT JOIN returns all records from the left table (Student), and the matched records
from the right table (Course). If no match is found, the result is NULL on the side of the
Course table.
SELECT s.StudentID, s.FirstName, s.LastName, c.CourseName
FROM Student s
LEFT JOIN Course c ON s.CourseID = c.CourseID;
Result:
This will return all students and their courses if available. If a student has a CourseID that
does not match any entry in the Course table, the CourseName will be NULL.
3. RIGHT JOIN (or RIGHT OUTER JOIN)
A RIGHT JOIN is the opposite of a LEFT JOIN. It returns all records from the right table
(Course), and the matched records from the left table (Student). If no match is found,
NULL values are returned for columns from the Student table.
SELECT s.StudentID, s.FirstName, s.LastName, c.CourseName
FROM Student s
RIGHT JOIN Course c ON s.CourseID = c.CourseID;
Result:
This query will display all courses and any students enrolled in them. If a course has no
students, the columns for StudentID, FirstName, and LastName will be NULL.
4. FULL OUTER JOIN
A FULL OUTER JOIN returns all records when there is a match in either the Student or
Course table. If there is no match, NULL values are returned for columns where there is no
match in the corresponding table.
SELECT s.StudentID, s.FirstName, s.LastName, c.CourseName
FROM Student s
FULL OUTER JOIN Course c ON s.CourseID = c.CourseID;
Result:
This will return all students and all courses, with NULL values where a student does not have a
course or a course does not have any students enrolled.
5. CROSS JOIN
A CROSS JOIN returns the Cartesian product of both tables. This means it will pair each row
in the Student table with each row in the Course table, resulting in every possible
combination. Use this join carefully, especially with large tables, as it can generate a large
number of rows.
SELECT s.StudentID, s.FirstName, s.LastName, c.CourseName
FROM Student s
CROSS JOIN Course c;
Result:
This query returns each student paired with every course, regardless of the CourseID. If the
Student table has 5 records and the Course table has 5 records, this will return 25 rows (5 x
5).
6. SELF JOIN
A SELF JOIN is when a table is joined with itself. Although it’s not directly applicable to the
Student and Course tables, a self join could be used, for example, to find students with the
same age.
SELECT a.StudentID AS Student1_ID, a.FirstName AS
Student1_FirstName,
b.StudentID AS Student2_ID, b.FirstName AS
Student2_FirstName
FROM Student a
JOIN Student b ON a.Age = b.Age AND a.StudentID <> b.StudentID;
Result:
This query returns pairs of students with the same age but different StudentIDs. Each row
shows two students with matching ages.
Summary of Join Results
Join Type Description
INNER JOIN Returns records with matching values in both tables.
Returns all records from the left table, with matched records from the right
LEFT JOIN
table if available.
Returns all records from the right table, with matched records from the left
RIGHT JOIN
table if available.
FULL OUTER Returns all records when there is a match in either table, with NULLs where
JOIN no match exists.
CROSS JOIN Returns the Cartesian product of both tables (all combinations of rows).
Join Type Description
SELF JOIN Joins a table with itself, useful for comparing rows within the same table.
9. Subqueries and Correlated Subqueries
• Subquery: A query inside another query.
• Correlated Subquery: A subquery that depends on the outer query.
Lab Assessment:
• Task: Use a subquery to find employees whose salary is above the average salary.
SELECT Name, Salary
FROM Employee
WHERE Salary > (SELECT AVG(Salary) FROM Employee);
LAB PRACTICAL
Step 1: Create the Course Table
The Course table contains CourseID as the primary key, which will act as a foreign key in the Student table.
CREATE TABLE Course (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(50)
);
-- Insert some example courses
INSERT INTO Course (CourseID, CourseName) VALUES
(101, 'Mathematics'),
(102, 'Physics'),
(103, 'Chemistry'),
(104, 'Biology'),
(105, 'Computer Science');
Step 2: Create the Student Table
The Student table includes fields like FirstName, LastName, DOB, Age, Marks, and CourseID, with CourseID
as a foreign key referencing the Course table.
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DOB DATE,
Age INT,
Marks DECIMAL(5, 2),
CourseID INT,
FOREIGN KEY (CourseID) REFERENCES Course(CourseID)
);
-- Insert some example students
INSERT INTO Student (StudentID, FirstName, LastName, DOB, Age, Marks, CourseID) VALUES
(1, 'Alice', 'Johnson', DATE '2001-05-15', 23, 89.5, 101),
(2, 'Bob', 'Smith', DATE '2002-08-22', 22, 76.2, 102),
(3, 'Charlie', 'Brown', DATE '2000-10-10', 24, 82.7, 103),
(4, 'Daisy', 'Miller', DATE '2001-12-01', 23, 91.4, 104),
(5, 'Edward', 'Wilson', DATE '2003-04-18', 21, 88.0, 105);
Explanation of Fields:
• StudentID: Primary key for identifying each student uniquely.
• FirstName and LastName: Name fields.
• DOB: Date of Birth.
• Age: Age of the student.
• Marks: The marks obtained by the student.
• CourseID: A foreign key referencing the Course table, establishing a relationship with the course that each
student is enrolled in.
Final Data in Tables:
Course Table:
CourseID CourseName
101 Mathematics
102 Physics
103 Chemistry
104 Biology
105 Computer Science
Student Table:
StudentID FirstName LastName DOB Age Marks CourseID
1 Alice Johnson 2001-05-15 23 89.5 101
2 Bob Smith 2002-08-22 22 76.2 102
3 Charlie Brown 2000-10-10 24 82.7 103
4 Daisy Miller 2001-12-01 23 91.4 104
5 Edward Wilson 2003-04-18 21 88.0 105
1. SELECT Statements, Restricting, and Sorting Data
Objective: Teach students how to retrieve data from tables, apply conditions, and sort results.
• SELECT Basics: Show how to select specific columns from a table.
o Example Command:
SELECT FirstName, LastName FROM Students;
• Restricting Data with WHERE: Teach how to filter rows using conditions.
o Example Command:
SELECT FirstName, LastName FROM Students WHERE Age > 18;
• Sorting Data with ORDER BY: Teach students how to sort the data.
o Example Command:
SELECT FirstName, LastName FROM Students ORDER BY LastName ASC;
• Lab Exercise: Ask students to fetch and sort data from tables based on different conditions.
2. Single-Row Functions
Objective: Learn to use single-row functions to modify and display data.
• String Functions:
o Example Command:
SELECT UPPER(FirstName), LOWER(LastName) FROM Students;
• Numeric Functions:
o Example Command:
SELECT ROUND(Salary, 2) FROM Employees;
• Date Functions:
o Example Command:
SELECT SYSDATE, ADD_MONTHS(DateOfBirth, 12) FROM Students;
3. Displaying Data from Multiple Tables (Joins)
Objective: Teach students how to retrieve data from multiple related tables using JOIN.
• INNER JOIN: Fetch data from related tables where the relationship exists.
o Example Command:
SELECT Students.FirstName, Courses.CourseName
FROM Students
INNER JOIN Courses ON Students.CourseID = Courses.CourseID;
• LEFT JOIN: Fetch all records from the left table, even if there are no matches in the right table.
o Example Command:
SELECT Students.FirstName, Courses.CourseName
FROM Students
LEFT JOIN Courses ON Students.CourseID = Courses.CourseID;
4. Aggregating Data Using Group Functions
Objective: Teach how to summarize data using aggregate functions like COUNT, SUM, AVG, etc.
• Group by Aggregate Functions:
o Example Command:
SELECT COUNT(*), AVG(Salary)
FROM Employees
WHERE DepartmentID = 10;
• Using GROUP BY:
o Example Command:
SELECT DepartmentID, AVG(Salary)
FROM Employees
GROUP BY DepartmentID;
5. Manipulating Data Using INSERT, DELETE, and UPDATE Statements
Objective: Learn to insert, update, and delete data in a table.
• INSERT Data:
o Example Command:
INSERT INTO Students (StudentID, FirstName, LastName, Age)
VALUES (101, 'John', 'Doe', 20);
• UPDATE Data: Modify existing data.
o Example Command:
UPDATE Students
SET Age = 21
WHERE StudentID = 101;
• DELETE Data: Remove data from a table.
o Example Command:
DELETE FROM Students
WHERE StudentID = 101;
LAB PRACTICAL
Step 1: Create the Tables
We will create two tables for this exercise: Employee and Department.
-- Create Department table
CREATE TABLE Department (
DepartmentID NUMBER PRIMARY KEY,
DepartmentName VARCHAR2(50),
Location VARCHAR2(50)
);
-- Create Employee table
CREATE TABLE Employee (
EmployeeID NUMBER PRIMARY KEY,
Name VARCHAR2(50),
Designation VARCHAR2(50),
Salary NUMBER(10, 2),
DepartmentID NUMBER,
HireDate DATE,
FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID)
);
Step 2: Insert Sample Data
Populate the tables with sample data for running the queries.
-- Insert data into Department table
INSERT INTO Department (DepartmentID, DepartmentName, Location) VALUES (1, 'HR', 'New
York');
INSERT INTO Department (DepartmentID, DepartmentName, Location) VALUES (2, 'Finance',
'London');
INSERT INTO Department (DepartmentID, DepartmentName, Location) VALUES (3, 'IT',
'California');
-- Insert data into Employee table
INSERT INTO Employee (EmployeeID, Name, Designation, Salary, DepartmentID, HireDate)
VALUES (101, 'Alice', 'Manager', 80000, 1, TO_DATE('2021-06-01', 'YYYY-MM-DD'));
INSERT INTO Employee (EmployeeID, Name, Designation, Salary, DepartmentID, HireDate)
VALUES (102, 'Bob', 'Analyst', 60000, 2, TO_DATE('2022-04-15', 'YYYY-MM-DD'));
INSERT INTO Employee (EmployeeID, Name, Designation, Salary, DepartmentID, HireDate)
VALUES (103, 'Charlie', 'Developer', 70000, 3, TO_DATE('2020-09-23', 'YYYY-MM-DD'));
INSERT INTO Employee (EmployeeID, Name, Designation, Salary, DepartmentID, HireDate)
VALUES (104, 'David', 'Tester', 50000, 3, TO_DATE('2023-01-10', 'YYYY-MM-DD'));
INSERT INTO Employee (EmployeeID, Name, Designation, Salary, DepartmentID, HireDate)
VALUES (105, 'Eva', 'HR Specialist', 45000, 1, TO_DATE('2021-07-11', 'YYYY-MM-DD'));
Step 3: SQL Queries
1. SELECT Statements: Restricting and Sorting Data
Problem: Select employee names, designations, and salaries. Sort by salary in descending order and restrict the
query to employees with a salary greater than 50,000.
SELECT Name, Designation, Salary
FROM Employee
WHERE Salary > 50000
ORDER BY Salary DESC;
• Explanation: This query selects employee names, designations, and salaries, restricts it to those with a salary
greater than 50,000, and sorts the result in descending order by salary.
2. Single-Row Functions
Problem: Display the names of employees in uppercase and their hire date formatted as 'DD-Mon-YYYY'.
SELECT UPPER(Name) AS EmployeeName,
TO_CHAR(HireDate, 'DD-Mon-YYYY') AS HireDateFormatted
FROM Employee;
• Explanation: The UPPER() function converts the employee name to uppercase, and TO_CHAR() formats the
hire date in the 'DD-Mon-YYYY' format.
3. Displaying Data from Multiple Tables (JOINs)
Problem: Display the employee names along with their department names.
SELECT e.Name, d.DepartmentName
FROM Employee e
JOIN Department d ON e.DepartmentID = d.DepartmentID;
• Explanation: The JOIN clause connects the Employee and Department tables on the DepartmentID field,
and the query displays employee names along with their respective department names.
4. Aggregating Data Using Group Functions
Problem: Find the total salary, average salary, and number of employees in each department.
SELECT d.DepartmentName, COUNT(e.EmployeeID) AS NumEmployees,
SUM(e.Salary) AS TotalSalary, AVG(e.Salary) AS AvgSalary
FROM Employee e
JOIN Department d ON e.DepartmentID = d.DepartmentID
GROUP BY d.DepartmentName;
• Explanation: The COUNT(), SUM(), and AVG() functions aggregate the data, grouping by the department name.
It calculates the total number of employees, the total salary, and the average salary per department.
5. Data Manipulation (INSERT, DELETE, UPDATE)
• INSERT Multiple Rows:
INSERT INTO Employee (EmployeeID, Name, Designation, Salary, DepartmentID,
HireDate)
VALUES (106, 'Frank', 'Accountant', 55000, 2, TO_DATE('2022-10-25', 'YYYY-MM-DD')),
(107, 'Grace', 'HR Assistant', 40000, 1, TO_DATE('2023-05-01', 'YYYY-MM-
DD'));
• DELETE: Delete employees from the 'IT' department.
DELETE FROM Employee
WHERE DepartmentID = (SELECT DepartmentID FROM Department WHERE DepartmentName =
'IT');
• UPDATE: Update the salary of employees in the 'Finance' department by increasing it by 10%.
UPDATE Employee
SET Salary = Salary * 1.10
WHERE DepartmentID = (SELECT DepartmentID FROM Department WHERE DepartmentName =
'Finance');
Step 4: View the Data
To check the data in the tables after running these queries, use the following commands:
-- View Employee data
SELECT * FROM Employee;
-- View Department data
SELECT * FROM Department;
Implementation of advanced SQL queries using Sub Queries, and Correlated Sub Queries.
LAB PRACTICAL
Step 1: Create the Tables
We will create two tables for this exercise: Employee and Department.
-- Create Department table
CREATE TABLE Department (
DepartmentID NUMBER PRIMARY KEY,
DepartmentName VARCHAR2(50),
Location VARCHAR2(50)
);
-- Create Employee table
CREATE TABLE Employee (
EmployeeID NUMBER PRIMARY KEY,
Name VARCHAR2(50),
Designation VARCHAR2(50),
Salary NUMBER(10, 2),
DepartmentID NUMBER,
FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID)
);
Step 2: Insert Sample Data
Populate the tables with some sample data.
-- Insert data into Department table
INSERT INTO Department (DepartmentID, DepartmentName, Location) VALUES (1, 'HR', 'New
York');
INSERT INTO Department (DepartmentID, DepartmentName, Location) VALUES (2, 'Finance',
'London');
INSERT INTO Department (DepartmentID, DepartmentName, Location) VALUES (3, 'IT',
'California');
-- Insert data into Employee table
INSERT INTO Employee (EmployeeID, Name, Designation, Salary, DepartmentID)
VALUES (101, 'Alice', 'Manager', 80000, 1);
INSERT INTO Employee (EmployeeID, Name, Designation, Salary, DepartmentID)
VALUES (102, 'Bob', 'Analyst', 60000, 2);
INSERT INTO Employee (EmployeeID, Name, Designation, Salary, DepartmentID)
VALUES (103, 'Charlie', 'Developer', 70000, 3);
INSERT INTO Employee (EmployeeID, Name, Designation, Salary, DepartmentID)
VALUES (104, 'David', 'Tester', 50000, 3);
INSERT INTO Employee (EmployeeID, Name, Designation, Salary, DepartmentID)
VALUES (105, 'Eva', 'HR Specialist', 45000, 1);
Step 3: Advanced SQL Queries using Subqueries
Example 1: Subquery in the WHERE Clause
Problem: Find employees whose salary is greater than the average salary of all employees.
SELECT Name, Salary
FROM Employee
WHERE Salary > (SELECT AVG(Salary) FROM Employee);
• This query uses a subquery to calculate the average salary of all employees. The outer query then selects
employees who earn more than this average.
Example 2: Subquery in the FROM Clause
Problem: Retrieve the employee names and department names using a subquery in the FROM clause.
SELECT e.Name, d.DepartmentName
FROM Employee e, (SELECT DepartmentID, DepartmentName FROM Department) d
WHERE e.DepartmentID = d.DepartmentID;
• The subquery retrieves department information, and the outer query joins it with employee data to display each
employee’s department.
Step 4: Correlated Subqueries
Example 1: Correlated Subquery in the WHERE Clause
Problem: Find employees whose salary is greater than the average salary of their department.
SELECT Name, Salary
FROM Employee e
WHERE Salary > (SELECT AVG(Salary)
FROM Employee
WHERE DepartmentID = e.DepartmentID);
• The correlated subquery calculates the average salary for the current employee’s department. The outer query
retrieves employees who earn more than this department’s average.
Example 2: Correlated Subquery with EXISTS
Problem: Find all employees who earn more than at least one other employee in the same department.
SELECT e1.Name, e1.Salary
FROM Employee e1
WHERE EXISTS (SELECT 1
FROM Employee e2
WHERE e2.DepartmentID = e1.DepartmentID
AND e2.Salary < e1.Salary);
• The EXISTS clause checks whether there is at least one employee in the same department with a lower salary
than the current employee. If such an employee exists, the current employee’s data is returned.
Step 5: Data and Table Output for Queries
You can view the data stored in the tables after execution by running these queries:
-- View Employee data
SELECT * FROM Employee;
-- View Department data
SELECT * FROM Department;
The data stored in the Employee and Department tables would look something like this:
Employee Table:
EmployeeID Name Designation Salary DepartmentID
101 Alice Manager 80000 1
102 Bob Analyst 60000 2
103 Charlie Developer 70000 3
104 David Tester 50000 3
105 Eva HR Specialist 45000 1
Department Table:
DepartmentID DepartmentName Location
1 HR New York
2 Finance London
3 IT California
Key Differences: Subqueries vs Correlated Subqueries
• Subquery: The subquery is independent of the outer query and is executed once.
• Correlated Subquery: The subquery depends on the outer query, is executed for each row processed by the
outer query, and often references columns from the outer query.
Cartesian Definition:
A Cartesian Product occurs when there is no condition to limit or specify the match between rows of two tables.
This results in every possible combination of rows between the tables.
Syntax:
SELECT *
FROM table1, table2;
Alternatively:
SELECT *
FROM table1
CROSS JOIN table2;
Example:
Consider two tables, Students and Courses:
Table: Students
Student_ID Student_Name
1 John
2 Sarah
Table: Courses
Course_ID Course_Name
101 Math
102 Science
If we perform a Cartesian Product of these two tables:
SELECT *
FROM Students, Courses;
The result will be:
Student_ID Student_Name Course_ID Course_Name
1 John 101 Math
1 John 102 Science
2 Sarah 101 Math
2 Sarah 102 Science
Key Points:
• The result of a Cartesian Product can be very large since every row from the first table is combined with
every row from the second table.
• It is typically used when no specific join condition is applied.
• In practice, it’s often undesirable unless you're specifically looking for all possible combinations.
In most cases, a Cartesian Product is not useful without conditions (like a join) to limit the results.
❖ Primary Key, Foreign Key, Candidate Key, and Super Key are used in the
Student and Course tables, along with their explanations.
1. Primary Key
A Primary Key is a unique identifier for a record in a table. It ensures that each record is unique and cannot
contain NULL values.
• In the Course table, CourseID is the Primary Key. This means each course has a unique CourseID that
identifies it distinctly.
• In the Student table, StudentID is the Primary Key. Each student has a unique StudentID to identify their
record in the database.
Example Code:
CREATE TABLE Course (
CourseID INT PRIMARY KEY, -- Primary Key in Course table
CourseName VARCHAR(50) NOT NULL
);
CREATE TABLE Student (
StudentID INT PRIMARY KEY, -- Primary Key in Student table
FirstName VARCHAR(50),
LastName VARCHAR(50),
DOB DATE,
Age INT,
Marks DECIMAL(5, 2),
CourseID INT, -- Foreign Key referring to Course table
FOREIGN KEY (CourseID) REFERENCES Course(CourseID)
);
Explanation:
The Primary Key constraint ensures that CourseID in the Course table and StudentID in the Student table
are unique identifiers for each row. No two courses can have the same CourseID, and no two students can have
the same StudentID.
2. Foreign Key
A Foreign Key is a field (or collection of fields) in one table that refers to the Primary Key in another table. It
is used to establish and enforce a link between the data in the two tables.
• In the Student table, CourseID is a Foreign Key that references CourseID in the Course table. This creates a
relationship where each student is linked to a specific course.
Explanation:
The Foreign Key constraint on CourseID in the Student table enforces referential integrity between the
Student and Course tables. This means each student must be assigned an existing CourseID from the Course
table. If you try to add a student with a CourseID that doesn’t exist in the Course table, it will result in an error.
3. Candidate Key
A Candidate Key is a column, or set of columns, that can uniquely identify a row in a table. Each Candidate
Key can qualify as a Primary Key, and a table can have multiple Candidate Keys.
In the Student table:
• StudentID is a Candidate Key because it uniquely identifies each student.
• If we add another column Email, this could also be a Candidate Key if each student has a unique email address.
In the Course table:
• CourseID is a Candidate Key because it uniquely identifies each course.
• If we added a unique CourseCode (e.g., "MATH101"), it could also serve as a Candidate Key.
Explanation:
Each Candidate Key is capable of being a Primary Key, but only one Candidate Key is selected as the
Primary Key (e.g., StudentID and CourseID in our case). Candidate Keys help maintain data integrity by
identifying unique records.
4. Super Key
A Super Key is any combination of columns that can uniquely identify a row in a table. Super Keys include
Primary Keys, Candidate Keys, and any additional combinations of attributes that uniquely identify a record.
In the Student table:
• StudentID alone is a Super Key.
• The combination of StudentID and FirstName is also a Super Key (though it’s redundant).
In the Course table:
• CourseID alone is a Super Key.
• If we added CourseID and CourseName together, they would form another Super Key (though again,
redundant).
Explanation:
While Primary Keys and Candidate Keys are minimal unique identifiers, Super Keys can include extra
attributes that still uniquely identify records. Super Keys are useful in defining unique constraints beyond
minimal identifiers.
Summary Table of Key Usage:
Key Type Definition Example in Course Table Example in Student Table
Uniquely identifies each record in the
Primary Key CourseID StudentID
table
References a Primary Key in another CourseID (references
Foreign Key -
table CourseID)
Candidate Can uniquely identify each record CourseID, CourseCode (if
StudentID, Email (if unique)
Key (subset of Super Key) added)
Any set of columns that can uniquely CourseID, CourseID + StudentID, StudentID +
Super Key
identify a record CourseName FirstName
NOTE: In SQL, Candidate Keys and Super Keys are concepts more than specific constraints, as SQL does
not have direct syntax for creating Candidate Keys or Super Keys. However, we can use UNIQUE constraints
and PRIMARY KEY constraints to enforce these concepts. Here’s how you can implement them indirectly:
1. Candidate Key
A Candidate Key is a column or a set of columns that could serve as a Primary Key. You can designate
Candidate Keys using the UNIQUE constraint to ensure that each candidate key has unique values in the table.
Example Syntax:
Consider the Student table where StudentID is the Primary Key, and we want Email as a Candidate Key.
CREATE TABLE Student (
StudentID INT PRIMARY KEY, -- Primary Key
FirstName VARCHAR(50),
LastName VARCHAR(50),
Email VARCHAR(100) UNIQUE, -- Candidate Key (Email should be unique)
CourseID INT
);
In this example:
• StudentID is the Primary Key.
• Email is a Candidate Key due to the UNIQUE constraint.
Explanation:
The UNIQUE constraint on Email ensures that each email is unique across records, qualifying it as a
Candidate Key.
2. Super Key
A Super Key is any combination of columns that can uniquely identify a row in a table. While SQL does not
have a specific constraint for Super Keys, you can define additional UNIQUE constraints on a combination of
columns.
Example Syntax:
Define a Super Key by combining StudentID and Email to uniquely identify each record in the Student table.
CREATE TABLE Student (
StudentID INT,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Email VARCHAR(100),
CourseID INT,
PRIMARY KEY (StudentID),
UNIQUE (StudentID, Email) -- Super Key (combination of StudentID and Email)
);
In this example:
• StudentID is the Primary Key.
• (StudentID, Email) forms a Super Key because the combination of these two fields is unique for each row.
Explanation:
By using UNIQUE (StudentID, Email), we define a Super Key that uniquely identifies each record with this
combination, though it’s not a minimal unique identifier like a Candidate Key.
Summary:
• Candidate Key: Use the UNIQUE constraint on individual columns that could serve as additional identifiers (e.g.,
Email in the Student table).
• Super Key: Use the UNIQUE constraint on combinations of columns that can uniquely identify rows but are not
necessarily minimal (e.g., StudentID + Email in the Student table).
In practice, Primary Keys and UNIQUE constraints provide the structure needed to support the concepts of
Candidate and Super Keys.