Database Management System - Relational database concepts, primary keys, foreign keys, creating tables, and basic SQL queries
Data is one of the most vital assets of modern civilization. From national identification systems and online school portals to global banking networks, millions of transactions occur every second. Managing this overwhelming volume of data efficiently, securely, and without redundancy requires specialized software systems known as Database Management Systems (DBMS).
In a traditional file-processing system (such as storing data in separate spreadsheets or paper registers), data is vulnerable to duplication (redundancy), inconsistency, lack of security, and structural rigidity. A Relational Database Management System (RDBMS) overcomes these limitations by organizing data into interconnected tables based on well-defined mathematical principles of set theory. Understanding relational database concepts, primary and foreign key constraints, table design, and Structured Query Language (SQL) is essential for mastering computing curriculum and building real-world digital applications.
1. In-Depth Conceptual Breakdown
1.1 Fundamental Database Terminology
To understand relational databases, we must first distinguish between raw data, information, and the relational structures that organize them.
- Data: Raw, unorganized facts, figures, symbols, or observations (e.g., ,
101,"Aarav").95.5 - Information: Processed, structured data presented in a meaningful context (e.g., "Student Aarav, Roll No. 101, scored 95.5% in Mathematics").
- Database: An organized collection of logically related data stored electronically for easy access, management, and updating.
- RDBMS (Relational Database Management System): A DBMS based on the relational model introduced by E.F. Codd in 1970. In an RDBMS, data is represented in two-dimensional tables called relations. Popular RDBMS tools include MySQL, PostgreSQL, SQLite, Oracle, and LibreOffice Base.
Components of a Relation (Table)
A table (or relation) consists of horizontal rows and vertical columns.
+---------+--------------+-------+-------------+ | Roll_No | Student_Name | Class | Total_Marks | <-- Column Headers (Attributes) +---------+--------------+-------+-------------+ | 101 | Aarav Sharma | 10A | 485 | <-- Row 1 (Tuple) | 102 | Priya Verma | 10A | 492 | <-- Row 2 (Tuple) | 103 | Rohan Mehta | 10B | 440 | <-- Row 3 (Tuple) +---------+--------------+-------+-------------+
- Attribute (Column / Field): A named column in a table representing a specific characteristic or property of an entity. For example, ,
Roll_No,Student_Name, andClassare attributes.Total_Marks - Tuple (Row / Record): A single horizontal row in a table representing a complete set of attribute values for a single entity.
- Domain: The set of all permissible atomic (indivisible) values for a given attribute. For example, the domain of might be restricted to
Class.{'10A', '10B', '10C'} - Degree: The total number of attributes (columns) present in a table. In the table above, Degree .
- Cardinality: The total number of tuples (rows) present in a table (excluding the header row). In the table above, Cardinality .
1.2 Keys in Relational Database Systems
Keys are individual columns or combinations of columns used to uniquely identify records, enforce data integrity, and establish relationships between different tables.
[ All Available Column Combinations ] │ ▼ [ CANDIDATE KEYS ] (All keys capable of unique identification) / \ / \ ▼ ▼ [ PRIMARY KEY ] [ ALTERNATE KEYS ] (Chosen as main identifier) (Remaining candidate keys)
Types of Keys
- Candidate Key: Any attribute or minimal set of attributes that can uniquely identify every tuple in a table. A table can have multiple candidate keys.
- Primary Key: A specific candidate key selected by the database designer to uniquely identify each tuple in a table.
- Rule 1: It must contain unique values for every row.
- Rule 2: It cannot contain NULL values (unspecified or missing values).
- Rule 3: A table can have only one Primary Key.
- Alternate Key: Any candidate key that was not chosen as the primary key.
- Composite Primary Key: A primary key that consists of two or more attributes combined together to uniquely identify a record when no single attribute is sufficient.
- Foreign Key: An attribute or combination of attributes in a table whose values are derived from and reference the Primary Key of another table (or the same table).
- The table containing the foreign key is called the Child Table (or Referencing Table).
- The table containing the referenced primary key is called the Parent Table (or Referenced Table).
- Referential Integrity: A foreign key value must either match an existing primary key value in the parent table or be .
NULL
Comparison Matrix: Primary Key vs. Foreign Key vs. Candidate Key
| Feature | Primary Key | Foreign Key | Candidate Key |
|---|---|---|---|
| Primary Purpose | Uniquely identifies a record in a table. | Links two tables and maintains referential integrity. | Eligible candidate to uniquely identify a row. |
| Null Values | Not Allowed ( | Allowed (unless explicitly defined | Allowed (unless designated as Primary Key). |
| Number per Table | Exactly One. | Multiple allowed. | Multiple allowed. |
| Uniqueness | Values must be strictly unique. | Values can repeat (matches Parent PK). | Values must be strictly unique. |
1.3 Introduction to SQL (Structured Query Language)
SQL is the standard language used to communicate with Relational Database Management Systems. SQL commands are categorized into functional sub-languages based on their operations:
- DDL (Data Definition Language): Used to define, alter, or delete database structures and schemas.
- Commands: ,
CREATE,ALTER,DROP.TRUNCATE
- Commands:
- DML (Data Manipulation Language): Used to manipulate and modify data contained within relations.
- Commands: ,
INSERT,UPDATE.DELETE
- Commands:
- DQL (Data Query Language): Used to retrieve data from relations.
- Commands: .
SELECT
- Commands:
Essential SQL Data Types
| Data Type | Description | Example |
|---|---|---|
| Whole numbers without decimals. | |
| Variable-length text up to length . Saves memory space. | |
| Fixed-length text of exact length . Pads remaining space with blanks. | |
| Fixed-point numbers with total digits and decimal places. | |
| Calendar date formatted as | |
1.4 Detailed SQL Syntax & Operations
1. Creating Tables (CREATE TABLE
)
CREATE TABLEThe
CREATE TABLECREATE TABLE Student ( Roll_No INT PRIMARY KEY, Student_Name VARCHAR(50) NOT NULL, Class VARCHAR(5), DOB DATE, Marks DECIMAL(5,2) );
2. Inserting Data (INSERT INTO
)
INSERT INTOThe
INSERT INTO-- Syntax 1: Inserting values for all columns in order INSERT INTO Student VALUES (101, 'Aarav Sharma', '10A', '2008-05-14', 485.50); -- Syntax 2: Inserting values for specific columns INSERT INTO Student (Roll_No, Student_Name, Class) VALUES (102, 'Priya Verma', '10A');
3. Querying Data (SELECT
)
SELECTThe
SELECT
- Select All Columns:
SELECT * FROM Student; - Select Specific Columns:
SELECT Roll_No, Student_Name FROM Student; - Filtering Rows (Clause):
WHERESELECT * FROM Student WHERE Marks >= 400.00 AND Class = '10A'; - Sorting Output (Clause):
ORDER BYSELECT * FROM Student ORDER BY Marks DESC; - Pattern Matching Operators ():
LIKE- represents zero or more characters.
% - represents exactly one character.
_
-- Names starting with 'A' SELECT * FROM Student WHERE Student_Name LIKE 'A%'; -- Names having 'a' as the second letter SELECT * FROM Student WHERE Student_Name LIKE '_a%';
4. Updating Records (UPDATE
)
UPDATEThe
UPDATEUPDATE Student SET Marks = 490.00, Class = '10B' WHERE Roll_No = 101;
5. Deleting Records (DELETE
)
DELETEThe
DELETEDELETE FROM Student WHERE Roll_No = 102;
2. Real-World Applications & Analogies
Application 1: School Information System
Consider a school management system that handles thousands of students, teachers, and examination records.
+------------------------------------+ | STUDENT TABLE | +------------------------------------+ | PK: Roll_No | | Name, Class, Contact_No | +------------------------------------+ │ │ 1-to-Many Relationship ▼ +------------------------------------+ | MARKS TABLE | +------------------------------------+ | PK: Mark_ID | | FK: Roll_No (References STUDENT) | | Subject, Marks_Obtained | +------------------------------------+
- Primary Key Role: uniquely identifies each student. Even if two students share the name "Rahul Sharma", their unique
Roll_Noprevents administrative errors.Roll_No - Foreign Key Role: In the table,
MARKSacts as a Foreign Key referencing theRoll_Notable. This ensures that marks cannot be entered for a non-existent student roll number (referential integrity).STUDENT
Application 2: E-Commerce Order Management Analogy
Imagine buying items on an e-commerce website like Amazon or Flipkart:
- Customer Table: Contains (Primary Key), Name, Address, Phone.
Customer_ID - Order Table: Contains (Primary Key),
Order_ID(Foreign Key referencing Customer Table),Customer_ID,Order_Date.Total_Amount
Why split this into two tables? If customer details were repeated in every order line, updating an address would require changing thousands of records (Update Anomaly). Splitting data into relations linked by
Customer_ID3. Step-by-Step Solved Textbook Examples
Example 1: Determining Table Attributes, Degree, Cardinality, and Keys
Given the following relation
EMPLOYEE| Emp_ID | Aadhaar_No | Emp_Name | Department | Salary |
|---|---|---|---|---|
| E101 | 4521-8890-1234 | Ananya Das | HR | 55000 |
| E102 | 9812-3341-5567 | Bikram Roy | IT | 72000 |
| E103 | 1120-4451-9988 | Chitra Sen | Finance | 68000 |
| E104 | 7765-1109-4321 | Deepak Nag | IT | 72000 |
Questions:
- State the Degree and Cardinality of the relation.
- Identify all Candidate Keys.
- If is designated as the Primary Key, name the Alternate Key.
Emp_ID
Solution:
-
Step 1: Calculate Degree
- Count total columns: ,
Emp_ID,Aadhaar_No,Emp_Name,Department.Salary
- Count total columns:
-
Step 2: Calculate Cardinality
- Count total rows (excluding header): 4 data rows.
-
Step 3: Identify Candidate Keys
- is unique for every employee.
Emp_ID - is unique for every citizen/employee.
Aadhaar_No - Candidate Keys =
{Emp_ID, Aadhaar_No}
-
Step 4: Identify Alternate Key
- If , then:
Primary Key = Emp_ID
- If
Example 2: DDL Table Creation with Constraints
Problem: Create a table named
BOOK- : Integer, must be the Primary Key.
Book_ID - : Text string up to 100 characters, cannot be empty.
Title - : Text string up to 50 characters.
Author - : Floating-point decimal with 2 decimal places.
Price - : Date format.
Pub_Date
Solution:
To construct the query, match each requirement to its SQL keyword:
- Primary Key constraint
PRIMARY KEY - Cannot be empty
NOT NULL - Text up to chars
VARCHAR(N) - Decimal
DECIMAL(precision, scale)
CREATE TABLE BOOK ( Book_ID INT PRIMARY KEY, Title VARCHAR(100) NOT NULL, Author VARCHAR(50), Price DECIMAL(7,2), Pub_Date DATE );
Example 3: Complex SQL Data Filtering & Manipulation Queries
Given the table
PRODUCT| P_Code | P_Name | Category | Price | Quantity |
|---|---|---|---|---|
| P01 | Mechanical Keyboard | Electronics | 3500.00 | 15 |
| P02 | Wireless Mouse | Electronics | 1200.00 | 40 |
| P03 | Wooden Desk | Furniture | 8500.00 | 5 |
| P04 | Ergonomic Chair | Furniture | 12500.00 | 8 |
| P05 | USB-C Cable | Electronics | 450.00 | 100 |
Write SQL statements for the following operational queries:
- Display and
P_Nameof all products in thePricecategory priced below'Electronics'.2000.00 - Increase the of all
Priceitems by .'Furniture' - Delete all products whose is less than 10.
Quantity - Display all products arranged by from highest to lowest.
Price
Solution:
-
Query 1: Data Selection with Multiple Conditions
SELECT P_Name, Price FROM PRODUCT WHERE Category = 'Electronics' AND Price < 2000.00; -
Query 2: Updating Numerical Values with Calculations
UPDATE PRODUCT SET Price = Price * 1.10 WHERE Category = 'Furniture'; -
Query 3: Deleting Rows Based on Numeric Condition
DELETE FROM PRODUCT WHERE Quantity < 10; -
Query 4: Sorting Output
SELECT * FROM PRODUCT ORDER BY Price DESC;
4. Common Student Mistakes to Avoid
Mistake 1: Confusing CHAR
and VARCHAR
Data Types
CHARVARCHAR- The Error: Using for names, thinking it dynamic saves memory.
CHAR(20) - The Fact: is fixed-length. Storing
CHAR(20)(3 characters) in"Raj"forces the system to pad 17 blank space characters, wasting memory.CHAR(20)allocates only 3 characters dynamically. UseVARCHAR(20)for fixed-length codes (e.g.,CHARGender,'M'/'F'Country_Code) and'IND'for varying names/addresses.VARCHAR
Mistake 2: Using Equality (=
) Instead of IS NULL
for Missing Values
=IS NULL- Incorrect SQL:
SELECT * FROM Student WHERE Marks = NULL; - Correct SQL:
SELECT * FROM Student WHERE Marks IS NULL; - Reason: In SQL logic, represents an unknown value. Standard relational comparison operators (
NULL,=,<>) with<evaluate toNULL(false), returning zero rows.UNKNOWN
Mistake 3: Confusing DELETE
, DROP
, and TRUNCATE
DELETEDROPTRUNCATE- : Removes rows/records based on conditions. Table structure remains intact. (DML Command)
DELETE FROM TableName - : Destroys the entire table structure along with all data permanently. (DDL Command)
DROP TABLE TableName - : Removes all rows instantly, preserving the structure for future inserts. (DDL Command)
TRUNCATE TABLE TableName
Mistake 4: Omitting Quotes for Strings and Dates in Queries
- Incorrect SQL:
SELECT * FROM Student WHERE Class = 10A AND DOB = 2008-05-14; - Correct SQL:
SELECT * FROM Student WHERE Class = '10A' AND DOB = '2008-05-14'; - Reason: Numeric values (,
INT) are written without quotes. Non-numeric literals (DECIMAL,VARCHAR,CHAR) must always be enclosed in single or double quote marks.DATE
5. Practice Questions for Self-Assessment
Question 1
Consider the relation
DOCTOR| Doc_ID | Doc_Name | Specialization | Salary | Joining_Date |
|---|---|---|---|---|
| D101 | Dr. K. S. Rao | Cardiology | 120000 | 2015-03-10 |
| D102 | Dr. Anita Ray | Pediatrics | 95000 | 2018-07-22 |
| D103 | Dr. M. Verma | Neurology | 140000 | 2012-11-05 |
| D104 | Dr. S. Kapoor | Pediatrics | 90000 | 2020-01-15 |
- Write the SQL command to create the above table with as the primary key.
Doc_ID - What is the degree and cardinality of this table?
- Write an SQL query to display the names and salaries of doctors who joined before and earn more than
'2016-01-01'.100000
Solution:
- Table Creation Query:
CREATE TABLE DOCTOR ( Doc_ID VARCHAR(10) PRIMARY KEY, Doc_Name VARCHAR(50) NOT NULL, Specialization VARCHAR(30), Salary INT, Joining_Date DATE ); - Degree and Cardinality:
- Degree (columns)
- Cardinality (rows)
- Data Retrieval Query:
SELECT Doc_Name, Salary FROM DOCTOR WHERE Joining_Date < '2016-01-01' AND Salary > 100000;
Question 2
Explain the concept of Foreign Key with an example. What is Referential Integrity?
Solution:
- Foreign Key Definition: A Foreign Key is a non-key attribute (or combination of attributes) in a child table whose values must match the Primary Key of a parent table.
- Example:
- Parent Table: (
DEPARTMENT[PK],Dept_ID)Dept_Name - Child Table: (
EMPLOYEE[PK],Emp_ID,Emp_Name[FK referencingDept_ID])DEPARTMENT
- Parent Table:
- Referential Integrity: A database rule ensuring that relationships between tables remain consistent. It dictates that any value in a Foreign Key column must exist in the Primary Key column of the referenced Parent table. You cannot insert an employee with a of
Dept_IDifD99does not exist in theD99table.DEPARTMENT
Question 3
Write SQL statements for the
STUDENTRoll_NoNameStreamMarksCity- Display records of all students living in either or
'Delhi'.'Mumbai' - Display all unique values available in the table.
Stream - Increase by 5 points for all students in the
Marksstream.'Science'
Solution:
- Using the Operator:
INSELECT * FROM STUDENT WHERE City IN ('Delhi', 'Mumbai'); - Using the Keyword:
DISTINCTSELECT DISTINCT Stream FROM STUDENT; - Updating Data:
UPDATE STUDENT SET Marks = Marks + 5 WHERE Stream = 'Science';
6. Exam Revision & FAQs
Q1: What is the primary difference between DDL and DML commands?
Answer:
- DDL (Data Definition Language) commands define, alter, or drop the structure/schema of database objects (tables, indexes). They do not directly alter stored data records. Examples: ,
CREATE,ALTER.DROP - DML (Data Manipulation Language) commands operate directly on the data records/tuples stored within tables to insert, modify, or delete contents without changing table structure. Examples: ,
INSERT,UPDATE.DELETE
Q2: Can a table have multiple Primary Keys? Explain.
Answer: No. A table can have only one Primary Key. However, a single Primary Key can be composed of multiple combined columns. When two or more columns together form a single primary key, it is called a Composite Primary Key.
Q3: What is the purpose of the LIKE
operator in SQL? Name its two wildcard characters.
LIKEAnswer: The
LIKEWHERE- (Percent sign): Represents zero, one, or multiple characters.
% - (Underscore sign): Represents a single character.
_
Q4: If a table initially has columns and rows, and a user inserts new rows and adds new column, what will be the new Degree and Cardinality?
Answer:
- Initial state: , .
- Adding column increases the Degree: .
- Inserting rows increases the Cardinality: .
- Final Answer: New Degree = , New Cardinality = .