Unit 2: Relational data Model and Language




Relational Data Model and Relational Language

Relational Data Model Concepts

The Relational Data Model represents data in the form of tables (relations). It was proposed by E. F. Codd.

Basic Terminology

TermMeaning
RelationTable
TupleRow
AttributeColumn
DegreeNumber of attributes
CardinalityNumber of tuples
DomainSet of valid values for an attribute

Structure of a Relation

A relation consists of:

  • Relation name
  • Attributes with domains
  • Tuples (records)

Example: STUDENT (RollNo, Name, Course, Marks)

Integrity Constraints

Integrity constraints are rules that ensure correctness and consistency of data in a database.

Types of Integrity Constraints

  1. Domain Constraints
  2. Key Constraints
  3. Entity Integrity
  4. Referential Integrity

Domain Constraints

  • Ensure that attribute values come from a valid domain
  • Prevents invalid data entry

Example: Marks must be between 0 and 100

Marks INT CHECK (Marks BETWEEN 0 AND 100)

Key Constraints

Key constraints ensure uniqueness of data.

Types of Keys

Key TypeDescription
Super KeyUniquely identifies tuples
Candidate KeyMinimal super key
Primary KeySelected candidate key
Alternate KeyCandidate key not selected
Foreign KeyReferences primary key of another relation

Entity Integrity Constraint

  • Ensures that primary key cannot be NULL
  • Every relation must have a primary key

Example: RollNo in STUDENT table cannot be NULL.

RollNo INT NOT NULL PRIMARY KEY

Referential Integrity Constraint

  • Ensures consistency between related tables

Foreign key must:

  • Match primary key in referenced table, or
  • Be NULL

Example

STUDENT (RollNo, Name, DeptID)
DEPARTMENT (DeptID, DeptName)

FOREIGN KEY (DeptID) REFERENCES DEPARTMENT(DeptID)

Actions on Referential Integrity

ActionMeaning
CASCADEChanges propagate
SET NULLForeign key set to NULL
RESTRICTPrevents change
NO ACTIONSimilar to RESTRICT

Relational Algebra

Relational Algebra is a procedural query language.

Characteristics

  • Uses operators
  • Specifies how to retrieve data
  • Foundation of SQL

Basic Relational Algebra Operators

OperatorSymbolDescription
SelectionσSelect rows
ProjectionπSelect columns
UnionCombine relations
Set DifferenceSubtract relations
Cartesian Product×Combine tuples

Additional Operators

OperatorSymbol
Join
Intersection
Division÷
Renameρ

Example

Find students from MCA course:

σ Course = 'MCA' (STUDENT)

Relational Calculus

Relational Calculus is a non-procedural query language.

Characteristics

  • Specifies what data is required
  • Does not specify retrieval method
  • Based on predicate logic

Types of Relational Calculus

  1. Tuple Relational Calculus (TRC)
  2. Domain Relational Calculus (DRC)

Tuple Relational Calculus (TRC)

  • Variables represent tuples
  • Queries written using tuple variables

General Form

{ t | P(t) }

Where:

  • t = tuple variable
  • P(t) = predicate condition

Example

Find names of students in MCA:

{ t.Name | STUDENT(t) ∧ t.Course = 'MCA' }

Domain Relational Calculus (DRC)

  • Variables represent domains (attribute values)
  • Closer to SQL

General Form

{ <x1, x2, ..., xn> | P(x1, x2, ..., xn) }

Example

Find RollNo and Name of MCA students:

{ <r, n> | ∃c, m (STUDENT(r, n, c, m) ∧ c = 'MCA') }

Difference Between Relational Algebra and Relational Calculus

BasisRelational AlgebraRelational Calculus
NatureProceduralNon-procedural
FocusHow to get dataWhat data to get
FoundationSQL executionSQL logic
ComplexityEasier to understandMore theoretical

Exam-Focused Summary (MCA)

  • Relational model stores data in tables
  • Integrity constraints maintain data correctness
  • Entity integrity ensures primary key not NULL
  • Referential integrity maintains table relationships
  • Relational algebra is procedural
  • Relational calculus is non-procedural
  • TRC uses tuples; DRC uses domains

Introduction to SQL (Structured Query Language)

