0% found this document useful (0 votes)
23 views16 pages

Understanding DBMS and SQL Concepts

The document provides an overview of Database Management Systems (DBMS), focusing on relational data model concepts, integrity constraints, relational algebra, and SQL. It explains key terminologies, types of integrity constraints, and SQL commands, along with examples and best practices for database management. Additionally, it contrasts relational algebra with relational calculus and highlights the importance of SQL in managing relational databases.

Uploaded by

sweetak.0012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views16 pages

Understanding DBMS and SQL Concepts

The document provides an overview of Database Management Systems (DBMS), focusing on relational data model concepts, integrity constraints, relational algebra, and SQL. It explains key terminologies, types of integrity constraints, and SQL commands, along with examples and best practices for database management. Additionally, it contrasts relational algebra with relational calculus and highlights the importance of SQL in managing relational databases.

Uploaded by

sweetak.0012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Database Management System (DBMS)

Relational Data Model Concepts


The Relational Data Model organizes data into tables (relations) consisting of
rows (tuples) and columns (attributes).

1.1 Key Terminologies

Term Definition Example

Relation A table with rows and columns Student (RollNo, Name,


representing an entity. Age)

Tuple A single row in a relation (record). (101, "Alice", 20)

Attribute A column in a relation (field). RollNo, Name, Age

Domain The set of allowable values for an Age: Integers 1 to 100


attribute.

Degree Number of attributes in a relation. Student table has degree


=3

Cardinality Number of tuples in a relation. 100 students →


Cardinality = 100
2. Integrity Constraints
Integrity Constraints are rules applied to maintain data accuracy and consistency
in a database.

2.1 Types of Integrity Constraints

(a) Entity Integrity Constraint

 Ensures that primary keys cannot be NULL and must be unique.

 Example:

CREATE TABLE Student (

RollNo INT PRIMARY KEY, -- Cannot be NULL and must be unique

Name VARCHAR(50),

Age INT

);

(b) Referential Integrity Constraint

 Ensures that a foreign key matches a primary key in another table (or
is NULL).

 Example:

CREATE TABLE Orders (

OrderID INT PRIMARY KEY,

ProductID INT,

FOREIGN KEY (ProductID) REFERENCES Products(ProductID)

);
o If ProductID in Orders refers to Products(ProductID), it must exist
in Products.

(c) Key Constraints


 Primary Key (PK): Uniquely identifies a tuple (NOT NULL + UNIQUE).

 Candidate Key: A set of attributes that could be a PK


(e.g., RollNo or AadharNo in Student).

 Super Key: A superset of candidate keys (e.g., {RollNo, Name}).

 Foreign Key (FK): Links two tables (must reference a PK in another table).

(d) Domain Constraints

 Restricts attribute values to a defined domain (data type, range, format).

 Example:

CREATE TABLE Employee (

EmpID INT PRIMARY KEY,

Age INT CHECK (Age >= 18 AND Age <= 60), -- Domain constraint

Email VARCHAR(50) UNIQUE -- Key constraint

);

3. Examples of Integrity Constraints in SQL

3.1 Entity Integrity Example

CREATE TABLE Employee (

EmpID INT PRIMARY KEY, -- PK cannot be NULL

Name VARCHAR(50) NOT NULL, -- Name cannot be NULL

Salary DECIMAL(10,2)

);
3.2 Referential Integrity Example

CREATE TABLE Department (

DeptID INT PRIMARY KEY,

DeptName VARCHAR(50)

);

CREATE TABLE Employee (

EmpID INT PRIMARY KEY,

Name VARCHAR(50),

DeptID INT,

FOREIGN KEY (DeptID) REFERENCES Department(DeptID) -- Ensures valid


DeptID

);

3.3 Domain Constraint Example

CREATE TABLE Student (

RollNo INT PRIMARY KEY,

Name VARCHAR(50) NOT NULL,

Age INT CHECK (Age >= 16 AND Age <= 25), -- Age must be between 16-25

Gender CHAR(1) CHECK (Gender IN ('M', 'F', 'O')) -- Only M, F, or O allowed

);
4. Why Are Integrity Constraints Important?

1. Prevent Data Inconsistency:

o Ensures no duplicate or invalid entries.

2. Maintain Relationships:

o Foreign keys ensure valid references between tables.

3. Enforce Business Rules:

o E.g., "Age must be ≥ 18" or "Email must be unique."

