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

Database Management System Overview

This document provides a comprehensive overview of Database Management Systems (DBMS), including definitions of data, information, and databases. It covers the functions of DBMS, advantages over traditional file systems, data models, relational database concepts, SQL commands, and operations. Key topics include data integrity, security, SQL constraints, and detailed syntax for various SQL operations.
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

Database Management System Overview

This document provides a comprehensive overview of Database Management Systems (DBMS), including definitions of data, information, and databases. It covers the functions of DBMS, advantages over traditional file systems, data models, relational database concepts, SQL commands, and operations. Key topics include data integrity, security, SQL constraints, and detailed syntax for various SQL operations.
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

NOTES BY :- VISHWAROOP SHARMA


PGT (COMPUTER SCIENCE)
Basic Introduction to Databases –
What is Data?
Raw facts, figures, or symbols known as Data such as “Aman”, 56, 98.5 etc.
What is Information?
When data is processed to get meaningful data, it is called information.
i.e. “Aman scored 98.5 marks.”
What is a Database?
A shared collection of related data stored in an organized manner, so that it can be easily
accessed, managed and updated. Examples of database are -
• School database (students, marks, teachers)
• Banking system
• Ticket reservation system

Database Management System (DBMS)


A DBMS is software that helps create, maintain, and operate a database efficiently and securely.
Examples of DBMS softwares are –
MySQL, Oracle, PostgreSQL, SQL Server

Main functions of a DBMS software -


1. Data Storage
2. Data Retrieval
3. Data Manipulation
4. Data Security
5. Backup and Recovery
6. Concurrency Control (when same updation is done at same time).

Advantages/Need of DBMS
Advantage Explanation
Reduced Data No duplicate storage and redundant data (unused and duplicate) is
Redundancy removed.
Data Consistency Same data everywhere across all places (tables).

Page | 1
Advantage Explanation
Data Security Access control & authorization.
Data Integrity Correctness & accuracy of data when data is stored.
Shareability Multiple users can access data as per their authentication level.
Backup & Recovery Automatic backup and restoration of data.

DBMS vs File System


DBMS File System
Centralized control Individual files managed separately
Secure Less secure
Consistent data High data Inconsistency
Faster querying for data
Slow searches
insert, search and updation
Concurrency support Very limited

Data Models

1. Hierarchical Model
Data stored in tree structure like parent-child relationships.
2. Network Model
Many-to-many relationships allowed between the nodes where data is stored.
3. Relational Model (used in CBSE)
Data stored in tables (relations) and these tables can be interconnected using Primary
Key/Foreign Key.

Page | 2
RDBMS (Relational DBMS)
Definition
A DBMS based on E.F. Codd’s relational model, storing data in tables (relations). In
RDBMS the data is stored in tables and these tables are called as relations.
Examples of RDBMS softwares are
MySQL, PostgreSQL, Oracle DB, SQL Server etc.

Relational Data Model and its terminologies


1. Relation – In relational model the data is stored in tables consisting of rows and columns
and these tables are called as Relation.
2. Tuple /Row/Record - A row/record in a table.
3. Attribute/Field/Column - A column in a table.
4. Domain - Set of valid values an attribute can take.
5. Degree - Total number of attributes in a table.
6. Cardinality - Total number of rows (tuples).

Keys in RDBMS –
1. Primary Key – The column/set of columns that is used to uniquely identify every record(row) is
known as primary key. The attribute with declared as primary key can not be null and
value can be repeated. i.e. EmployeeID, Student_ID etc.
2. Candidate Key – All the attributes(columns) which can be made as primary key i.e. the value in
these columns can not be NULL or duplicate are known as candidate key.

Page | 3
3. Alternate Key – Out of all candidate key one attribute is declared as primary key. Remaining
columns from these candidte key are known as alternate key.
4. Foreign Key - Attribute in one table that refers to primary key in another table is known as
foreign key. Foreign key is used to maintain referential integrity
5. Composite Key – If any singal column from any table can not be declared as primary key then
the combination of multiple attributes is used to uniquely identify the data from tables
and this combination of multiple attributes is known as composite key.

