You are on page 1of 122

XII D – Computer Science (Python)

S. Murugan @ Prakasam
PGT Teacher, Computer Science Dept
Database Management
What is Database?
➢ A Database is a collection of interrelated data and stored together to
serve multiple applications.
➢ A Database is a collection of interrelated data and set of programs to
access those data.
What is DBMS?
➢ DBMS stands for Data Base Management System, its refers to a
software(pre-written program) that is responsible for storing, organizing,
maintaining and utilizing(retrieving) databases.
➢ A database along with a DBMS is referred to as a database system.
➢ Duplication of data is known as Data Redundancy.
➢ Multiple Copies of same data but not matching with one another known
as Data Inconsistency.
➢ Primary goal of DBMS is provide an environment to convenient and
efficient to use in retrieving and storing database information.
➢ New categories of data can be added to the database without disturbing
existing system.
*Application of DBMS
Banking: For customer information, account activities, payments,
deposits, loans, etc.
Transport: For reservations and schedule information.
Universities: For student information, course registrations, colleges
and grades.
Libraries: For book information, book taken returned, updating etc.
Telecommunication: It helps to keep call records, monthly bills, maintaining
balances, etc.
Finance: For storing information about stock, sales, and
purchases of financial instruments like stocks and
bonds.
Sales: Use for storing customer, product & sales information.
Manufacturing: It is used for the management of supply chain and for
tracking production of items. Inventories status in
warehouses.
HR Management: For information about employees, salaries, payroll,
deduction, generation of paychecks, etc.
Relational Data Model
➢ In Relational Data Model, the data is organized into Tables (i.e. Rows
and Columns),these tables are called Relations.
➢ A row in a table represents a relationship among a set of values (data items).
➢ Relational Data Model represents data and relationship among the data
by a collection of tables, each of which has number of unique names.
➢ Relational Data Model is based on a collection of tables(relations).
➢ RDBMS is the subset of DBMS.
➢ Sample Database being shown here has three tables(relations):
Suppliers, Items ,Shipments.
➢ Suppliers(SuppNo, Supp_Name, Status, City)
➢ Items(ItemNo, Item_Name, Price)
➢ Shipments(SuppNo, ItemNo, Qty-supplied))
[bolded fields(words) are represented primary keys]
Each of these three tables closely resembles a conventional sequential
file, with of the table corresponding to records of the file and columns
corresponding to fields of the records.
Relational Data Model
Components of a Table
Rows/Tuples/Records: Its is a named collections of data items which represents
complete unit of data elements (information). They are logically related information.
Columns/Attributes/Fields: They are Columns containing one type of information.
Byte: It’s a group of eight bits and used to store a character.
Data Item(Field): A Data Item is the small unit of named data, it may consist
of any number of bits or bytes. A data item represents one type of information and is often
referred to as a fields or data elements.
Degree: The Number of Attributes in a relation determine the Degree of a
relation. A relation having 3 attributes is said to be a relation of degree 3. Similarly a
relation having N attributes is said to be a relation of degree N. Relations of degree one are
said to be Unary, Relations of degree two are Binary, Relations of degree three are
Ternary… and relation of degree N are called N-ary.
Cardinality: The Number of Tuples(rows)in a relation is called the cardinality of the
relation.(e.g.) the cardinality of suppliers relation is 5.
Domain: this is pool of values from which the actual values appearing in a given column
are drawn.
Views: Here Contents are taken from other tables depending upon a Condition, it’s a
(virtual) table that does not really exist in its own right but is instead derived from one or
more underlying base tables
Components of a Table
Components of a Table
*DBMS RDBMS
DBMS stores data as file. RDBMS stores data in tabular form.
Multiple data elements can be accessed at the
Data elements need to access individually.
same time.
Data is stored in the form of tables which are
No relationship between data.
related to each other.
Normalization is not present. Normalization is present.
DBMS does not support distributed database. RDBMS supports distributed database.
It uses a tabular structure where the headers are
It stores data in either a navigational or
the column names, and the rows contain
hierarchical form.
corresponding values.
It deals and handle with small quantity of data. It deals and handle with large amount of data.
Data redundancy is common in this model. Keys and indexes do not allow Data redundancy.
It supports single user. It supports multiple users.
Data fetching is slower for the large amount of Data fetching is fast because of relational
data. approach.
The data in a DBMS is subject to low security There exists multiple levels of data security in a
levels with regards to data manipulation. RDBMS.
Low software and hardware necessities. Higher software and hardware necessities.
Examples: MySQL, PostgreSQL, Microsoft SQL
Examples: XML, Microsoft Access, etc.
Server, Oracle DB, IBM DB2,SAP SASE etc.
Keys
Keys:
Keys also help uniquely identify relationships and thus distinguish
relationships from each other.
Its used to fetch or retrieve records/data rows from data table according
to the condition/requirements.
Keys are also used to create relationship among different database
tables or views.
Types:
1. Primary Key 2. Candidate Key
3. Alternate Key 4. Foreign Key
Primary Key:
A Primary Key is a set of one or more attributes that can uniquely
identify tuple(record) with in the relation (database table).It cannot accept Null
Value, Duplicate Values.
Keys
Keys
Unique Key:
A Unique Key is a set of one or more attributes that can uniquely identify
tuple(record) with in the relation (database table).It can accept Null Value (Only
One Null Value), cannot accept Duplicate Values.
Candidate Key:
All attribute combinations inside a relation that can serve as primary key
are candidate keys, they are candidates for the primary key position. It cannot
accept Null Value, Duplicate Values.
Alternate Key:
A Candidate key that is not the primary key is called an alternate key. It
cannot accept Null Value, Duplicate Values.
Foreign Key:
A Non-Key Attribute, whose values are derived from the primary key of
some other table, is known as foreign key in its current table.
Super Key:
Super key is a set of one or more than one keys that can be used to
identify a record uniquely in a table.(e.g.)Primary Key, Candidate Key, Alternate
Key.
SQL (Structured Query Language)
➢ SQL: is the standard command set used to communicate with relational
database management systems.
➢ SQL is Structured Query Language, which is a computer language for
storing, manipulating and retrieving data stored in relational database.
➢ All task are related to relational management creating tables, querying
the tables for information, modifying the data in the database, deleting them,
granting access to the users, etc.
➢ It is a user-friendly and domain-specific language.
➢ (e.g.) MySQL, Postgre SQL, Microsoft SQL Server, Oracle DB, IBM
DB2, SAP SASE etc.
➢ SQL usage by its very nature is extremely flexible, its uses free form
syntax gives the user the ability to structure SQL statements in a way best
suited to him.
➢ Each SQL request(queries) are parsed by RDBMS before execution, to
check the proper syntax and to optimize the request.
Advantages of SQL
➢ SQL is a High level language that provides a greater degree of data
abstraction than procedural languages.
➢ SQL enables the end-users and systems personnel, to deal with a number of
database management systems where it is available.
➢ SQL identifies what is required and not, how is should be done.
➢ All SQL operations are performed at a set level.one select can retrieve
multiple row, one modify statement can modify rows, etc.
➢ Standardized Language: It provides a uniform platform worldwide to all
its users.
➢ Portable: It can be used in programs in PCs, server, laptops independent of
any platform (Operating System, etc). Also, it can be embedded with other
applications as per need/requirement/use.
➢ Interactive Language: The language while being simple and easy to learn
can handle complex situation and also answers to complex queries can be
received in seconds.
Advantages of SQL
Faster Query Processing: Large amount of data is retrieved quickly and
efficiently. Operations like Insertion, deletion, manipulation of data is also
done in almost no time.