5. Summary Table

Constraint Purpose SQL Example


Type

Entity Integrity Ensures PK is unique PRIMARY KEY (RollNo)


and not NULL.

Referential Ensures FK matches a FOREIGN KEY (DeptID) REFERENCES


Integrity PK in another table. Department(DeptID)

Key Defines PK, FK, UNIQUE (Email)


Constraints Candidate Keys, Super
Keys.

Domain Restricts attribute CHECK (Age >= 18)


Constraints values (type, range).
Relational Algebra
Relational Algebra is a procedural query language that operates on relations
(tables) and returns relations as results. It consists of a set of operations to
retrieve and manipulate data.

1.1 Basic Operations


Operation Symbol Description Example

Selection (σ) σ Selects rows based on a σ_(Age > 18)(Student) →


condition. Students older than 18.

Projection π Selects columns π_(Name, Age)(Student) →


(π) (attributes) from a Only Name and Age
relation. columns.

Union (∪) ∪ Combines rows from two Student ∪ Teacher → All


relations (must be union- students and teachers.
compatible).

Set – Returns rows in the first Student – Teacher →


Difference (– relation but not in the Students who are not
) second. teachers.

Cartesian × Combines each row of Student × Course → All


Product (×) the first relation with possible student-course
every row of the second. combinations.

Rename (ρ) ρ Renames a relation or ρ_(S1, Student) →


attribute. Renames "Student" to
"S1".
1.2 Derived Operations
Operation Symbol Description Example

Join (⋈) ⋈ Combines related tuples Student ⋈_([Link] =


from two relations. [Link]) Enroll →
Natural join.

Intersection ∩ Returns common rows in Student ∩ Employee →


(∩) two relations. Students who are also
employees.

Division (÷) ÷ Finds tuples in one Student ÷ Course →


relation that match all Students enrolled in all
tuples in another. courses.

1.3 Example Queries


1. Find students with Age > 20:

σ_(Age > 20)(Student)

2. Get names of students enrolled in "DBMS":

π_Name(σ_(Course="DBMS")(Student ⋈ Enroll))

2. Relational Calculus
Relational Calculus is a non-procedural (declarative) query language that
specifies what to retrieve without specifying how. It has two variants:

1. Tuple Relational Calculus (TRC)

2. Domain Relational Calculus (DRC)

2.1 Tuple Relational Calculus (TRC)

 Queries are expressed using tuple variables that range over rows.
 Notation:

{ t | Condition(t) }

 Example:

{ t | t ∈ Student ∧ [Link] > 20 } → Students older than 20.

2.2 Domain Relational Calculus (DRC)

 Queries are expressed using domain variables (attribute values).

 Notation:

{ <A1, A2, ...> | Condition(A1, A2, ...) }

 Example:

{ <Name, Age> | ∃RollNo ( <RollNo, Name, Age> ∈ Student ∧ Age > 20 ) }

→ Names and ages of students older than 20.

2.3 Comparison: TRC vs DRC

Feature Tuple Domain


Relational Relational
Calculus Calculus (DRC)
(TRC)

Variables Tuple Domain variables


variables (RollNo, Name).
(t, s).

Notation `{ t Condition(t) }` `{ <A1, Condition(A1, A2) }`


A2>

Example `{ t t ∈ Student ∧ `{ <Name> ∃RollNo


[Link] > 20 }` (Student(RollNo,
Name, Age) ∧ Age >
20) }`
3. Key Differences: Relational Algebra vs Calculus
Aspect Relational Algebra Relational Calculus

Type Procedural (specifies how to Non-procedural (specifies what to


retrieve). retrieve).

Operations Uses operators (σ, π, ⋈, etc.). Uses logical conditions


(∧, ∨, ∃, ∀).

Variables No variables. Uses tuple/domain variables.

Use Case Query execution steps. High-level query specification.

4. Summary
Concept Key Idea

Relational Algebra Procedural operations (σ, π, ⋈) to


manipulate relations.

Tuple Calculus Declarative queries using tuple variables t ∈ R ∧


(TRC) (`{ t Condition }`).

