Unit-III DMBS
Unit-III DMBS
Database Management – 1
Information: information is data that has been given meaning by way of relational connection.
This "meaning" can be useful, but does not have to be. In computer parlance, a relational database
makes information from the data stored within it. Information embodies the understanding of some
sort. E.g. the temperature dropped to 15 degrees and then it started raining.
DATABASE: A database is a collection of data, typically describing the activities of one or more
related organizations. For example, a university database might contain information about the
following:
Entities such as students, faculty, courses, and classrooms.
Relationships between entities, such as students' enrollment in courses, faculty teaching
courses, and the use of rooms for courses.
Proper storage of data in a database will enhance efficient
Data Management
Data processing
Data retrieval
Database System: It refers to an organization of components that define and regulate the
collection, storage, management from general management point of view, the DB system is
composed of-
Hardware
Software
People – system administrators: database systems operations
o DB administrators: manage the DBMS and ensure the DB is functioning properly
o DB designers
o System analysts and programmers design and implement the application programs
o end user
Procedures
Data
DBMS: A database management system (DBMS) is a collection of programs that manages the
database structure and controls access to the data stored in the database. In a sense, a database
resembles a very well-organized electronic filing cabinet in which powerful software (the DBMS)
helps manage the cabinet’s contents.
ADVANTAGES OF A DBMS
Data independence: This is the technique that allow data to be changed without affecting the
applications that process it.
Efficient data access: A DBMS deploys sophisticated techniques to store and retrieve data
efficiently.
Data integrity control: The DBMS can enforce integrity constraints on the data. For example,
before inserting salary information for an employee, the DBMS can check that the department
budget is not exceeded.
Security Control: The DBMS can enforce access controls that govern what data is visible to
different classes of users. Users are only allowed to perform an operation he or she is allowed to
carry out on data.
Concurrent access and crash recovery: A DBMS schedules concurrent accesses to the data in
such a manner that users can think of the data as being accessed by only one user at a time. Further,
the DBMS protects users from the effects of system failures.
Reduced application development time: Clearly, the DBMS supports many important functions
that are common to many applications accessing data stored in the DBMS. This, in conjunction
with the high-level interface to the data, facilitates quick development of applications. Such
applications are also likely to be more robust than applications developed from scratch because
many important tasks are handled by the DBMS instead of being implemented by the application.
DBMS APPLICATIONS
Banking: all transactions
Airlines: reservations, schedules Universities: registration, grades
Sales: customers, products, purchases Online retailers: order tracking, customized
recommendations
Manufacturing: production, inventory, orders, supply chain
Human Resources: employee records, salaries, tax deductions
RELATIONAL DATABASE
• The Relational Database is a collection of related relations/tables to represent both data and the
relationships among those data.
• Each table has multiple columns and rows.
• Each column has a unique name.
• Table is called as a Relation
• Column is called as an Attribute or Domain
• Row is called as a Tuple or Record
DBMS Vs RDBMS
DBMS RDBMS
It stores data as a file It stores data in the form of tables.
It supports single users It supports multiple users.
It does not support client-server architecture It supports client-server architecture.
It has low software and hardware requirements It has higher hardware and software
requirements.
In DBMS, data redundancy is common In RDBMS, keys and indexes do not allow
data redundancy.
DEGREE OF A TABLE
The number of columns/fields is called as ‘degree’ of a Table.
This is also called as ‘arity’.
CARDINALITY OF A TABLE
The cardinality of a Table instance is the number of tuples/rows in it.
Example:
Degree of the relation is 5
Cardinality of the relation is 4.
KEYS IN A TABLE
A DBMS key is a Column or set of Columns which helps you to identify a row(tuple) in
a relation(table).
They also allow you to find the relation between two tables.
Keys help you uniquely identify a row in a table by a combination of one or more
columns in that table.
CANDIDATE KEY
A set of fields that uniquely identifies a tuple according to a key constraint is called as a
‘Candidate Key’ for the relation.
This is also called as a ‘key’
A relation may have more than key.
Every relation must have a key.
PRIMARY KEY
A column or group of columns in a table which helps us to uniquely identify every row in
that table is called a primary key.
Rules for defining Primary key
o Unique Values: Two rows can't have the same Primary key field
o Not NULL: The primary key field cannot be NULL.
FOREIGN KEY
A foreign key is a column which is added to create a relationship with another table.
Foreign keys help us to maintain data integrity and also allows navigation between two
different instances of an entity.
DBMS LANGUAGES
The workings of a DBMS is controlled by four different languages, they are:
Data Definition Language (DDL): Used by the DBA and database designers to specify
the conceptual schema of a database. In many DBMSs, the DDL is also used to define
internal and external schemas (views). In some DBMSs, separate storage definition
language (SDL) and view definition language (VDL) are used to define internal and
external schemas. SDL is typically realized via DBMS commands provided to the DBA
and database designers. Some examples include:
o CREATE - to create objects in the database
o ALTER - alters the structure of the database
o DROP - delete objects from the database
o TRUNCATE - remove all records from a table, including all spaces allocated for
the records are removed
o COMMENT - add comments to the data dictionary
o RENAME - rename an object
Data Manipulation Language (DML): These statements manage data within schema
objects. They specify database retrievals and updates. DML commands can be embedded
in a general-purpose programming language (host language), such as COBOL, C, C++, or
Java.
o A library of functions can also be provided to access the DBMS from a
programming language
o Alternatively, stand-alone DML commands can be applied directly (called a query
language). Some examples in SQL include:
SELECT - Retrieve data from the a database
INSERT - Insert data into a table
UPDATE - Updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)
CALL - Call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency
Data Control Language (DCL): used for granting and revoking user access on a database
o To grant access to user – GRANT
o To revoke access from user – REVOKE
Transaction Control (TCL): Statements are used to manage the changes made by DML
statements. It allows statements to be grouped together into logical transactions. Some
examples include:
o COMMIT - save work done
o SAVEPOINT - identify a point in a transaction to which you can later roll back
o ROLLBACK - restore database to original since the last COMMIT
o SET TRANSACTION - Change transaction options like isolation level and what
rollback segment to use in practical data definition language, data manipulation
language and data control languages are not separate language; rather they are the
parts of a single database language such as SQL.
SQL QUERY:
1. Create: It is a DDL SQL command used to create a table or a database in relational
database management system.
To create a database named “test_db” -
CREATE DATABASE test_db;
3. INSERT: It is a DML command used to insert rows/ records into a table. One INSERT
Query can insert only one row in a table.
E.g.:
INSERT INTO Student VALUES(101, 'Adam', 15);
The HAVING Clause HAVING clause was added to SQL, because the WHERE keyword
could not be used with aggregate function.
E.g.:
SELECT * FROM CUSTOMERS GROUP BY City
HAVING BALANCE>10000;
The HAVING clause can contain either a simple boolean expression (i.e. a condition which
results into true or false) or use aggregate function in the having condition.
SQL AGGREGATE FUNCTIONS
An aggregate function performs a calculation on a set of values, and returns a single
value.
Except for COUNT , aggregate functions ignore null values.
Aggregate functions are often used with the GROUP BY clause of the SELECT
statement.
Commonly used Aggregate Functions are:
o AVG() – calculates the average of a set of values.
o COUNT () – counts rows in a specified table.
o MIN () – gets the minimum value in a set of values.
o MAX () – gets the maximum value in a set of values.
o SUM () – calculates the sum of values.
Creating a Database
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", passwd="")
mycursor = con.cursor()
mycursor.execute("DROP DATABASE IF EXISTS student")
mycursor.execute("CREATE DATABASE student")
mycursor.execute("USE student")
Creating the Table
mycursor.execute("DROP TABLE IF EXISTS studentinfo")
mycursor.execute("CREATE TABLE studentinfo (name VARCHAR(30), age INT(3), gender
CHAR(1))")
fetchmany([size=cursor.arraysize])
Fetch the next set of rows of a query result, returning a list of tuples. An empty list is returned
when no more rows are available.
The number of rows to fetch per call is specified by the parameter. If it is not given, the cursor’s
arraysize determines the number of rows to be fetched. The method should try to fetch as many
rows as indicated by the size parameter. If this is not possible due to the specified number of rows
not being available, fewer rows may be returned:
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", passwd="", database="student")
mycursor = con.cursor()
mycursor.execute("SELECT * FROM students;")
print(mycursor.fetchmany(3))
Differences between Char & Varchar
Char Varchar
Char datatype is used to store character Varchar datatype is used to store character
strings of fixed length. strings of variable length.
We can use char datatype when we know the We can use it when we are not sure of the
length of the string. length of the string.
Char datatype can be used when we expect Varchar datatype can be used when we expect
the data values in a column to be of same the data values in a column to be of variable
length. length.