No Coding Skills: For data retrieval, large number of lines of code is not
required. All basic keywords such as SELECT, INSERT INTO, UPDATE, etc
are used and also the syntactical rules are not complex in SQL, which makes it
a user-friendly language.

Multiple data views: The main purpose of a view in SQL is thus to combine
data from multiple sources in a useful way without having to create yet
another database table to store that data. The multiple sources can include
tables and view from other database servers.
SQL Data Types
1.Charater(n): This data type represents a fixed length string of exactly ‘n’ character
where ‘n’ is greater than zero and should be an integer. It can contain letters, numbers,
and special characters, The size parameter specifies the column length in characters -
can be from 0 to 255. Default is 1.
Example : Name character(10)
2.varchar(n): This data type represents a varying length string whose maximum length
is ’n’ characters. It can contain letters, numbers, and special characters.
Example: Name varchar(n)
Varchar:
1.varchar can store up to 2000 bytes.
2. varchar occupies space for the NULL values.
Varchar2 :
1.varchar2 can store up to 4000 bytes. However, this was raised to 32,767 bytes as one of the
new features in Oracle 12c.
2. varchar2 is not occupying space for the NULL values.
3.Text:
1.Text can store up to 65,535 bytes.
2. Long Text can store up to 4,294,967,295 bytes of data.
SQL Data Types
4.Integer: An integer represents a signed integer decimal or binary.
Example: RollNo int(3) # int() #999
5.Small int: A small integer is a machine independent subset of the integer domain type.
Example: RollNo smallint() #tinyint,mediumint,bigint
6.Float(n): A floating point number, with precision of at least n digits.
Example: Rate float(5,2) or weight float() #652.56 #62.36
Decimal(p,q) Exact numerical, precision p, scale q. #decimal(5,2)
Example: decimal(5,2) is a number that has 3 digits before the decimal and 2 digits after the
decimal
Numeric(p,q) Exact numerical, precision p, scale q. (Same as DECIMAL)
7.Date: A calendar date containing a (four-digits)year, month and day of the month.
Example: DOB date() #year,datetime #int a=10 20 25
8.Time: The time of day in hours ,minutes and seconds . A variant time(P)can be used to
specify the number of fractional digits seconds(default begins 0).
Example: Arrival_Time time()
9.Timestamp: A combination of date and time. A variant, timestamp(P),can be used to specify
the number of fractional digits for seconds.
Example:
date’1987-10-25’ , time’07:25:25’ , timestamp ‘1987-10-25 08:25:45’
SQL Commands
The standard SQL commands to interact with relational databases are
CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These
commands can be classified into groups based on their nature. They are:

