Relational Database Management System (RDBMS) & MySQL
Understanding RDBMS • Keys & Constraints • Introduction to MySQL • DDL & DML Commands • Operators & Clauses
No matching notes found
Try searching for another SQL keyword, table name, or concept.
Introduction to Database Management System (DBMS)
In today’s era of Big Data, organizations such as schools, libraries, airlines, police forces, medical research centers, and entertainment industries rely on computerized databases to store and retrieve large volumes of information efficiently.
1.1 What is a DBMS?
A Database Management System (DBMS) is specialized software that enables users to create, store, modify, and maintain databases on a computer.
1.2 Core Functions & Benefits of a DBMS
Structured Data Storage
Organizes data systematically in tables, records, and fields.
Querying & Manipulation
Allows users to ask questions (queries), sort, filter, and update data easily.
Data Validation
Checks entered data against rules to prevent inconsistencies and invalid entries.
Flexible Reporting
Generates clear on-screen and printed reports for decision-making.
Controls Data Redundancy
Minimizes unnecessary duplication of the same data across multiple files.
Avoids Inconsistency
Updating data in one place ensures consistent values everywhere.
Data Sharing & Security
Allows multiple authorized users to share data while enforcing strict access controls.
1.3 Relational Database Management System (RDBMS)
A Relational Database stores data in multiple separate tables that are linked together through common columns (keys). For example, in a Learner database:
Stores StudentName and StudentID.
Links StudentID with the Activity enrolled in.
Links Activity with its respective Cost.
RDBMS Terminology & Database Keys
| Term | Alias / Also Known As | Definition & Key Properties |
|---|---|---|
| Table | Relation | A two-dimensional representation of data organized in horizontal rows and vertical columns. |
| Row | Tuple / Record | A horizontal subset of a table representing a complete set of related data about a single entity (e.g., one student or customer). |
| Column | Attribute / Field | A vertical subset of a table with a unique name within that table. All values in a column must share the same data type. |
| Domain | Value Pool | The pool or set of all possible valid values from which a column’s actual values are derived. |
2.1 Types of Keys in an RDBMS
A Key is a column or combination of columns used to identify one or more rows (tuples) in a table:
| Key Type | Definition | Key Rules & Examples |
|---|---|---|
| Primary Key | A column or group of columns chosen to uniquely identify every row in a table. | Cannot contain NULL or duplicate values. A table can have only ONE primary key (though it may span multiple columns as a composite primary key). Examples: Admission_No, EmpID, Flight_No. |
| Candidate Key | Any column or set of columns capable of uniquely identifying each row in a table. | Every candidate key is eligible to become the Primary Key. Example: Both Admission_No and RollNo in a class table. |
| Alternate Key | A Candidate Key that is NOT selected as the Primary Key. | Example: If Admission_No is chosen as the Primary Key, RollNo becomes the Alternate Key. |
| Foreign Key | A column in one table that refers to the Primary Key of another base table to establish a link. | Must have the same data type and size as the referenced Primary Key. Example: DEPTID in Employee table referencing DEPTID (PK) in Department table. |
Introduction to MySQL & Data Types
MySQL (pronounced “My Sequel”) is an open-source Relational Database Management System originally developed in Sweden by David Axmark, Allan Larsson, and Michael Widenius.
3.1 Key Characteristics of MySQL
Open-Source & Free
Released under an open-source license (GPL); free to download, use, and customize.
High Speed & Reliability
Capable of handling large datasets quickly and reliably.
ANSI-SQL Standard
Follows standard Structured Query Language (SQL) syntax.
Platform Independent
Runs across Windows, Linux, UNIX, and macOS, and integrates with Java, C++, PHP, Python, and Perl.
3.2 Categories of SQL Commands
| Category | Full Form | Purpose | Common Commands |
|---|---|---|---|
| DDL | Data Definition Language | Defines, modifies, or deletes database structures (databases, tables, columns, keys, constraints). | CREATE DATABASE, CREATE TABLE, ALTER TABLE, DROP TABLE |
| DML | Data Manipulation Language | Retrieves, inserts, modifies, or deletes the actual data records stored inside tables. | SELECT, INSERT INTO, UPDATE, DELETE |
| DCL | Data Control Language | Manages user permissions, access rights, and database security. | GRANT, REVOKE |
3.3 Common MySQL Data Types
| Category | Data Type | Description | Example |
|---|---|---|---|
| Text | CHAR(size) | Fixed-length string (1 to 255 chars). Right-padded with spaces to the defined size. Enclosed in single/double quotes. | ‘Maths’, “Text” |
| Text | VARCHAR(size) | Variable-length string (1 to 255 chars). Uses only the storage needed for actual characters. | ‘Computer’, “Hello” |
| Numeric | INT / INTEGER | Stores whole numbers (integers) without fractional parts (width up to 11 digits). | 76, 1024 |
| Numeric | DECIMAL(size, d) | Stores exact numbers with fractional parts. ‘size’ = total digits; ‘d’ = digits after decimal point. | 17.32, 345.00 |
| Date | DATE | Stores date values in standard ‘YYYY-MM-DD’ format. | ‘2009-07-02’ |
| Time | TIME | Stores time values in ‘HH:MM:SS’ format. | ’14:30:00′ |
Database & Table Management (DDL Commands)
4.1 Database Operations
Basic Database Management Commands (Every SQL statement ends with a semicolon ';')
-- 1. Create a new database
CREATE DATABASE School;
-- 2. Open/select a database to work in
USE School;
-- 3. View the name of the currently active database
SELECT DATABASE();
-- 4. List all tables in the current database
SHOW TABLES;
4.2 Table Creation & Naming Rules
-
Case Insensitivity: Table and column names are not case-sensitive (
STUDENTandstudentare treated identically). -
Valid Characters: Use letters, numbers, and underscores (
_). Spaces and special symbols are invalid (e.g.,first_nameis valid). - Column Uniqueness: Column names must be unique within the same table.
-- Syntax: CREATE TABLE <TableName> (<Col1> <DataType1>, <Col2> <DataType2>, ...);
CREATE TABLE Learner (
RollNo INTEGER,
Name VARCHAR(25)
);
4.3 Integrity Constraints in MySQL
Constraints are rules enforced on table columns to ensure data validity and accuracy:
| Constraint | Purpose & Behavior |
|---|---|
| PRIMARY KEY | Uniquely identifies each row. Automatically rejects NULL values and duplicate entries. Only one PRIMARY KEY is allowed per table. |
| NOT NULL | Ensures a column cannot be left blank (NULL). Rejects records if no value is provided for that column. |
| UNIQUE | Ensures all values in a column are distinct (no duplicates allowed), though NULL may be permitted unless NOT NULL is also set. |
| FOREIGN KEY | Restricts values in a column to only those already existing in the Primary Key column of a parent/referenced table. |
Applying Constraints During Table Creation
-- Single-column Primary Key & NOT NULL constraint
CREATE TABLE Shoes (
Code CHAR(4) PRIMARY KEY,
Name VARCHAR(20),
Type VARCHAR(10),
Size INT(2) NOT NULL,
Cost DECIMAL(6,2),
Qty INT(4)
);
-- Composite Primary Key (combining two columns)
CREATE TABLE Bills (
Order_Num INT(4),
Cust_Code VARCHAR(4),
Bill_Date DATE,
Bill_Amt DECIMAL(8,2) NOT NULL,
PRIMARY KEY (Order_Num, Cust_Code)
);
4.4 Viewing & Modifying Table Structure (DESCRIBE, ALTER TABLE, DROP TABLE)
-- View table structure (columns, data types, Null status, Keys, Defaults)
DESCRIBE Student; -- Short form: DESC Student;
-- Add a new column (existing rows get NULL in this column)
ALTER TABLE Student ADD Games VARCHAR(20);
-- Modify a column's data type or add NOT NULL constraint
ALTER TABLE Student MODIFY Games INTEGER;
ALTER TABLE Bills MODIFY Bill_Date DATE NOT NULL;
-- Remove a column from a table
ALTER TABLE Student DROP Games;
-- Add or Drop a Primary Key
ALTER TABLE Shoes ADD PRIMARY KEY (Code);
ALTER TABLE Shoes DROP PRIMARY KEY;
-- Permanently delete the entire table structure and its data
DROP TABLE Orders;
Data Manipulation Language (DML Commands)
5.1 INSERT INTO Command (Adding Records)
Data Formatting: Numbers are written directly; strings and dates ('YYYY-MM-DD') must be enclosed in single or double quotes; blank values are written as NULL without quotes.
-- Insert values for ALL columns (must match table column order)
INSERT INTO Student VALUES (1, 'ABHISHEK', 'NARULA', 'M', '1998-10-05', 98);
-- Insert values for SELECTED columns only (unspecified columns get NULL)
INSERT INTO Student (Rno, Gender, Lname, Fname) VALUES (8, 'F', 'SHANU', 'DEEPAKSHI');
5.2 SELECT Command & Essential Clauses
The SELECT command retrieves data from one or more tables without altering the stored records.
-- Retrieve specific columns or all columns (*)
SELECT Rno, Fname, Marks FROM Student;
SELECT * FROM Student;
-- Eliminate duplicate values using DISTINCT (ALL displays duplicates)
SELECT DISTINCT Marks FROM Student;
-- Column Aliases (AS) & Custom Display Text
SELECT Rno AS 'Roll Number', Fname AS 'First Name', Marks FROM Student;
SELECT Fname, 'has roll number', Rno AS 'Roll Number' FROM Student;
-- Arithmetic Expressions in SELECT (display-only calculation)
SELECT Fname, Marks + 10 FROM Student WHERE Marks > 90;
5.3 Filtering Records with WHERE & SQL Operators
| Operator Type | Operators / Keywords | Purpose & Example |
|---|---|---|
| Arithmetic | +, -, *, /, % (Modulo) | Performs math on numeric columns. Example: Salary + Salary * 0.1 |
| Relational | =, >, <, >=, <=, != or <> | Compares values in WHERE clause. Example: WHERE Edept <> 'Sales' |
| Logical | AND, OR, NOT | Combines or negates conditions. Example: WHERE Gender = 'F' AND Marks > 90 |
| Range | BETWEEN … AND … | Matches values within an inclusive range. Example: WHERE Marks BETWEEN 92 AND 95 |
| List Membership | IN (…) | Matches any value in a specified list. Example: WHERE Marks IN (88, 92, 95) |
| NULL Check | IS NULL, IS NOT NULL | Tests for missing/NULL values (= NULL is invalid). Example: WHERE Zone IS NULL |
| Pattern Matching | LIKE with % and _ | '%' matches zero or more characters; '_' matches any single character. |
Common LIKE Pattern Examples
'A%' → Starts with ‘A’ (e.g., Abhishek, Akshi)
'%K' → Ends with ‘K’ (e.g., Abhishek, Bhishek)
'_____' (5 underscores) → Exactly 5 characters
'S____' → Starts with ‘S’ and has exactly 5 characters
'___%' → At least 3 characters long
'%in%' → Contains ‘in’ anywhere in the text
5.4 Sorting Results with ORDER BY
The ORDER BY clause sorts query output in ascending (ASC, default) or descending (DESC) order. When sorting in ascending order, NULL values appear first.
-- Sort by marks in ascending order (default)
SELECT Fname, Lname, Marks FROM Student ORDER BY Marks;
-- Multi-column sorting with WHERE filter
SELECT Fname, Lname, Marks FROM Student WHERE Marks > 90 ORDER BY Marks DESC, Fname ASC;
5.5 UPDATE & DELETE Commands
-- UPDATE: Modify existing records matching a condition
UPDATE Student SET Dob = '2004-03-23', Marks = 90 WHERE Fname = 'DEEPAKSHI';
-- Update all rows (when WHERE clause is omitted)
UPDATE Employee SET Esal = Esal + Esal * 0.1;
-- DELETE: Remove specific records from a table
DELETE FROM Student WHERE Rno = 13;
-- Remove ALL records from a table (structure remains intact)
DELETE FROM Student;
Key Exam Distinction: DELETE vs. DROP TABLE
- DELETE (DML): Removes specific rows (or all rows) from a table, while the empty table structure and columns remain in the database.
- DROP TABLE (DDL): Permanently deletes both the data AND the entire table structure from the database.
Solved Chapter Exercises & Lab SQL Queries
6.1 Quick Objective & Conceptual Review
UPDATE
|
Statement to delete records → DELETE
All attributes that can uniquely identify rows are Candidate Keys; the one chosen by the DBA to identify records is the Primary Key, and the rest become Alternate Keys.
A table cannot have two Primary Keys simultaneously. To switch from Y to (P, Q), first drop the existing key (ALTER TABLE X DROP PRIMARY KEY;) and then add the composite key (ALTER TABLE X ADD PRIMARY KEY (P, Q);). Note: A primary key column cannot be dropped individually if remaining PK columns contain duplicate values.
6.2 Solved Lab Exercise — Table: GYM
-- (a) Display the names of all the products in the store
SELECT PrName FROM GYM;
-- (b) Display the names and unit price of all the products
SELECT PrName, UnitPrice FROM GYM;
-- (c) Display names of products with unit price less than Rs. 20000.00
SELECT PrName FROM GYM WHERE UnitPrice < 20000;
-- (d) Display details of products with unit price in the range 20000 to 30000
SELECT * FROM GYM WHERE UnitPrice BETWEEN 20000 AND 30000;
-- (e) Display names of all products by manufacturer 'Fit Express'
SELECT PrName FROM GYM WHERE Manufacturer = 'Fit Express';
-- (f) Display all rows sorted in descending order of unit price
SELECT * FROM GYM ORDER BY UnitPrice DESC;
-- (g) Add a new row: 'P106', 'Vibro Exerciser', 23000, 'Avon Fitness'
INSERT INTO GYM VALUES ('P106', 'Vibro Exerciser', 23000, 'Avon Fitness');
-- (h) Apply a 10% discount reduction to UnitPrice of all products
UPDATE GYM SET UnitPrice = UnitPrice - (UnitPrice * 0.10);
-- (i) Display details of all products with manufacturer name starting with 'A'
SELECT * FROM GYM WHERE Manufacturer LIKE 'A%';