SQL (Structured Query Language) is a standard database language used to create, access, manipulate, and control data in a relational database.

  • Developed by IBM
  • Standardized by ANSI and ISO
  • Used in DBMS like MySQL, Oracle, SQL Server, PostgreSQL

Characteristics of SQL

CharacteristicExplanation
Declarative LanguageSpecifies what data is needed, not how
Non-ProceduralNo need to define step-by-step process
User FriendlyEasy to learn and use
Standard LanguageSame syntax across most DBMS
Supports Multiple UsersAllows concurrent access
Integrated with Programming LanguagesWorks with Java, Python, C, etc.
SecureProvides access control
PortableWorks on different platforms

Advantages of SQL

AdvantageDescription
Easy Data AccessRetrieve data using simple commands
Reduced CodingFewer lines compared to traditional programming
High PerformanceEfficient query processing
Data SecurityGrant and revoke privileges
Data IntegrityEnforces constraints
ScalabilityHandles large databases
Transaction ControlSupports commit and rollback

SQL Data Types and Literals

SQL Data Types

SQL data types define type of data that can be stored in a column.

Numeric Data Types

Data TypeDescription
INT / INTEGERWhole numbers
SMALLINTSmall range integers
BIGINTLarge range integers
DECIMAL(p,s)Fixed-point numbers
FLOAT / REALFloating-point numbers

Character / String Data Types

Data TypeDescription
CHAR(n)Fixed-length string
VARCHAR(n)Variable-length string
TEXTLarge text data

Date & Time Data Types

Data TypeDescription
DATEStores date
TIMEStores time
DATETIMEDate and time
TIMESTAMPDate and time with timezone

Boolean Data Type

Data TypeDescription
BOOLEANTRUE or FALSE

SQL Literals

A literal is a fixed value used in SQL statements.

Types of Literals

Literal TypeExample
Numeric Literal100, 45.5
String Literal'MCA', 'Jay'
Date Literal'2025-01-01'
Boolean LiteralTRUE, FALSE
NULL LiteralNULL

Types of SQL Commands

SQL commands are classified based on their functionality.

DDL – Data Definition Language

Used to define and modify database structure.

CommandUse
CREATECreate tables/databases
ALTERModify structure
DROPDelete structure
TRUNCATERemove all records
RENAMERename object

DML – Data Manipulation Language

Used to insert, update, and delete data.

CommandUse
INSERTAdd new records
UPDATEModify existing data
DELETERemove records
SELECTRetrieve data

DCL – Data Control Language

Used to control user access.

CommandUse
GRANTProvide permissions
REVOKERemove permissions

TCL – Transaction Control Language

Used to manage transactions.

CommandUse
COMMITSave changes
ROLLBACKUndo changes
SAVEPOINTSet rollback point

SQL Operators and Their Procedure

SQL operators are used to perform operations on data.

Arithmetic Operators

OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
%Modulus

Example: SELECT Marks + 5 FROM Student;

Comparison Operators

OperatorMeaning
=Equal to
!= or <>Not equal
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal

Logical Operators

OperatorMeaning
ANDAll conditions true
ORAny condition true
NOTNegates condition

Set Operators

OperatorDescription
UNIONCombines result sets
UNION ALLIncludes duplicates
INTERSECTCommon records
EXCEPT / MINUSDifference

Special Operators

OperatorUse
BETWEENRange check
INMatch list
LIKEPattern matching
IS NULLNull check
EXISTSSubquery result

Example: SELECT * FROM Student WHERE Name LIKE 'A%';

Operator Precedence (Procedure)

SQL evaluates operators in the following order:

  1. Arithmetic
  2. Comparison
  3. Logical (NOT → AND → OR)

Exam-Focused Summary (MCA)

  • SQL is a standard relational database language
  • SQL is declarative and non-procedural
  • Data types define storage format
  • SQL commands are categorized into DDL, DML, DCL, TCL
  • Operators perform arithmetic, logical, and comparison operations

Introduction to SQL (Structured Query Language)

SQL (Structured Query Language) is a standard database language used to create, access, manipulate, and control data in a relational database.

  • Developed by IBM
  • Standardized by ANSI and ISO
  • Used in DBMS like MySQL, Oracle, SQL Server, PostgreSQL

Characteristics of SQL