➢ DDL Commands(Data Definition Language)

➢ DML Commands(Data Manipulation Language)

➢ DRL/DQL Commands(Data Retrieval/Query Language)

➢ TCL Commands(Transaction Control Language)

➢ DCL Commands(Data Control Language)


SQL Commands Usage
Data Definition Language(DDL):
Create: its used to Creates a new table(database) structure.
Alter: its used to Modifies an existing database structure, (add, modify).
Drop: Deletes an entire table structure.
Truncate: Truncates the table values without delete table structure.
Rename: its used to rename an object existing in the database.
Data Manipulation Language (DML) :
Insert: its used to Creates a record in to a table.
Update: its used to Modifies records with in a table.
Delete: its used to Deletes records from a database table.
Data Query Language (DQL) :
Select: its used to Retrieves certain records from one or more tables.
Transaction Control Language (TCL) :
Commit: Save work done(all the changes made by statements issued), permanently.
Savepoint Name: Identify a point in a transaction to which we can later roll back.
Rollback to Name: Restore database to original since the last commit.
Data Control Language (DCL) :
Grant: Gives a privilege to users to perform specified tasks.
Revoke: Takes back privileges granted from user.
Create, View, Drop & Use Databases
DDL :Create & Show Tables
DDL :Create Table from Existing Table
Alter Table(Add, Drop Column)
Alter Table(Modify Column)
DDL : Rename
DDL : Drop Table, Truncate
DDL :Create Table (Primary)
DDL :Primary Selection
DDL :Different Constraints
DDL :Different Constraints
DML
DML : Insert, Update(set)
DML : Update(set)
DML: Update(After the Values Insert)
DML : Delete
DQL
➢ SELECT: The SELECT list is list of column names of tables named in the FROM list.
Column names can be prefixed by a range variable.
➢ FROM: The FROM list in the FROM division is a list of table names. A Table name
can be followed by a range variable. A range variable is particularly useful when the
same table name appears more than once in the from-list.
➢ WHERE: The qualification in the WHERE clause is a Boolean combination (i.e., an
expression using the logical connectives AND, OR, and NOT) of conditions of the form
expression op expression, where op is one of the comparison operators {<, <=, =, <>,
>=,>}.An expression is a column name, a constant, or an (arithmetic or string)
expression.
➢ DISTINCT: The DISTINCT keyword is used to display the unique tuple or eliminated
the duplicate tuple. This DISTINCT keyword is Optional.
➢ Between: The SQL BETWEEN Condition will return the records where expression is
within the range of value1 and value2. Its including the start & end values.
➢ Like: The Like operator used to select data by comparing the values of a character
variable to a specified pattern.
➢ IN: The IN operator allows you to determine if a specified value matches any value in a
set of values or returned by a sub query.
➢ Is Null: A column value is Null if it does not exist. The Is Null operator is used to
display all the rows for columns that do not have a value.
➢ Is Not Null: A column value is Not Null if it does not exist. The Is Not Null operator is
used to display all the rows for columns that has value.
DQL/DRL: from
DQL: from, where, between
DQL: like, in
DQL: LIKE Using %
DQL: in
DQL: Distinct
DQL: Distinct
DQL: Distinct
DQL: Distinct
DQL: is Null/ is Not Null
DQL
LOGICAL OPERATOR:
AND: TRUE if all the conditions separated by AND is TRUE.
OR: TRUE if any of the conditions separated by OR is TRUE.
NOT: Displays a record if the condition(s) is NOT TRUE.
LOGICAL OPERATOR
TCL