SQL Constraints
Constraint Description
PRIMARY KEY Unique + Not Null
FOREIGN KEY References another table
UNIQUE No duplicates
NOT NULL Column must have a value
DEFAULT Auto-value in a column
CHECK Restricts values for entering

Operations in RDBMS
1. Select (σ) – row filtering
2. Project (π) – column selection
3. Union (∪) – Addition of data of multiple table
4. Intersection (∩) – common data between two relations
5. Difference (–) – Data from one table which is not in second table
6. Join (⨝) – Connection between multi tables

Page | 4
SQL (Structured Query Language)
SQL is divided mainly into 5 parts :
1. DDL 2. DML 3. DQL 4. DCL 5. TCL
1. DDL – Data Definition Language
DDL is used to define database or droping database. DDL is also used to create structure of
tables in a database, Alter (Change) the structure of the tables and Drop the tables.
Command Purpose
CREATE Used to Create Database/Table
ALTER Used to change the structure of the table
DROP Used to delete the Database/Table
TRUNCATE Used to delete all rows and remove the space occupied by these data in the rows.
2. DML – Data Manipulation Language
DML is used to insert the data in the table, updation of the data and deletion of the data
from the tables.
Command Purpose
INSERT Add data in new tuple(Row)
UPDATE Update the existing data of the table.
DELETE Remove the tuple (Row) from the table.
3. DQL – Data Query Language
DQL is used to search the data in the tables.
Command Purpose
SELECT To retrieve data from the tables.
4. DCL – Data Control Language
DCL is used to grant/revoke the data permission to the users
Command Purpose
GRANT Give permissions
REVOKE Remove permissions
5. TCL – Transaction Control Language
TCL is used to control the transactions in the database.
Command Purpose
Commit Save the transaction after successful completion of the transaction.
Savepoint Used to create savepoints during the transaction.
Rollback Used to roll back/revert the transaction in the database.

Page | 5
SQL – Detailed Syntax

1. DDL (Data Defination Language)


CREATE, ALTER, DROP, TRUNCATE

DDL For Database


1. To CREATE Database -
CREATE <db_name>
i.e. CREATE school
2. To DROP Database -
DROP DATABASE <db_name>
i.e. DROP school
3. To SHOW all Database list -
SHOW DATABASES
(it show the list of all databases)
4. To USE any existing Database -
USE <db_name>
i.e. USE school
DDL for Table
1. To CREATE new table -
CREATE TABLE <table_name>
(
Column1_name Datatype(/Size) constraint,
Column2_name Datatype(/Size) constraint,
Column3_name Datatype(/Size),
Column4_name Datatype(/Size)
)
i.e. CREATE TABLE student
(
Stud_ID Int PRIMARY KEY,
Roll_No Int UNIQUE,
Stud_Name VARCHAR(20),
DOB DATE,
FEES FLOAT
ADDRESS VARCHAR(50) DEFAULT=”DELHI”
)

Page | 6
2. To DESCRIBE the table structure -
DESC <table_name> or DESCRIBE <table_name>
(This command will display the complete structure of the table)

3. To ALTER (Change) the structure of the table -


a. ADD new Column
b. DROP existing Column
c. CHANGE the Column name/size
d. MODIFY the datatype of the column
e. ADD constriant in a column

a. To ADD new column -