CharacteristicExplanation
Declarative LanguageSpecifies what data is needed, not how
Non-ProceduralNo need to define step-by-step process
User FriendlyEasy to learn and use
Standard LanguageSame syntax across most DBMS
Supports Multiple UsersAllows concurrent access
Integrated with Programming LanguagesWorks with Java, Python, C, etc.
SecureProvides access control
PortableWorks on different platforms

Advantages of SQL

AdvantageDescription
Easy Data AccessRetrieve data using simple commands
Reduced CodingFewer lines compared to traditional programming
High PerformanceEfficient query processing
Data SecurityGrant and revoke privileges
Data IntegrityEnforces constraints
ScalabilityHandles large databases
Transaction ControlSupports commit and rollback

SQL Data Types and Literals

SQL Data Types

SQL data types define type of data that can be stored in a column.

Numeric Data Types

Data TypeDescription
INT / INTEGERWhole numbers
SMALLINTSmall range integers
BIGINTLarge range integers
DECIMAL(p,s)Fixed-point numbers
FLOAT / REALFloating-point numbers

Character / String Data Types

Data TypeDescription
CHAR(n)Fixed-length string
VARCHAR(n)Variable-length string
TEXTLarge text data

Date & Time Data Types

Data TypeDescription
DATEStores date
TIMEStores time
DATETIMEDate and time
TIMESTAMPDate and time with timezone

Boolean Data Type

Data TypeDescription
BOOLEANTRUE or FALSE

SQL Literals

A literal is a fixed value used in SQL statements.

Types of Literals

Literal TypeExample
Numeric Literal100, 45.5
String Literal'MCA', 'Jay'
Date Literal'2025-01-01'
Boolean LiteralTRUE, FALSE
NULL LiteralNULL

Types of SQL Commands

SQL commands are classified based on their functionality.

DDL – Data Definition Language

Used to define and modify database structure.

CommandUse
CREATECreate tables/databases
ALTERModify structure
DROPDelete structure
TRUNCATERemove all records
RENAMERename object

DML – Data Manipulation Language

Used to insert, update, and delete data.

CommandUse
INSERTAdd new records
UPDATEModify existing data
DELETERemove records
SELECTRetrieve data

DCL – Data Control Language

Used to control user access.

CommandUse
GRANTProvide permissions
REVOKERemove permissions

TCL – Transaction Control Language

Used to manage transactions.

CommandUse
COMMITSave changes
ROLLBACKUndo changes
SAVEPOINTSet rollback point

SQL Operators and Their Procedure

SQL operators are used to perform operations on data.

Arithmetic Operators

OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
%Modulus

Example: SELECT Marks + 5 FROM Student;

Comparison Operators

OperatorMeaning
=Equal to
!= or <>Not equal
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal

Logical Operators

OperatorMeaning
ANDAll conditions true
ORAny condition true
NOTNegates condition

Set Operators

OperatorDescription
UNIONCombines result sets
UNION ALLIncludes duplicates
INTERSECTCommon records
EXCEPT / MINUSDifference

Special Operators

OperatorUse
BETWEENRange check
INMatch list
LIKEPattern matching
IS NULLNull check
EXISTSSubquery result

Example: SELECT * FROM Student WHERE Name LIKE 'A%';

Operator Precedence (Procedure)

SQL evaluates operators in the following order:

  1. Arithmetic
  2. Comparison
  3. Logical (NOT → AND → OR)

Exam-Focused Summary (MCA)

  • SQL is a standard relational database language
  • SQL is declarative and non-procedural
  • Data types define storage format
  • SQL commands are categorized into DDL, DML, DCL, TCL
  • Operators perform arithmetic, logical, and comparison operations

Tables

A table is the basic storage structure in a relational database.

Characteristics

  • Data stored in rows (tuples) and columns (attributes)
  • Each table has a primary key
  • Data type defined for each column

Create Table Example

CREATE TABLE Student ( RollNo INT PRIMARY KEY, Name VARCHAR(50), Course VARCHAR(20), Marks INT );

Views

A view is a virtual table based on the result of a SQL query.

Characteristics

  • Does not store data physically
  • Improves security
  • Simplifies complex queries

Create View Example

CREATE VIEW MCA_Students AS SELECT RollNo, Name FROM Student WHERE Course = 'MCA';

Advantages of Views

  • Data abstraction
  • Restricted data access
  • Query reusability