Transaction Control Language (TCL) :

Commit: Save work done(all the changes made by statements issued),


permanently).

Savepoint Name: Identify a point in a transaction to which we can later


roll back.

Rollback to Name: Restore database to original since the last commit.


TCL : Commit
TCL : Savepoint & Rollback
TCL : Savepoint & Rollback
SQL Functions:
Aggregate Functions/Group Functions/Multiple Row Functions:
➢ This functions is used to groups of rows rather than on single rows.
➢ Its performs a calculation on a set of values and returns a single value.
➢ All aggregate functions are deterministic.
Avg: calculate the average of a set of values.
Count*: counts rows in a specified table or view.
Min: gets the minimum value in a set of values.
Max: gets the maximum value in a set of values.
Sum: calculate the sum of values.
Count: counts rows in a specified table or view with options.
Option in Group By:
Distinct: this option causes a group function to consider only distinct values of
the argument expression.
All: this option causes a group function to consider all the values including all
duplicates.
Aggregate Functions or Group Functions
Aggregate Functions or Group Fuctions
DQL
Querying and Manipulating Data:

Order By: This statement used to sort the fetched the data in either in ascending
order or descending order. Default order is ascending order.
➢ asc – ascending order & desc – descending order, are keys used here.

Group By: This statement used to combines all those records that have similar
values in a particular field or a group of fields. In other words the Group By
clause is used in select statements to divide the table in to groups. Group can be
done by a column name or with aggregate functions in which case the aggregate
produces values for each group.

Having: The Having clause places conditions on groups in contrast to where