Domain Calculus Declarative queries using domain Condition }`).


(DRC) variables (`{ <A1, A2>

Join (⋈) Combines related tuples from two


relations.
1. Introduction to SQL
SQL (Structured Query Language) is a standard language for managing and
manipulating relational databases.

Characteristics of SQL

 High-level language: Easy to understand and use

 Non-procedural: Specifies "what" not "how"

 Portable: Works across different DBMS

 Interactive: Can be used directly or embedded in programs

 Comprehensive: Handles data definition, manipulation, and control

Advantages of SQL

 Standardized language

 Powerful query capabilities

 Reduced training costs

 Application portability

 Multiple data views


2. Types of SQL Commands
Category Full Form Purpose Key Commands

DDL Data Definition Define database CREATE, ALTER, DROP,


Language structure TRUNCATE, RENAME

DML Data Manipulation Manipulate data SELECT, INSERT, UPDATE,


Language DELETE

DCL Data Control Control access GRANT, REVOKE


Language

TCL Transaction Control Manage COMMIT, ROLLBACK,


Language transactions SAVEPOINT

3. SQL Data Types and Literals


Common SQL Data Types

 Numeric: INT, SMALLINT, FLOAT, DECIMAL

 Character: CHAR(n), VARCHAR(n), TEXT

 Date/Time: DATE, TIME, TIMESTAMP

 Binary: BLOB, RAW

 Boolean: TRUE/FALSE

Literals in SQL

 String: 'John Doe'

 Numeric: 25, 3.14

 Date: DATE '2023-12-31'

 Time: TIME '[Link]'

 Boolean: TRUE, FALSE, UNKNOWN


4. SQL Operators
Arithmetic Operators

+, -, *, /, % (modulus)

Comparison Operators

=, <>, >, <, >=, <=, BETWEEN, LIKE, IN

Logical Operators

AND, OR, NOT

Set Operators

UNION, INTERSECT, EXCEPT/MINUS

Operator Precedence
1. Parentheses

2. Arithmetic operators

3. Comparison operators

4. NOT

5. AND

6. OR
5. Database Objects
Tables

CREATE TABLE Students (

student_id INT PRIMARY KEY,

name VARCHAR(50) NOT NULL,

age INT CHECK (age >= 18),

dept_id INT FOREIGN KEY REFERENCES Departments(dept_id)

);

Views

CREATE VIEW CS_Students AS

SELECT * FROM Students

WHERE dept_id = 'CS';

Indexes

CREATE INDEX idx_name ON Students(name);

6. Advanced SQL Concepts


Queries and Subqueries

SELECT name FROM Students

WHERE dept_id IN (

SELECT dept_id FROM Departments

WHERE dept_name = 'Computer Science'

);
Aggregate Functions
 COUNT(), SUM(), AVG(), MIN(), MAX()

SELECT AVG(age) FROM Students;

Joins

 INNER JOIN: Matching rows

 LEFT JOIN: All left + matching right

 RIGHT JOIN: All right + matching left

 FULL JOIN: All rows from both

 CROSS JOIN: Cartesian product

SELECT [Link], d.dept_name

FROM Students s

INNER JOIN Departments d ON s.dept_id = d.dept_id;

Set Operations

-- UNION

SELECT name FROM Students

UNION

SELECT name FROM Teachers;

-- INTERSECT

SELECT name FROM Students

INTERSECT

SELECT name FROM Teachers;


-- MINUS/EXCEPT

SELECT name FROM Students

EXCEPT

SELECT name FROM Teachers;

7. Programmatic SQL
Cursors

DECLARE student_cursor CURSOR FOR

SELECT name FROM Students;

OPEN student_cursor;

FETCH NEXT FROM student_cursor;

-- Process data

CLOSE student_cursor;

DEALLOCATE student_cursor;

Triggers

CREATE TRIGGER update_student_count

AFTER INSERT ON Students

FOR EACH ROW

BEGIN

UPDATE Department_Stats

SET student_count = student_count + 1


WHERE dept_id = NEW.dept_id;

END;

8. Transaction Control

BEGIN TRANSACTION;

UPDATE Accounts SET balance = balance - 100 WHERE id = 1;

UPDATE Accounts SET balance = balance + 100 WHERE id = 2;

-- If everything is OK

COMMIT;

-- If error occurs

ROLLBACK;

9. Data Control Commands

-- Grant permissions

GRANT SELECT, INSERT ON Students TO user1;

-- Revoke permissions

REVOKE DELETE ON Students FROM user1;

10. Best Practices

 Use meaningful table and column names

 Normalize database structure

 Create appropriate indexes

 Use transactions for data integrity

 Validate data before insertion

 Regularly backup databases.

You might also like