Indexes

An index improves the speed of data retrieval.

Characteristics

  • Created on columns
  • Uses additional storage
  • Slows INSERT/UPDATE slightly

Create Index Example

CREATE INDEX idx_rollno ON Student(RollNo);

Types of Indexes

TypeDescription
Simple IndexSingle column
Composite IndexMultiple columns
Unique IndexNo duplicate values

Queries and Subqueries

Queries

A query retrieves data from database.

SELECT * FROM Student WHERE Marks > 70;

Subqueries

A subquery is a query inside another query.

Types

  1. Single-row subquery
  2. Multiple-row subquery
  3. Correlated subquery

Example

SELECT Name FROM Student WHERE Marks > (SELECT AVG(Marks) FROM Student);

Aggregate Functions

Aggregate functions perform calculations on a set of values.

Common Aggregate Functions

FunctionUse
COUNT()Number of rows
SUM()Total
AVG()Average
MAX()Maximum
MIN()Minimum

Example SELECT AVG(Marks) FROM Student;

GROUP BY Clause

Used with aggregate functions.

SELECT Course, AVG(Marks) FROM Student GROUP BY Course;

HAVING Clause

Used to apply condition on groups.

SELECT Course, AVG(Marks) FROM Student GROUP BY Course HAVING AVG(Marks) > 70;

Insert, Update and Delete Operations (DML)

INSERT

INSERT INTO Student VALUES (101, 'Ravi', 'MCA', 80);

UPDATE

UPDATE Student SET Marks = 85 WHERE RollNo = 101;

DELETE

DELETE FROM Student WHERE RollNo = 101;

Joins

Joins are used to combine data from multiple tables.

Types of Joins

Join TypeDescription
INNER JOINMatching records
LEFT JOINAll from left table
RIGHT JOINAll from right table
FULL JOINAll records
SELF JOINTable joins with itself

Example (INNER JOIN)

SELECT Student.Name, Department.DeptName FROM Student INNER JOIN Department ON Student.DeptID = Department.DeptID;

Set Operations

Set operations combine results of two queries.

Conditions

  • Same number of columns
  • Same data type
  • Same order

Types of Set Operations

OperationMeaning
UNIONCombines rows (removes duplicates)
UNION ALLKeeps duplicates
INTERSECTCommon rows
MINUSRows in first query only

Example

SELECT RollNo FROM Student_2024 UNION SELECT RollNo FROM Student_2025;

Cursors (PL-SQL)

A cursor is a pointer used to process query result row-by-row.

Types of Cursors

  1. Implicit Cursor
  2. Explicit Cursor

Cursor Steps

  1. Declare
  2. Open
  3. Fetch
  4. Close

Example (Explicit Cursor)

DECLARE CURSOR c1 IS SELECT Name FROM Student; v_name Student.Name%TYPE; BEGIN OPEN c1; FETCH c1 INTO v_name; CLOSE c1; END;

Triggers

A trigger is a PL-SQL block that executes automatically when an event occurs.

Trigger Events

  • INSERT
  • UPDATE
  • DELETE

Example

CREATE TRIGGER trg_before_insert BEFORE INSERT ON Student FOR EACH ROW BEGIN DBMS_OUTPUT.PUT_LINE('Record Inserted'); END;

Uses of Triggers

  • Enforce business rules
  • Audit data changes
  • Automatic logging

Procedures (PL-SQL)

A procedure is a stored PL-SQL block that performs a specific task.

Characteristics

  • Stored in database
  • Improves performance
  • Can accept parameters

Procedure Example

CREATE PROCEDURE Add_Student AS BEGIN INSERT INTO Student VALUES (102, 'Amit', 'MCA', 78); END;

Execute Procedure

EXEC Add_Student;

Difference: Procedure vs Trigger

BasisProcedureTrigger
ExecutionManually calledAutomatically executed
ParametersAllowedNot allowed
Event BasedNoYes

Exam-Focused Summary (MCA)

  • Tables store data physically
  • Views are virtual tables
  • Indexes improve performance
  • Subqueries are nested queries
  • Aggregate functions summarize data
  • Joins combine tables
  • Set operations combine result sets
  • Cursors handle row-by-row processing
  • Triggers execute automatically
  • Procedures store reusable logic