clause that places conditions on individual rows. While where Conditions cannot
include aggregate functions, Having conditions can do so.
DQL: Order By
DQL: Order By
DQL: Order By
DQL: Group By
DQL: Group By
DQL: Having
Non-Group Expressions with Group By
Math Functions
Power():Returns the arguments raised to the specified power.
Round():Rounds a number to a specified number of decimal places.
Mod():Returns the remainder of a number divided by other.
Ceil():Returns the largest integer value greater than or equal to the input
number(n)
Floor():Returns the smallest integer value not greater than than the argument.
Sqrt(): Returns the square root of N.
Sin(): Returns the Sine value of N.
Cos(): Returns the Cosine value of N.
Tan(): Returns the Tangent value of N.
Pi(): Returns the Pi value(3.14).
Log10(): Returns the Log of 10 value of N.
ABS(): Returns Absolute value of N.
Exp(): Returns the Expression value of N.
Sign(): Returns the sign of a given number.
Truncate(): Returns numeric expl truncated to exp2 decimal place. etc etc…
Math Functions : Power, Round, Mod
Math Functions
Math Functions
Math Functions
Math Functions using Tables
Math Functions using Tables
Math Functions using Tables
Math Functions using Tables
Math Functions using Tables
Text Functions
CHAR():Returns the character of the integer passed.
ASCII(): Returns the integer of the character passed. (ASCII value)
CONCAT(): Join any two strings.
LENGTH():Returns the length of a string in bytes.
LCASE/LOWER: Convert the given input in to lower case.
UCASE/UPPER: Convert the given input in to upper case.
MID/SUBSTRING/SUBSTR(): Extracts a substring from a string(staring at any
position).
LEFT(): Extracts a number of characters from a string (staring from left).
RIGHT(): Extracts a number of characters from a string (staring from right).
INSTR(): Returns the position of the first occurrence of a string in another string.
TRIM(): Remove leading and trailing spaces from a string.
LTRIM(): Remove leading spaces from a string.
RTRIM(): Remove trailing spaces from a string.
REVERSE(): Reverse a string and Returns the results.
REPEAT(): Repeat a strings s many times s specified.
STRCMP(): Compare two strings etc etc…
Text Functions
Text Functions
Text Functions
Text Functions
Text Functions
Text Functions using TABLE
Text Functions using TABLE
Text Functions using TABLE
Text Text Functions using TABLEFunctions
Text Functions using TABLE
Text Functions using TABLE
Text Functions using TABLE
Text Functions using TABLE with Condition
Text Functions using TABLE with Condition
Date Functions
CURDATE():Returns the current date of the system.(YYYY-MM-DD)
CURTIME(): Returns the current time of the system.(HH:MM:SS)
NOW(): Returns the current date and time of the system. (YYYY-MM-DD HH:MM:SS)
DATE(): Extract the date from given date time value.
MONTH(): Extract the month from given date time value.
YEAR(): Extract the year from given date time value.
DAY(): Extract the day from given date time value.
DAYNAME(): Returns the Name of the weekday for date.
MONTHNAME(): Returns the Full Name of the month for date.
SYSTIME(): Returns the current date and time of the system.
TIMESTAMP(): Returns the date time expression.
HOUR(): Returns the hour for the time.
MINUTE(): Returns the minute for the time.
SECOND(): Returns the second for the time.
DAYOFWEEK(): Returns the weekday index for date(Sunday=1,Monday=2,……Saturday=7)
DAYOFMONTH():Returns the day of the month for date, in range 0 to 31.
DAYOFYEAR():Returns the day of the year for date, in range 1 to 366.
WEEKOFYEAR(): Returns the calendar week day of the date, in range 1 to 53. etc etc…
Date Functions
Date Functions
Date Functions
Date Functions using Table
Date Functions using Table
Date Functions using Table
Date Functions using Table
Date Functions using Table
Date Functions using Table
Operations on Relations :Join Functions
➢ Join is a Query tat fetches data from two or more tables whose records are joined
with one another based on a condition.
Syntax: select <fields list> from <table1>,<table2>,<table3>, …where <join
condition for the tables>.
Equi Join: An SQL Join Query that joins two or more tables based on a condition
using equality(‘=’) operator.
Natural Join: A Natural Join is a type of equi join where the join condition
compares all the same names columns in both tables.

Inner Join: An Inner Join implements as equi join. In this join, only those rows are
returned from both the tables the satisfy the join condition. The Join conditions can
match records based on one or more columns.
Left Join: The Left Join is a particular type of join that selects rows from both left and
right tables that are matched, plus all rows from left table(Table A)even with no
matching row found in the right table(Table B).
Right Join: The Right Join is a particular type of join that selects rows from both
left and right tables that are matched, plus all rows from right table(Table B)even
with no matching row found in the left table(Table A).
Operations on Relations :Join Functions
Full Outer Join: The Full Outer Join returns all the records whether the condition is
matched or unmatched, records present in left table or right table .

UNION: The UNION operator is used to combine the result-set of two or more
SELECT statements into single result set. Each SELECT statement within UNION
must have the same number of columns and its keeps only unique records.

UNION ALL: Same as Union, but keeps all records, including duplicates.

Cartesian Product/Cross Join: An SQL Join Query without any join condition
returns all the records of joined with all the records of the others table.

MINUS: The MINUS operator is used to fetch records which present in left query
,but not in right query.

Intersect: This Operator is used to fetch common rows from two or more tables. Its
compares the result of two queries and returns the distinct rows that are output by both
left and right queries.
Equi Join
Natural Join
Natural Join
Natural Join
Natural Join
Inner Join
Left Join
Left Join
Right Join
Right Join
Full / Outer Join
MySQL does not support FULL JOIN, so we have to combine Left JOIN, UNION ALL and
Right JOIN to get an equivalent.
Full / Outer Join
MySQL does not support FULL JOIN, so we have to combine Left JOIN, UNION ALL and
Right JOIN to get an equivalent.
Cartesian Product
Cartesian Product
Cartesian Product
Union of Tables
Union of Tables
Union All of Tables
Perform Union Operation using Two Different Fields
Minus/Except
Intersect
THANK YOU

You might also like