ALTER TABLE <table_name>
ADD <column_name> Datatype(/Size)
i.e. ALTER TABLE student
ADD Pan_no CHAR(10)
b. DROP existing Column -
ALTER TABLE <table_name>
DROP <column_name>
i.e. ALTER TABLE student
DROP Pan_no
c. CHANGE the column name -
ALTER TABLE <table_name>
CHANGE <old column name> <new column name> datatype(/Size)
i.e. ALTER TABLE student
CHANGE Roll_No Roll_Number int(2)
d. MODIFY the datatype of the column -
ALTER TABLE <table_name>
MODIFY <column_name> datatype(/Size)
i.e. ALTER TABLE student
MODIFY Stud_Name VARCHAR(30)
e. ADD constriant in a column -
ALTER TABLE <table_name>
ADD constraint(<column_name>
i.e. ALTER TABLE student
ADD NOT NULL(Stud_Name)

Page | 7
4. TRUNCATE the table -
- This command removes all the rows from the tables and leave only the blank table with
no data. TRUNCATE also removes the space occupied by the data earlier.
TRUNCATE <table_name>

2. DDL (Data Defination Language)


INSERT, UPDATE, DELETE

1. INSERT data in table -


INSERT INTO <table_name>
VALUES (<value1>,<value2>,<value3>)
(Note : - Here values must be same as No of columns and also as per the data type of the
columns)
INSERT INTO <table_name> (<column1_name>,< column2_name >,< column3_name >)
VALUES (<value1>,<value2>,<value3>)
i.e. INSERT INTO student (Stud_ID,Roll_No,Name)
VALUES (101, 01, ‘Rahul’)

2. UPDATE existing data in the table -


UPDATE TABLE <table_name>
SET column_name=value
WHERE <condition>
i.e. UPDATE student
SET Name=’Rohit’
WHERE Stud_ID=101

3. DELETE existing data from table -


DELETE FROM <table_name>
WHERE <condition>
i.e. DELETE FROM student
WHERE Stud_ID=101

Difference between DELETE & TRUNCATE :-


DELETE – DELETE command deletes the selected/entire rows data from the tables but does not free
up space from the memory.
TRUNCATE – TRUNCATE command delete entire rows data from the tables and free up the space
from memory that can be used for another purpose.
Page | 8
3. DQL (Data Query Language)
SELECT
a. Select all (Rows & Column) the data from the table
b. Select specific column from the table
c. Selecting specific tuple (WHERE clause)
i. Relational operator (=, <, >, <=, >=, !=)
ii. Mathematical operator (+, -, *, /, %)
iii. Logical operator (AND, OR, NOT)
d. ALIASING ( Using AS )
e. DISTINCT clause
f. IN clause
g. BETWEEN clause
h. ORDER BY clause
i. IS NULL/ IS NOT NULL
j. LIKE clause using Wildcards ( % (percent) & _ (underscore))
k. Aggregate functions (min, max, avg, sum, count)
l. GROUP BY clause
m. HAVING clause
a. Select all (Rows & Column) the data from the table -
SELECT * FROM <table_name>
- Displays complete data from the table
b. Select specific column from the table -
SELECT <column1_name><column2_name>
- Displays data of all rows for specified column
c. Selecting specific tuple (WHERE clause) -
i. Relational operator (=, <, >, <=, >=, !=)
SELECT * FROM <table_name>
WHERE column_name = value
i.e. SELECT * FROM student
WHERE Roll_No = 5
- Displays the data of the student whose roll no is 5.
ii. Mathematical operator (+, -, *, /, %)
SELECT column+value FROM <table_name>
WHERE condition
i.e. SELECT marks+10 FROM student
WHERE name=’Rohit’

Page | 9
iii. Logical operator (AND, OR, NOT)
a. AND
SELECT * FROM <table_name>
WHERE ( condition_1 AND condition_2)
- Display data in which both conditions satisfies
i.e. SELECT * FROM student
WHERE ( Subject = ‘Hindi’ AND Marks > 50)
- It displays the data of the students whose subject is hindi and marks greater than 50
b. OR
SELECT * FROM <table_name>
WHERE ( condition_1 OR condition_2)
- Display data in which either of the condition is satisfied
i.e. SELECT * FROM student
WHERE ( Subject = ‘Hindi’ OR Marks > 50)
- It displays the data of the students of whose either the subject is hindi or marks
greater than 50
c. NOT
SELECT * FROM <table_name>
WHERE NOT ( condition_1)
- Display data in which condition is not satisfied
i.e. SELECT * FROM student
WHERE NOT ( Subject = ‘Hindi’)
- It displays the data of the students whose subject is not hindi .

d. ALIASING ( Using AS )
- It is used to rename the Column name & Table name for displaying in the output
Note : it only displays the name in output but does not rename the column/table
name in database.
SELECT <column_name> AS <name_to_display>
FROM <table_name> AS <name_to_display>
i.e. SELECT Name AS ‘Student Name’
FROM student AS ‘Student Detail’

e. DISTINCT clause
- Used to display similar data only once
SELECT DISTINCT <column_name> From <table_name>
i.e. SELECT DISTINCT subject FROM student
Page | 10
f. IN clause
- Used to get the data which is similer to the list within IN clause
SELECT * FROM <table_name>
WHERE <column_name> IN (‘value1’, ‘value2’, ‘value3)
i.e. SELECT * FROM student
WHERE subject in (‘Hindi’, ‘English’, ‘Maths’)
- This command is used to display the details of the student whose subject is in
Hindi, English or Maths

g. BETWEEN clause
- Used to get data which have values between the range defined. Both the values
are inclusive
SELECT * FROM <table_name>
WHERE <column_name> BETWEEN <start of range> AND <end of range>
i.e. SELECT * FROM student
WHERE Roll_No BETWEEN 10 AND 20
- Here the details of the students whose Roll no is between 10 & 20 are displayed.
Also both student who have Roll No 10 & 20 will also be displayed.

h. ORDER BY clause
- It is used to sort the data on the basis of the column selected as according to
Number/Alphbatically in either ascending or descending type.
- Default type is ascending.
i. To display in ascending order -
SELECT * FROM <table_name>
WHERE <condition> ORDER BY <column_name>
ii. To display in descending order -
SELECT * FROM <table_name>
WHERE <condition> ORDER BY <column_name> DESC
i.e. SELECT * FROM Student
WHERE Roll_No<= 25 ORDER BY Name
- This will display the list of the students whose Roll No is less than or equals to 25
in the ascending form as per Name

Page | 11
i. IS NULL/ IS NOT NULL
- It is used get the values which are NULL/NOT NULL
Select * FROM <table_name>
WHERE <column_name> IS NULL
i.e. SELECT * FROM <table_name>
WHERE Subject IS NULL
- This will display the details of the students who don’t have any subject in the
table.

j. LIKE clause using Wildcards ( % (percent) & _ (underscore))


- LIKE clause is also know as Pattern Matching Clause.
- It have two characters known as wildcards for pattern matching.
- Percent (%) is used to match string sequence.
- Underscore ( _ ) is used to match one character.
SELECT * FROM <table_name>
WHERE <column_name> LIKE “Wildcard Pattern”
i.e. SELECT * FROM Student
WHERE Name LIKE ‘%T_’
Examples -
‘R%’ Name starting with R
‘%R’ Name ending with R
‘%R% Name having R anywhere in it
‘_ R% ‘ Name having R as Second Character
‘ R _ S %’ Name having R as first and S as third Character
‘R _ S’ Name having R as first and S as third character and only of 3
character
‘% R_S_’ Name having S as second last and R as 4th last character

k. Aggregate functions (min, max, avg, sum, count)


- Used to values after using formula
- Count function doesn’t count NULL values
- Avg function find average after ignoring NULL values
SELECT AggFunct(<column_name)
FROM <table_name>
i.e. SELECT MAX(Marks), MIN(Marks) FROM Student
- Gives maximum and minimum marks

Page | 12
l. GROUP BY clause
- The SQL GROUP BY clause groups rows that have the same values in specified
columns into summary rows. It is primarily used with aggregate functions like
COUNT(), SUM(), AVG(), MAX(), and MIN() to perform calculations on each group
and return a single result per group.
- Grouping can be done as Grouping and Subgrouping also.
SELECT AggFunction(<column_name) FROM <table_name>
GROUP BY <column_name>
i.e. SELECT MAX(Marks) FROM Student
GROUP BY Subject
- This function gives subject wise maximum marks.

m. HAVING clause
- The SQL HAVING clause is used to filter groups of data based on conditions
involving aggregate functions, such as COUNT(), SUM(), AVG(), MIN(), and MAX().
It is applied after the GROUP BY clause, in contrast to the WHERE clause, which
filters individual rows before grouping and cannot include aggregate functions.
SELECT <column1_name>, aggregate_function(<column2_name>) FROM table_name
WHERE condition (optional, for individual rows)
GROUP BY <column_name>
HAVING AggFunction(for grouped rows)
i.e. SELECT COUNT(Name), Subject
FROM Student
GROUP BY Subject
HAVING COUNT(Name)>1

Page | 13
Joins in SQL
1. Cartesian product on two tables
2. Equi join
3. Natural Join

1. Cartesian Product –
A Cartesian product, also known as a CROSS JOIN, combines every row from the
first table with every row from the second table. This results in a new table containing all
possible combinations of rows from the two original tables. If Table A has m rows and
Table B has n rows, the Cartesian product will have m * n rows.

SELECT * FROM TableA


CROSS JOIN TableB;

2. Equi Join –
An Equi Join is a type of INNER JOIN that combines rows from two or more tables
based on an equality condition (=) between specified columns in those tables. It returns
only the rows where the values in the specified columns are equal. If the common
column names are the same in both tables and you select all columns (*), the common
column will appear twice in the result.

SELECT * FROM TableA


INNER JOIN TableB
ON TableA.column_name = TableB.column_name;
3. Natural Join –
A Natural Join automatically joins two tables based on all columns that have the
same name and compatible data types in both tables. It implicitly uses an equality
condition on these common columns. Unlike an Equi Join, a Natural Join eliminates
duplicate columns, meaning the common columns appear only once in the result set.
SELECT *
FROM TableA
NATURAL JOIN TableB;

Page | 14
4. DCL (Data Control Language)
GRANT, REVOKE

DCL, or Data Control Language, in SQL is used to manage user permissions and access rights
to a database. It consists of two main commands: GRANT, which gives users specific privileges to
database objects, and REVOKE, which withdraws those privileges. DCL is crucial for database
security, as it determines who can perform what actions on which data.
Key DCL commands
• GRANT: Assigns new privileges to a user account, allowing them to perform specific actions
like SELECT, INSERT, UPDATE, or DELETE on certain tables or other database objects.
• REVOKE: Removes previously granted privileges from a user account, taking away their
access to perform certain actions on database objects.

5. TCL (Transaction Control Language)


COMMIT, SAVEPOINT, ROLLBACK

TCL in SQL stands for Transaction Control Language, which is a set of commands used to
manage transactions, ensuring data integrity and consistency. It allows you to group a series of SQL
statements into a single, all-or-nothing unit of work. The main commands are COMMIT (to save
changes), ROLLBACK (to undo changes), and SAVEPOINT (to set a temporary point to roll back to).
Key TCL commands
• COMMIT: Makes all the changes made during the current transaction permanent and saves
them to the database.
• ROLLBACK: Undoes all the changes made since the beginning of the transaction or since the
last SAVEPOINT, reverting the database to its previous state.
• SAVEPOINT: Creates a temporary marker within a transaction to which you can later roll
back. This is useful for undoing only part of a large transaction.

Transactions & ACID Property of transaction


1. Atomicity – Either the transaction must be completed or nothing.
2. Consistency – The transaction must be in valid state.
3. Isolation – One transaction must not be influenced by another transaction
4. Durability – After the complete transaction execution, it should not go back.

Page | 15
Python & MySQL Connectivity (Basics)

Library to be imported for connection of python and mysql:


[Link]

Steps:
1. Connect to database
2. Create cursor
3. Execute queries
4. Commit changes
5. Close connection

Example of DQL:
Import [Link]
mydb = [Link](
host=”localhost”, user=”root”, password=”1234”, database=”school”
)
cur = [Link]( )
[Link](“SELECT * FROM Student;”)
myresult = [Link]()
for x in myresult:
print(x)

Example of DML:
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
[Link](sql, val)
[Link]()
print([Link], "record inserted.")

Page | 16

You might also like