0% found this document useful (0 votes)
54 views145 pages

Database

The document discusses key concepts related to databases and SQL, including: - A database is a collection of related data that can be processed to produce information, while a database management system (DBMS) stores data in a way that makes it easier to retrieve, manipulate, and produce information from that data. - DBMSs follow ACID properties of atomicity, consistency, isolation, and durability and support features like concurrent access, multiple views, and security. - Data models like the entity-relationship and relational models define how data is structured and related within a database. - SQL is the most widely used language for managing relational databases and allows users to create and modify database structures as

Uploaded by

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

Database

The document discusses key concepts related to databases and SQL, including: - A database is a collection of related data that can be processed to produce information, while a database management system (DBMS) stores data in a way that makes it easier to retrieve, manipulate, and produce information from that data. - DBMSs follow ACID properties of atomicity, consistency, isolation, and durability and support features like concurrent access, multiple views, and security. - Data models like the entity-relationship and relational models define how data is structured and related within a database. - SQL is the most widely used language for managing relational databases and allows users to create and modify database structures as

Uploaded by

Waqas Ahmad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 145

CSS Computer Science

BY MARYAM JAVED
MPHIL COMPUTER SCIENCE
Database

 Database is a collection of related data and data is a collection of facts and figures
that can be processed to produce information.

Database Management System


 A database management system stores data in such a way that it becomes easier
to retrieve, manipulate, and produce information.
Characteristics of DBMS

• ACID Properties − DBMS follows the concepts


of Atomicity, Consistency, Isolation, and Durability (normally shortened as
ACID). These concepts are applied on transactions, which manipulate data in a
database. ACID properties help the database stay healthy in multi-transactional
environments and in case of failure.
• Multiuser and Concurrent Access − DBMS supports multi-user environment
and allows them to access and manipulate data in parallel. Though there are
restrictions on transactions when users attempt to handle the same data item, but
users are always unaware of them.
Characteristics of DBMS (Cont.)

• Multiple views − DBMS offers multiple views for different users. A user who is
in the Sales department will have a different view of database than a person
working in the Production department. This feature enables the users to have a
concentrate view of the database according to their requirements.
• Security − Features like multiple views offer security to some extent where users
are unable to access data of other users and departments. DBMS offers methods
to impose constraints while entering data into the database and retrieving the
same at a later stage. DBMS offers many different levels of security features,
which enables multiple users to have different views with different features. For
example, a user in the Sales department cannot see the data that belongs to the
Purchase department. Additionally, it can also be managed how much data of the
Sales department should be displayed to the user. Since a DBMS is not saved on
the disk as traditional file systems, it is very hard for miscreants to break the code.
Data Models

 Data models define how the logical structure of a database is modeled. Data
Models are fundamental entities to introduce abstraction in a DBMS. Data models
define how data is connected to each other and how they are processed and stored
inside the system.
Types of Data Models

 Entity Relationship Data Model: Entity-Relationship (ER) Model is based on the


notion of real-world entities and relationships among them. While formulating
real-world scenario into the database model, the ER Model creates entity set,
relationship set, general attributes and constraints. ER Model is best used for the
conceptual design of a database.
 ER Model is based on −
 Entities and their attributes.
 Relationships among entities.
 Relational Model: The most popular data model in DBMS is the Relational
Model. It is more scientific a model than others. This model is based on first-order
predicate logic and defines a table as an n-ary relation.
Relational Data Model

 Data is stored in tables called relations.


 Relations can be normalized.
 In normalized relations, values saved are atomic values.
 Each row in a relation contains a unique value.
 Each column in a relation contains values from a same domain.
Constraints on Relational Model

 Mainly Constraints on the relational database are of 4 types:

 Domain constraints
 Key constraints
 Entity Integrity constraints
 Referential integrity constraints
SQL

 Structured Query Language, abbreviated as SQL, is a domain-specific language


used in programming and designed for managing data held in a relational database
management system, or for stream processing in a relational data stream
management system
Objectives of SQL
• Ideally, database language should allow user to:
– create the database and relation structures;
– perform insertion, modification, deletion of data from relations;
– perform simple and complex queries.

• Must perform these tasks with minimal user effort and command
structure and syntax must be easy to learn.

• It must be portable.

• SQL does not contain flow control commands. These must be


implemented using a programming or job-control language, or
interactively by the decisions of the user.

1
0
Objectives of SQL …
• SQL is relatively easy to learn:
– It is a non-procedural language - you specify what
information you require, rather than how to get it.
– It is essentially free-format.

• Can be used by a range of users including DBAs, management,


application programmers, and other types of end users.

• An ISO standard now exists for SQL, making it both the formal and
de facto standard language for relational databases.

1
1
Objectives of SQL …
• Consists of standard English words:

CREATE TABLE staff(


sno

VARCHAR(5),
lname

VARCHAR(15),
salary

NUMBER(7,2)
);

INSERT INTO staff


VALUES ('SG16', 'Brown', 8300);

SELECT sno, lname, salary


FROM staff 1
WHERE salary > 10000; 2
Components of SQL
• A database language must have support for the components
listed below. Most implementations of SQL support various
components listed below:
– Data Definition Language (DDL)
– Interactive Data Manipulation Language (Interactive
DML)
– Embedded Data Manipulation Language (Embedded
DML)
– Views
– Integrity and transaction control
– Authorization & Security (DCL)
– Catalog and dictionary facility.
13
Basic Guidelines for Writing SQL
Statements …
• SQL statement consists of reserved words and user-defined words.
– Reserved words are a fixed part of SQL and must be spelt exactly as
required and cannot be split across lines.
– User-defined words are made up by user and represent
names of various database objects such as relations, columns, views.

• Most components of an SQL statement are case insensitive, except for


literal character data.

• More readable with indentation and lineation:


– Each clause should begin on a new line.
– Start of a clause should line up with start of other clauses.
– If clause has several parts, should each appear on a separate line and be
indented under start of clause.

14
Basic Guidelines for Writing SQL
Statements …
• Use extended form of BNF notation:
– Upper case letters represent reserved words.
– Lower case letters represent user-defined words.
– | indicates a choice among alternatives.
– Curly braces indicate a required element.
– Square brackets indicate an optional element.
– … indicates optional repetition (0 or more).
– ALL SQL is case less

15
ISO SQL Data Types

16
Comparison Operators in SQL
• There are six comparison operators in SQL. These operators are used
to build conditions that are used in the WHERE clause of a DML
statement:

Operator Meaning
= Equal to
<> Not equal to

< Less than


> Greater than
<= Less than and equal
to
>= Greater than and
equal tp 17
Logical Operators in SQL

• There are three logical operators that help us to build


compound conditions to be used in the WHERE clause of
the SELECT statement.
– The AND operator joins two or more conditions, and
display a row only if that row’s data satisfies ALL the
specified conditions.
– The OR operator joins two or more conditions, and
display a row only if that row’s data satisfies any of the
specified conditions.
– The NOT is a unary operator, and is used to negates a
condition.
18
Arithmetic Operators in SQL
• Another feature of SQL allows the use of arithmetic in
queries.

– The standard arithmetic operators ( +, -, /, *) can be


applied to numeric values or attributes with numeric
domain.

– The arithmetic operators can be used in expressions in


the SELECT and the WHERE clauses to compute
numeric values.

– All attributes that can be computed using arithmetic


expressions (such as age from birth date, annual salary
from monthly salary) must be eliminated as
part of a good desDig.r naEjpz Arahmcetdice in databases. 18
SQL Schema and Catalog

• In SQL92, relations and other database objects exist in an

 environment.

 Each environment contains one or more catalogs, and each catalog consists of
set of schemas.

 Schema is a named collection of related database objects.

 Objects in a schema can be tables, views, domains, constraints,


translations, and character sets. All have same owner.
20
SELECT
• SELECT Definition
• Selecting Columns
• Selecting Rows
• Sorting
• Aggregation
• Grouping
• Restricting Groups
• Aliasing Table Names
• Nested Queries
• Join
• Set Operations
21
SELECT Definition …

• SQL has only one statement for retrieving information from a database
called the SELECT statement.

• SQL SELECT statement is different from that of Relational Algebra.

• An important distinction between SQL and formal relational model is that


SQL allows duplicate rows. Hence an SQL table is not a set but a multiset
(some times called a bag) of tuples.

22
Retrieving Information From the Database

Jo
Sm hn ry
ith Ma es
l
Sti
Data

DB

23
SQL

24
SQL - Usage

25
SELECT Definition …
• A SELECT statement can consist up to six clauses.

SELECT [DISTINCT | ALL]


{*
|
[column_expression
[WHERE condition][AS
new_name]]
[GROUP BY [,...] }
column_list]
FROM
[HAVING table_name
condition][alias] [, ...]
[ORDER By column_list]

• Only SELECT and FROM clauses are mandatory.

• Order of the clauses cannot be changed.

26
SELECT Definition …

• FROM Specifies table(s) to be used.

• WHERE Filters rows.

• GROUP BY Forms groups of rows with same column value.

• HAVING Filters groups subject to some condition.

• SELECT Specifies which columns are to appear in output.

• ORDER BY Specifies the order of the output.

27
Selecting Columns
• Selecting all columns +
• Selecting Specific columns +
• Selecting Computed columns +
• Renaming Columns +

28
Input Tables

Selecting All Columns


Example 1:
City Year Cars_sold

SELECT city, year, cars_sold Dhahran 2001 525


FROM car_sales;
Dhahran 2002 456
• Can use * as an abbreviation
for 'all columns': Riyadh 2001 700

Riyadh 2002 654


Example 2:
Jeddah 2001 921
SELECT *
FROM car_sales; Jeddah 2002 752

Khobar 2002
29
Input Tables

Selecting Specific Columns


• Selected columns can be listed as
shown in the following example.
City Cars_sold
Notice that the year column was
not selected so it doesn’t appear Dhahran 525
in the output.
Dhahran 456
Example: Riyadh 700

Riyadh 654
SELECT city, cars_sold
FROM car_sales; Jeddah 921

Jeddah 752

Khobar

30
Input Tables

Selecting Computed Columns

• If the value of a car is


100,000 then the total City Year Cars_Sold Cars_Sold *100000
sales per year for each
city is computed as Dhahra 2001 525 52500000
n
follows.
Dhahra 2002 456 45600000
n
Example: Riyad 2001 700 70000000
h
Riyad 2002 654 65400000
SELECT h
city
Jedda 2001 921 92100000
,year h
,cars_sold Jedda 2002 752 75200000
,cars_sold * 100000 h
FROM car_sales; Khoba 2002 0 0
r
31
Input Tables

Renaming Columns

• The name of the


computed column in City Year Sold sales
the last slide cab be
changed from Dhahra 2001 525 52500000
cars_sold*100000 to n
sales as follows. Dhahra 2002 456 45600000
n

Example: Riyad 2001 700 70000000


h
Riyad 2002 654 65400000
SELECT h
city
Jedda 2001 921 92100000
,year h
,cars_sold As Sold
Jedda 2002 752 75200000
,cars_sold * 100000 h
AS sales
FROM car_sales; Khoba 2002 0 0
r
32
Selecting Rows
• Selecting All Rows +
• Partial match Search +
• Range Search +
• Set Membership Search +
• Pattern matching Search +
• Null Search +
• Removing Duplicate Rows +

33
Input Tables

Selecting All Rows

• A SELECT statement without a


WHERE clause selects all rows. City Year Cars_Sold

Dhahra 2001 525


Example: n
Dhahra 2002 456
n

*
Riyad 2001 700
SELECT h
Riyad 2002 654
FROM car_sales; h
Jedda 2001 921
h
Jedda 2002 752
h
Khoba 2002
r

34
Selecting Rows
• To Select certain rows of a table you need to use the
WHERE clause of the SELECT statement.
• The WHERE clause has a condition which is a logical
expression.
• The Where condition consists of:
– Comparison Operators
– Logical Operators
– Arithmetic Operators
– Other SQL constructs which will be discussed later.
• A record to be selected it must make the WHERE logical
expression true. In other words it must satisfy the where
condition.
35
Input Tables

Partial match Search

• Selecting all the records whose column City Year Cars_Sold


values match the column values specified
in the WHERE clause.
Dhahra 2001 525
n
Example1:
SELECT * Dhahra 2002 456
n
FROM car_sales
WHERE city = ‘Dhahran’;

Example2:

SELECT * City Year Cars_Sold


FROM car_sales
WHERE city = ‘Dhahran’ Dhahra 2002 456
AND year > 2001; n
36
Input Tables

Range Search
Selecting all the records whose column values is
between the values specified in the WHERE cluause.
Example:
City Year Sold
SELECT *
FROM car_sales
WHERE cars_sold >= 525 Dhahra 2001 525
AND cars_sold n
<= 752; Riyad 2001 700

OR h
Riyad 2002 654
SELECT * h
FROM car_sales
WHERE cars_sold
Jedda 2002 752
BETWEEN 525 h
AND 752;
range.
■ BETWEEN test includes the 36
endpoints of range. NOT
Input Tables

Set Membership Search …


Selecting all the records whose column value is a member of the set
specified in the WHERE clause.

Example: City Year Sold

SELECT * Dhahra 2001 525


FROM car_sales n
WHERE city Dhahra 2002 456
n
IN
Riyad 2001 700
(‘Dhahran’,
h
‘Riyadh’);
Riyad 2002 654
h

38
Input Tables

Set Membership Search

Selecting all the records whose column value not a member of the set
specified in the WHERE clause.

Example:
City Year Sold
SELECT *
FROM car_sales
Jedda 2001 921
h
WHERE city
NOT IN Jedda 2002 752
(‘Dhahran’, h
‘Riyadh’); Khoba 2002
r

39
Pattern Matching Search …
• SQL has two special pattern
matching symbols:
– %: sequence of zero or more characters;
– _ (underscore): any single character.

• LIKE '%dd%' means a sequence


of characters of any length containing ‘dd'.

40
Input Tables

Pattern matching Search


Selecting all the records whose column value match the pattern specified in the
WHERE clause.

Example: Example:

SELECT * SELECT *
FROM car_sales FROM car_sales
WHERE WHERE
city LIKE ‘J%’ city LIKE ‘%dd
%’

City Year Sold City Year Sold

Jedda 2001 921 Jedda 2001 921


h h

Jedda 2002 752 Jedda 2002 752


h Dr. Ejaz Ahm ed h 40
Input Tables

NULL Search
Example 1: Select all cities Example 2: Select all cities where
where the number of cars the number of cars sold is kown.
sold is unkown.
SELECT city
FROM car_sales
SELECT city
WHERE
FROM car_sales
cars_sold IS
WHERE
NOT NULL; City
cars_sold IS
NULL; City Dhahran
Dhahran
Khoba Riyadh
r Riyadh
Jeddah
Jeddah
Input Tables

Removing Duplicate Rows


Example1: Example2:

SELECT city SELECT DISTINCT city


FROM car_sales
FROM car_sales
City

Dhahra City
nDhahra
Dhahra
nRiyad
nRiyad
hRiyad
hJedda
hJedda
hKhoba
r
hJedda

hr Khoba

Using DISTINCT in the SELECT clause removes duplicate rows from the output table
43
Sorting
• The ORDER BY clause specifies an order
for displaying the result of a query.
– SQL allows the user to order the tuples in the result of a query by the
values of one or more attributes; the default order is ascending or
increasing.

– The keyword DESC is specified to sort in a descending order of


values while the keyword ASC can be used to specify ascending
order explicitly.

– The sorting will be applied alphabetically or numerically


depending on the type of the column attribute.
44
Input Tables

Example: Sorting
Example: SELECT *
FROM car_sales
The following SELECT statement ORDER BY city asc, car_sales desc;
sorts the car_sales table in
City Year Cars_Sold
ascending order of city and
descending order of car_sales Dhahra 2001 525
columns n
Dhahra 2002 456
n
Jedda 2001 921
h
Jedda 2002 752
h
Khoba 2002
r
Riyad 2001 700
h
Riyad
Dr. Ejaz Ahmed 2002 654 44
h
Aggregation …

• ISO standard defines five aggregate functions:

– COUNT returns number of values in a specified


column.
– SUM returns sum of values in a specified column.
– AVG returns average of values in a specified
column.
– MIN returns smallest value in a specified column.
– MAX returns largest value in a specified column.

46
Aggregation …

 Each operates on a single column of a table and return single value.

 COUNT, MIN, and MAX apply to numeric and non-numeric fields, but SUM and
AVG may be used on numeric fields only.

 Apart from COUNT(*), each function eliminates nulls first and


operates only on remaining non-null values.

 COUNT(*) counts all rows of a table, regardless of whether nulls or duplicate


values occur.

 47duplicates.
Can use DISTINCT before column name to eliminate
Aggregation …

• DISTINCT has no effect with MIN/MAX, but may have with SUM/AVG.

• Aggregate functions can be used only in SELECT list and in HAVING


clause.

• If SELECT list includes an aggregate function and there is no GROUP BY


clause, then SELECT list cannot reference a column with an aggregate
function. For example, following is illegal:

SELECT city, COUNT(*)


FROM car_sales;

48
Input Tables

Example : COUNT

• How many ■ How many cities are


are there in rows there in the
table? car_sales
car_sales table? the
SELECT
SELECT COUNT(*) as Rows COUNT(DISTINCT city)
FROM car_sales as city
FROM car_sales

Rows city

7 4
Input Tables

Example : SUM
• Find the total number of ■ Find the number of all the
all the cars sold from the cars_sold in Dhahran from the
car_sales table? car_sales table?

SELECT SELECT
SUM(cars_sold) as cars_sold SUM(cars_sold) as Dah_cars
FROM car_sales FROM car_sales
WHERE city = ‘Dhahran’

Cars_sold Dah_cars

4008 981
Input Tables

Example: MIN, MAX, AVG

• Find the minimum, maximum, and average cars_sold per year and per
city form the car_sales table

SELECT MIN(cars_sold) as Min_sold


, MAX(cars_sold) as Max_sold
, AVG(cars_sold) as
Avg_sold FROM car_sales
WHERE car_sales IS NOT
NULL;
Min_sold Max_sold Avg_sold

456 921 668

51
Grouping
• Use GROUP BY clause to get sub-totals.
• SELECT and GROUP BY closely integrated: each item in SELECT list
must be single-valued per group, and SELECT clause may only
contain:
– Column names.
– Aggregate functions.
– Constants.
– An expression involving combinations of the above.

• All column names in SELECT list must appear in GROUP BY clause


unless name is used only in an aggregate function.

• If WHERE is used with GROUP BY, WHERE is applied first, then groups
are formed from remaining rows satisfying predicate.

• ISO considers two nulls to be equal for purposes of GROUP BY.

52
Input Tables

Example: Grouping
• Find the total cars sold in each city from the car_sales table.

SELECT city, SUM(cars_sold) as cars


FROM car_sales
WHERE cars_sold IS NOT NULL
GROUP BY city
ORDER BY SUM(cars_sold) ;

City Cars
Dhahran 981
Riyad 1354
Jheddah 1637

53
Restricting Groups

• HAVING clause is designed for use with GROUP BY clause to


restrict groups that appear in final result table.

• Similar WHERE, but WHERE filters individual rows


whereas
to HAVING filters groups.

• Column names in HAVING clause must also appear in the


GROUP BY list or be contained within an aggregate function.

54
Input Tables

Example: Restricting Groups

• Find the cities who sold a total of more than 1000 cars from the
car_sales table.

SELECT city, SUM(cars_sold) as cars


FROM car_sales
WHERE cars_sold IS NOT NULL
GROUP BY city
HAVING SUM(cars_sold) > 1000
;

City Cars
Riyad 1354
Jhedda 1637
h

55
Aliasing Table Names

• A table alias is created by directly placing an alias after the table name
in the FROM clause.
• The advantage of using a table alias when performing JOIN is
readily apparent when we discuss JOIN later.

• For example in the following example we will refer to departments


table as d or dept.

SELECT d.dname SELECT dept.dname


FROM departments d FROM departments dept
WHERE d.dno = 1; WHERE dept.dno = 1;
56
Nested queries

• Some SQL statements can have


SELECT
a embedded within them.
• A subselect can be used in WHERE
and
HAVING clauses of an outer SELECT, where
it is called a nested query or a
subquery.
• Subselects may also appear in INSERT,
UPDATE, and DELETEs.
57
Example: Nested queries
• From the Lecturer table, select lecturers
whose salary is above average.
• Cannot write 'WHERE salary
avg(salary)'.
> Inner select

SELECT *
FROM lecturers
WHERE salary (
> SELECT AVG(salary)
FROM lecturers
Outer
);
select

▪ The Inner select is done before the outer select.


58
Input Tables

Nested query: Example

• List the names of all Lecturers who are in


the ICS department

SELECT lname
FROM lecturers
WHERE dno IN
( SELECT dno
FROM department
WHERE dname
); = ‘ICS’

59
Nested Query Rules

• ORDER BY clause may not be used in a subquery (although it may be


used in outermost SELECT).
• Subquery SELECT list must consist of a single column name or
expression, except for subqueries that use EXISTS.
• By default, column names refer to table name in FROM clause of
subquery. Can refer to a table in FROM using an alias.
• When subquery is an operand in a comparison, subquery
must appear on right-hand side.
• A subquery may not be used as an operand in an expression.

60
Input Tables

Nested Query: Example


• Find lecturers whose salary higher
than the salary of at least 1 COE lecturer.
SELECT *
FROM Lecturers
WHERE salary >

(
SELECT min(salary)
FROM lecturers
WHERE dno = SELECT DNO
FROM department
( WHERE dname = ‘COE’
);

61
Input Tables

Nested Query: Example


• Find lecturers whose salary higher than the salary of every COE lecturer.

SELECT *
FROM Lecturers
WHERE salary >

(
SELECT max(salary) SELECT DNO
FROM lecturers FROM department
WHERE dno = WHERE dname = ‘COE’

(
);

) 62
Join
• Can use subqueries provided result columns come from same table.
• If result columns come from more than one table must use a join.
• To perform join, include more than one table in FROM clause.
• Use comma as separator and typically include WHERE clause to
specify join column(s).

• Also possible to use an alias for a table named in FROM clause.

• Alias is separated from table name with a space.

• Alias can be used to qualify column names when there is ambiguity.

63
Input Tables

Example: Join (Inner Join)


• The default type of join is inner join, where arow is included in the
result only if matching row exists in the other relation.
• List each lecturer’s name and his department name.

Lname dname
SELECT a.lname, b.dname Ahme IC
FROM lecturers a,
Admin CS O
departments b E
Han
WHERE a.dno = b.dno; IC
iAgee SIC
l S
PK-FK never makes default Yousef CO
join, must specify Join in SQL E
Khali CO
d E
64
Example: Join (Inner Join) …
• To obtain correct rows, include only those
rows from both tables that have identical
values in the dno columns: a.dno = b.dno.

• These two columns are the matching columns


for two tables.

• This type of join is also called inner join and


they equivalent to equi-join in relational
algebra.
65
Computing a Join
• Procedure for generating results of a SELECT
with a join are:
1. Form Cartesian product of the tables named in FROM
clause.
2. If there is a WHERE clause, apply the search condition to
each row of the product table, retaining those rows that
satisfy the condition.
3. For each remaining row, determine the value of each item
in the SELECT list to produce a single row in the result
table.
4. If SELECT DISTINCT has been specified, eliminate any
duplicate rows from the result table.
5. If there is an ORDER BY clause, sort the result table
as required. 65
Outer Joins
• With an inner join, if one row of a table is unmatched,
row is omitted from result table.
• The outer join operations retain rows that do not satisfy the
join condition.
• There are three types of OUTER JOIN
– Left Outer Join
– Right Outer Join
– Full Outer Join
• Lets discuss inner join then we will come back to outer
join.
• Query (Performance) is much better than
execution other
joins
Input Tables

Outer Join …
• Inner join of departments
and lecturers tables will
result in the following Lid Lname dno salary dno dname
output.
1 Ahme 1 4000 1 IC
S
2 Admin 2 3700 2 CO
SELECT a.*, b.* 3 Han 1 4200 1 E
IC
FROM lecturers a, i S
4 Agee 1 4000 1
Departments b IC
WHERE a.dno = b.dno 5
l
Yousef 2 3500 2 S
CO
E
6 Khali 2 4500 2 E
CO
d

68
Outer Join …

 Result table has two rows where the dno are the
same.

 There are no rows corresponding to NW or


Abdella.

 To include unmatched rows in result table, use an


outer join. 69
Input Tables

Example: Left Outer Join


• If We want to Include in
the output table the
lecturers Lid
whose department is Lname dno salary dno dname
we
unknow rewrite our
1 Ahme 1 4000 1 S
previous query as E
follows 2 Admin 2 3700 2 SW
3 Han 1 4200 1 E
IC
i S
5 Agee 1 4000 1 SW
SELECT a.*, b.* l E
6 Yousef 2 3500 2 CO
FROM lecturers a, 7 Khali 2 4500 2
E
CO
Departments b 4 4300 E
dAddella
WHERE a.dno = b.dno(+)

70
Input Tables

Example: Right Outer Join


• If We want to Include in Lid Lname dno salary dno dname
the output table the
departments with no 1 Ahme 4 4000 4 S
lecturers we rewrite our 2 3 3700 3
E
previous query as Admin SW
follows 3 Han 1 4200 1 E
IC
i S
5 Agee 3 4000 3 SW
l E
6 Yousef 2 3500 2 CO
E
7 Khali 2 4500 2
SELECT a.*, b.* d
CO
5
FROM lecturers a, NEW
Departments b
WHERE a.dno (+) = b.dno

71
Input Tables

Example: Full Outer Join


• If We want to Include in Lid Lname dno salary dno dname
the output table the
departments with no 1 Ahme 4 4000 4 S
lecturers and the lecturers E
2 Admin 3 3700 3 SW
with unknow
departments we rewrite 3 Han 1 4200 1 E
IC
our previous query as i S
follows 5 Agee 3 4000 3 SW
l E
6 Yousef 2 3500 2 CO
SELECT a.*, b.* E
7 Khali 2 4500 2 CO
FROM lecturers a,
d
Departments b 5 NEW
WHERE a.dno (+) = b.dno
4 Abdella 4300
UNION
SELECT
a.*, b.* FROM
lecturers a,
Departments b
WHERE a.dno= b.dno (+);
72
Characteristic of Outer Join
• Left Outer Join:
– Includes those rows of first (left) table unmatched with
rows from second (right) table.
– Columns from second table are filled with NULLs.

• Right outer Join :


– includes those rows of second (right) table that are unmatched with rows
from first (left) table.
– Columns from first table are filled with NULLs.

• Full Outer Join:


– Is the UNION of both left and right outer joins.

73
Examples: Left, Right and Full Outer
Joins

74
Union, Intersect, and Difference
• Can use normal set operations of union, intersection, and
difference to combine results of two or more queries into a
single result table.
• Union of two tables, A and B, is table containing all rows in
either A or B or both.
• Intersection is table containing all rows common to both A
and B.
• Difference is table containing all rows in A but not in B.
• Two tables must be union compatible.
• If ALL specified, result can include duplicate rows

75
Input Tables

Example: Use of UNION

• List all the ICS and COE  List all the ICS and COE facu
faculty salaries. Include duplicates
salaries. Remove
duplicates
 SELECT salary FROM
SELECT salary lecturers WHERE dno =
FROM lecturers 1 UNION ALL
WHERE dno =  SELECT salary FROM
1 UNION lecturers WHERE dno =
SELECT salary 2;
FROM lecturers
WHERE dno = 2;
Input Tables

Example: Use of UNION …


• List the ICS and COE ■ Listall the ICS and COE
faculty
all salaries. Remove faculty salaries. Include
duplicates duplicates

SELECT salary SELECT salary


FROM lecturers FROM lecturers
WHERE dno = WHERE dno =
( SELECT dno ( SELECT dno
FROM FROM
departments departments
) WHERE ) WHERE
dname= ‘ICS’
UNION dname=ALL
UNION ‘ICS’
SELECT salary SELECT salary
FROM lecturers FROM lecturers
WHERE dno = WHERE dno =
( SELECT dno ( SELECT dno
FROM FROM
departments departments
) WHERE ) WHERE
dname= ‘COE’ 77 ‘COE’
dname=
Input Tables

Example: Use of DIFFERENCE


• List salaries that are taken by ICS and not COE lecturers.

SELECT salary
FROM lecturers
WHERE dno =
(
S
E
L
E
C
T

d
n
o
FROM departments
where dname=
‘ICS’ 78
)
Input Tables

Example: Use of INTESECTION


• List salaries that are taken by both COE and ICS lecturers.

SELECT salary
FROM lecturers
WHERE dno =
(
S
E
L
INTERSECTION E
SELECT salary C Produces result tables from both
FROM lecturers T queries and creates single result
WHERE dno = table consisting of those rows that
( SELECT
d dno
are common to both result tables.
FROM
n departments
WHERE
o dname= ‘COE’
) FROM departments
where dname=
‘ICS’ 79
)
Other SQL Operators
• IN (covered)
• BETWEEN (covered)
• LIKE (covered)
• ANY (SOME)
• ALL
• EXISTS
• NOT EXISTS

80
ANY (SOME) and ALL

• ANY and ALL may be used with subqueries that produce a single
column of numbers.

• If subquery preceded by ALL, condition will only be true if it


is satisfied by all values produced by subquery.

• If subquery preceded by ANY, condition will be true if it is satisfied by


any values produced by subquery.

• If subquery is empty, ALL returns true, ANY returns false.

• ISO standard allows SOME to be used in place of ANY.

81
Input Tables

Example using the SOME Operator


• Find lecturers whose salary higher
than the salary of at least 1 COE lecturer.
SELECT *
FROM Lecturers
WHERE salary > SOME (
SELECT salary
FROM lecturers
WHERE dno =
SELECT DNO
( FROM department
WHERE dame = ‘COE’
)
);

82
Example Using the ALL
Operator
• Find lecturers whose salary higher than the salary of every COE lecturer.

SELECT *
FROM Lecturers
WHERE salary > ALL
SELECT salary
( FROM lecturers
WHERE dno =
SELECT DNO
( FROM department
WHERE dname = ‘COE’
)
);

83
EXISTS and NOT EXISTS
• EXISTS and NOT EXISTS are for use only with subqueries specially with
correlated subqueries. A correlated subquery is a subquery where some
attributes of the outer select are used in the inner select.

• They produce a simple true/false result.

• EXISTS is true if and only if there exists at least one row in result table returned by
subquery.

• It is false if subquery returns an empty result table.

• NOT EXISTS is the opposite of EXISTS.

• Since EXISTS and NOT EXISTS check only for existence or non-existence of
rows in subquery result table, subquery can contain any number of columns.

84
--- Example using the
EXIS T S Operator
In put Tables

• Find all ICS lecturers.

SELECT *
FROM lecturers a
WHERE EXISTS
(
SELECT 1
FROM department b
WHERE a.dno = b.dno
AND b.dname
= ‘ICS‘
);

85
Example using the NOT
EXISTS Operator
• Find all non
ICS lecturers.
SELECT *
FROM lecturers a
WHERE NOT EXISTS
(
SELECT 1
FROM department b
WHERE a.dno = b.dno
AND b.dname
= ‘ICS‘
);

86
More SQL Functions
 SUBSTR TO_CHAR
 INSTR TO_DATE
 LENGTH
TO_NUMBER
 LEFT, RIGHT
 ADD_MONTHS
LPAD, RPAD
 TRIM FLOOR
 DECODE SYSDATE
 CEIL NVL
 ROWNUM
TRANSLATE
SQL Data Definition Statements
(DDL)
• CREATE SCHEMA and DROP SCEHMA +
• CREATE TABLE +
• ALTER TABLE +
• DROP TABLE +

88
CREATE SCHEMA and DROP
SCHEMA
CREATE SCHEMA [name| AUTHORIZATION creator_id ];

Example: CREATE USER COMPANY IDENTIFIED BY password;

DROP SCHEMA name [RESTRICT | CASCADE ];

Example: DROP USER COMPANY CASCADE;

• With RESTRICT (default), schema must be empty or operation fails.

• With CASCADE, operation cascades to drop all objects associated with schema in
the order defined above. If any of these operations fail, DROP SCHEMA fails.

89
CREATE TABLE
CREATE TABLE table_name
(col_name data_type [NULL | NOT NULL] [,...]);

• Creates a table with one or more of the specified


columns
data_type.
• NULL (default) indicates whether column can contain nulls.

• With NOT NULL, system rejects any attempt to insert a null in the
column.

• Primary keys should always be specified as NOT NULL.

• Foreign keys are often (but not always) candidates for NOT NULL.
90
CREATE TABLE – Example 1
CREATE TABLE Employee
(
fname VARCHAR2(15) NOT NULL,
minit CHAR,
lname VARCHAR2(15) NOT NULL,
ssn CHAR(9),
bdate DATE,
address VARCHAR2(50),
sex CHAR,
salary NUMBER(10,2) NOT NULL,
Superssn CHAR(9),
dno NUMBER(3) NOT NULL,
CONSTRAINT employee_ssn_pk PRIMARY KEY(ssn),
CONSTRAINT employee_superssn_fk
FOREIGN KEY(Superssn) REFERENCES
employee(ssn),
CONSTRAINT employee_dno_fk
FOREIGN KEY(dno) REFERENCES
department(dnumber),
);
91
CREATE TABLE – Example 2

CREATE TABLE department


(
dname VARCHAR2(15 NOT NULL,
dnumber ) NUMBER(3) NOT
mgrssn CHAR(9), NULL,
mgrStartDateDATE,
CONSTRAINT department_dnumber_pk
PRIMARY KEY(dnumber),
CONSTRAINT department_mgrssn_fk
FOREIGN KEY(mgrssn) REFERENCES
employee(ssn)
);

92
DROP TABLE

DROP TABLE tbl_name [RESTRICT | CASCADE]


e.g. DROP TABLE employee;

• Removes named table and all rows within it.

• With RESTRICT, if any other objects depend for their existence on


continued existence of this table, SQL does not allow request.

• With CASCADE, SQL drops all dependent objects (and


objects dependent on these objects).

93
ALTER TABLE
• The ALTER command is a schema modification command.
• It is used to add or drop a column, change a column definition, add or drop
table constraints.
Examples:
ALTER TABLE COMPANY.EMPLOYEE
MODIFY(lname VARCHAR2(30));

ALTER TABLE EMP


ADD Constraints pk_emp
primary key (EMPNO);

ALTER TABLE EMP


ADD CONSTRAINTS FK_DEPTNO FOREIGN KEY (DEPTNO)
REFERENCES DEPT(DEPTNO); 94
SQL Data Manipulation Statements
(DML)
• INSERT Statement +
• UPDATE Statement +
• DELETE Statement +

• Note: Use following control commands for above


SQL
• Commit for DO or confirm
• Rollback for UNDO
95
INSERT Statement
• Definition of INSERT Statement +
• Types of INSERT Statement +
• INSERT and Integrity Constraints +

96
Definition of INSERT Statement
• INSERT is used to add a single row to a
table where we specify the relation name
and a list of values for the row.

• There are three types of INSERT


Statement:
– INSERT With Column list +
– INSERT Without Column list +
– INSERT with SELECT Statement +
97
INSERT with Column list
INSERT INTO table_name (column_list) VALUES
(data_value_list);

• Example: INSERT INTO employee(fname, lname, ssn,


salary, dno)
VALUES (‘Majid', ‘Al-Ghamdi', ‘1111111', 4000,
123);

• data_value_list must match column_list as follows:


– Number of items in each list must be the same.
– Must be direct correspondence in position of items in two lists.
– Data type of each item in data_value_list must be compatible with
data type of corresponding column.
– If one of the table columns is omitted from the column_list It must
also be omitted from the data_value_list and make sure it is
nullable.
98
INSERT without Column List
INSERT INTO table_name VALUES (data_value_list);
• Example: INSERT INTO employee
VALUES (‘Adel', NULL, ‘Al-Eid', ‘222222’,
NULL, NULL, NULL, NULL, NULL, 1);

• data_value_list must match the


columns of the table as follows:
– Number of items in the list must be equal to the
number of columns of the table.
– Datatype of corresponding items must
be compatible.
99
INSERT … SELECT

 Second form of INSERT allows multiple rows to be copied from one or more
tables to another:

 INSERT INTO table_name [ (column_list) ] SELECT ...

Example:

 INSERT INTO Table1 (A1, A2, A3) SELECT B1, B2,


B3 FROM Table2;

10
0
INSERT and Integrity
Constraints
• A DBMS that fully implement SQL2 should
support and enforce all the integrity constraints
that can be specified in the DDL.

• A DBMS enforcing NOT NULL will reject an


INSERT command in which an attribute
declared to be NOT NULL does not have a
value.

• A DBMS not supporting referential integrity will


allow insertion even if the referential integrity
constraint is violated. 101
UPDATE
• Definition +
• Examples
– Update All Rows +
– Update Specific Rows +
– Update Multiple Columns +

102
UPDATE Definition …
• The UPDATE command is used to modify attribute values of one or
more selected rows.

UPDATE table_name
SET column_name1 = data_value1
[, column_name2 = data_value2...]
[WHERE search_condition]

• table_name can be name of a base table


or an updatable view.

• SET clause specifies names of one or more columns that are to be


updated.

103
UPDATE Definition …

• WHERE clause is optional:


– If omitted, named columns are updated for all
rows in table.
– If specified, only those rows that
satisfy
search_condition are updated.

• New data_value(s) must be


compatible with data type for corresponding104
column.
Example: UPDATE All Rows

Give all employees a 3% pay increase.

UPDATE staff
SET salary = salary*1.03;

105
Example: UPDATE Specific
Rows
• Give all Employees in Department one a 5%
pay increase.

UPDATE employee
SET salary = salary*1.05
WHERE dno = 1;

• WHERE clause finds rows that contain data


for dno = 1. Update is applied only to these
particular rows.
106
Example: UPDATE Multiple
Columns
• Change Adel’s department to 2 and his Salary
to 4,000. Assume Adel’s ssn = 111;

UPDATE employee
SET dno = 2
, salary = 4000
WHERE ssn = ‘111’;

107
DELETE
• DELETE Definition +
• DELETE Example +

108
DELETE Definition
• A DELETE command removes rows from a table and may include a
where-clause.

• Rows are explicitly deleted from only one table at a time. However, the
deletion may propagate to rows in other tables if referential triggered
actions are specified in the referential integrity constraints of the DDL.

DELETE FROM table_name [WHERE search_condition]


• table_name can be name of a base table or an updatable view.

• The WHERE clause is optional; if omitted, all rows are deleted from table.
But if it is included only those rows that satisfy the search_condition are
deleted.

109
Example: DELETE

• Delete all records from employee.


DELETE FROM employee;

• Delete all employees in department 1.


DELETE FROM employee
WHERE dno = 1;

110
PL/SQL Procedures

 PL/SQL is a block-structured language that enables developers to combine the


power of SQL with procedural statements.
 A stored procedure in PL/SQL is nothing but a series of declarative SQL
statements which can be stored in the database catalogue. A procedure can be
thought of as a function or a method. They can be invoked through triggers, other
procedures, or applications on Java, PHP etc.
 All the statements of a block are passed to Oracle engine all at once which
increases processing speed and decreases the traffic.
Example

 SET ANSI_NULLS ON
 GO
 SET QUOTED_IDENTIFIER ON
 GO
 CREATE PROCEDURE GetStudentDetails
 @StudentID int = 0
 AS
 BEGIN
 SET NOCOUNT ON;
 SELECT FirstName, LastName, BirthDate, City, Country
 FROM Students WHERE StudentID=@StudentID
 END
 GO
PL/SQL Triggers

 Triggers are stored programs, which are automatically executed or fired when
some events occur. Triggers are, in fact, written to be executed in response to any
of the following events −

 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)

 A database definition (DDL) statement (CREATE, ALTER, or DROP).

 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or


SHUTDOWN).
Advantages

 Generating some derived column values automatically


 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions
Creating Triggers

• CREATE [OR REPLACE ] TRIGGER trigger_name


• {BEFORE | AFTER | INSTEAD OF }
• {INSERT [OR] | UPDATE [OR] | DELETE}
• [OF col_name]
• ON table_name
• [REFERENCING OLD AS o NEW AS n]
• [FOR EACH ROW]
• WHEN (condition)
• DECLARE
• Declaration-statements
• BEGIN
• Executable-statements
• EXCEPTION
• Exception-handling-statements
• END;
Difference between Procedures and
Triggers
Key Triggers Stored procedures
Basic trigger is a stored procedure Stored procedures are a pieces
that runs automatically when of the code in written in
various events happen (eg PL/SQL to do some specific
update, insert, delete) task

Running Methodology It can execute automatically It can be invoked explicitly by


based on the events the user

Parameter It can not take input as It can take input as a


parameter parameter
Transaction statements we can't use transaction We can use transaction
statements inside a trigger statements like begin
transaction, commit
transaction, and rollback inside
a stored procedure
Normal Forms in DBMS

 Normalization is the process of minimizing redundancy from a relation or set of


relations. Redundancy in relation may cause insertion, deletion, and update
anomalies. So, it helps to minimize the redundancy in relations. Normal forms are
used to eliminate or reduce redundancy in database tables.
First Normal Form –

 In this Normal Form, we tackle the problem of atomicity. Here


atomicity means values in the table should not be further divided. In
simple terms, a single cell cannot hold multiple values. If a table
contains a composite or multi-valued attribute, it violates the First
Normal Form.
Example-
In the above table, we can clearly see
that the Phone Number column has
two values. Thus it violated the 1st
NF. Now if we apply the 1st NF to
the above table we get the below
table as the result.
By this, we have achieved atomicity
and also each and every column have
unique values.
2nd Normal Form

 The first condition in the 2nd NF is that the table has to be in 1st NF. The table
also should not contain partial dependency. Here partial dependency means the
proper subset of candidate key determines a non-prime attribute. To understand in
a better way lets look at the below example.
 This table has a composite primary key Emplyoee ID, Department ID.
The non-key attribute is Office Location. In this case, Office Location
only depends on Department ID, which is only part of the primary key.
Therefore, this table does not satisfy the second Normal Form.
 To bring this table to Second Normal Form, we need to break the table
into two parts. Which will give us the below tables:
 As you can see we have removed the partial functional dependency
that we initially had. Now, in the table, the column Office Location is
fully dependent on the primary key of that table, which is Department
ID.
 Now that we have learnt 1st and 2nd normal forms lets head to the
next part of this Normalization in SQL article.
3rd Normal Form (3NF)

 The same rule applies as before i.e, the table has to be in 2NF before proceeding
to 3NF. The other condition is there should be no transitive dependency for non-
prime attributes. That means non-prime attributes (which doesn’t form a candidate
key) should not be dependent on other non-prime attributes in a given table. So a
transitive dependency is a functional dependency in which X → Z (X determines
Z) indirectly, by virtue of X → Y and Y → Z (where it is not the case that Y → X)
In the above table, Student ID
determines Subject ID, and
Subject ID determines Subject.
Therefore, Student ID determines
Subject via Subject ID. This
implies that we have a transitive
functional dependency, and this
structure does not satisfy the third
normal form.
Boyce Codd Normal Form (BCNF)

 This is also known as 3.5 NF. Its the higher version 3NF and was developed by
Raymond F. Boyce and Edgar F. Codd to address certain types of anomalies
which were not dealt with 3NF.

 Before proceeding to BCNF the table has to satisfy 3rd Normal Form.

 In BCNF if every functional dependency A → B, then A has to be the Super Key


of that particular table.
 One student can enrol for multiple subjects.
 There can be multiple professors teaching one subject
 And, For each subject, a professor is assigned to the student
 In this table, all the normal forms are satisfied except BCNF.
Why?
 As you can see Student ID, and Subject form the primary key,
which means the Subject column is a prime attribute. But, there
is one more dependency, Professor → Subject.
 And while Subject is a prime attribute, Professor is a non-prime
attribute, which is not allowed by BCNF.
 Now in order to satisfy the BCNF, we will be dividing the table
into two parts. One table will hold Student ID which already
exists and newly created column Professor ID.
XML documents

 XML Database is used to store huge amount of information in the XML format.
As the use of XML is increasing in every field, it is required to have a secured
place to store the XML documents. The data stored in the database can be queried
using XQuery, serialized, and exported into a desired format.
XML Database Types

 There are two major types of XML databases −

 XML- enabled
 Native XML (NXD)
XML - Enabled Database

 XML enabled database is nothing but the extension provided for the conversion of
XML document. This is a relational database, where data is stored in tables
consisting of rows and columns. The tables contain set of records, which in turn
consist of fields.
Native XML Database

 Native XML database is based on the container rather than table format. It can
store large amount of XML document and data. Native XML database is queried
by the XPath-expressions.

 Native XML database has an advantage over the XML-enabled database. It is


highly capable to store, query and maintain the XML document than XML-
enabled database.
Example

 <?xml version = "1.0"?>


 <contact-info>
 <contact1>
 <name>Tanmay Patil</name>
 <company>TutorialsPoint</company>
 <phone>(011) 123-4567</phone>
 </contact1>
 <contact2>
 <name>Manisha Patil</name>
 <company>TutorialsPoint</company>
 <phone>(011) 789-4567</phone>
 </contact2>
 </contact-info>
Query Processing in DBMS

 Query Processing is the activity performed in extracting data from the database. In
query processing, it takes various steps for fetching the data from the database.
The steps involved are:

 Parsing and translation


 Optimization
 Evaluation
Parsing and Translation

 As query processing includes certain activities for data retrieval. Initially, the given user
queries get translated in high-level database languages such as SQL. It gets translated
into expressions that can be further used at the physical level of the file system. After
this, the actual evaluation of the queries and a variety of query -optimizing
transformations and takes place. Thus before processing a query, a computer system
needs to translate the query into a human-readable and understandable language.
Consequently, SQL or Structured Query Language is the best suitable choice for humans.
But, it is not perfectly suitable for the internal representation of the query to the system.
Relational algebra is well suited for the internal representation of a query. The translation
process in query processing is similar to the parser of a query. When a user executes any
query, for generating the internal form of the query, the parser in the system checks the
syntax of the query, verifies the name of the relation in the database, the tuple, and finally
the required attribute value. The parser creates a tree of the query, known as 'parse-tree.'
Further, translate it into the form of relational algebra. With this, it evenly replaces all the
use of the views when used in the query.
Steps in Query Processing
 Suppose a user executes a query. As we have learned that there are various methods of extracting
the data from the database. In SQL, a user wants to fetch the records of the employees whose
salary is greater than or equal to 10000. For doing this, the following query is undertaken:

 select emp_name from Employee where salary>10000;

 Thus, to make the system understand the user query, it needs to be translated in the form of
relational algebra. We can bring this query in the relational algebra form as:

 σsalary>10000 (πsalary (Employee))


 πsalary (σsalary>10000 (Employee))
 After translating the given query, we can execute each relational algebra operation by using
different algorithms. So, in this way, a query processing begins its working.
Evaluation

 In order to fully evaluate a query, the system needs to construct a query evaluation
plan.
 The annotations in the evaluation plan may refer to the algorithms to be used for the
particular index or the specific operations.
 Such relational algebra with annotations is referred to as Evaluation Primitives. The
evaluation primitives carry the instructions needed for the evaluation of the operation.
 Thus, a query evaluation plan defines a sequence of primitive operations used for
evaluating a query. The query evaluation plan is also referred to as the query
execution plan.
 A query execution engine is responsible for generating the output of the given query.
It takes the query execution plan, executes it, and finally makes the output for the user
query.
Query Optimization

 The cost of the query evaluation can vary for different types of queries. Although
the system is responsible for constructing the evaluation plan, the user does need
not to write their query efficiently.
 Usually, a database system generates an efficient query evaluation plan, which
minimizes its cost. This type of task performed by the database system and is
known as Query Optimization.
 For optimizing a query, the query optimizer should have an estimated cost
analysis of each operation. It is because the overall operation cost depends on the
memory allocations to several operations, execution costs, and so on.
Object Oriented Database
 An object-oriented database (OOD) is a database system that can work with complex data
objects — that is, objects that mirror those used in object-oriented programming languages. In
object-oriented programming (OOP), everything is an object.
 The idea of object databases was originated in 1985 and today has become common for various
common OOP languages, such as C++, Java, C#, Smalltalk, and LISP. Common examples are
Smalltalk is used in GemStone, LISP is used in Gbase, and COP is used in Vbase
 Object databases are commonly used in applications that require high performance,
calculations, and faster results. Some of the common applications that use object databases are
real-time systems, architectural & engineering for 3D modeling, telecommunications, and
scientific products, molecular science, and astronomy.
 Db4o
 Cache
 Concept DB
Building blocks of an object-oriented database

 Objects are a real world entities, such as a specific task in a to-do list: “take the garbage out”.
All objects are assigned a class within data structures for both hierarchy and functional
purposes. So, when you hear the phrase "instances of a class," this is simply a reference to
objects created from particular classes.
 Attributes and Methods: An object has state and behaviors. Objects also have properties
(attributes) like name, status, and createdate. The set of properties, taken together, represents
its state. Objects also have behaviors (known as methods, actions, or functions) that modify
or operate on its properties. Examples include updatetask() or gettaskhistory(). Methods are
also the primary path of object-to-object communication.
 Classes are a grouping of all objects with the same properties and behaviors. In our example
above, we talked about task objects. These objects together all belong to the Task class.
 Pointers are addresses that facilitate both object access and establishing relationships between
objects.
distributed database
 A distributed database is a database that consists of two or more files located in
different sites either on the same network or on entirely different networks.
Portions of the database are stored in multiple physical locations and processing is
distributed among multiple database nodes.
 https://www.geeksforgeeks.org/distributed-database-system/
Features of distributed databases

 Location independent
 Distributed query processing
 Distributed transaction management
 Hardware independent
 Operating system independent
 Network independent
 Transaction transparency
 DBMS independent
Database security

 https://www.sumologic.com/blog/what-is-database-security/
Database access control

 Database access control is a method of allowing access to company’s sensitive data only
to those people (database users) who are allowed to access such data and to restrict
access to unauthorized persons. It includes two main components: authentication and
authorization.

 Authentication is a method of verifying the identity of a person who is accessing your


database. Note that authentication isn’t enough to protect data. An additional layer of
security is required, authorization, which determines whether a user should be allowed
to access the data or make the transaction he’s attempting. Without authentication and
authorization, there is no data security.

 Any company whose employees connect to the Internet, thus, every company today,
needs some level of access control implemented.
Types of Access Control

Discretionary Access Control (DAC): With DAC models, the data owner allows
access. DAC is a means of assigning access rights based on user-specified rules.
Mandatory Access Control (MAC): MAC was developed using a nondiscretionary
model, in which people are granted access based on an information clearance. MAC is a
policy in which access rights are assigned based on central authority regulations.
Role Based Access Control (RBAC): RBAC grants access based on a user’s role and
implements key security principles such as “least privilege” and “separation of
privilege.” Thus, someone attempting to access information can only access data
necessary for their role.
Attribute Based Access Control (ABAC) :In ABAC, each resource and user are
assigned a series of attributes. In this dynamic method, a comparative assessment of the
user’s attributes, including time of day, position and location, are used to make a
decision on access to a resource.
How it works

 Two-Factor Authentication: DataSunrise includes two-factor authentication mechanisms based on


emails and one-time passwords (OTP) which allow to access the target database. Database users
should input database’s password and complete email-based or Google Authenticator based
authentication to get access to the target database.
 Database Access Restriction: DataSunrise features Data Security component which enables you to
restrict access to a complete database or certain database objects depending on the following
factors:
 Database username;
 Client application;
 Application username;
 IP address or hostname;
 Operating system user;
 Number of unsuccessful login attempts;
 Query text.
Indexing in DB

 https://www.tutorialspoint.com/dbms/dbms_indexing.htm#:~:text=DBMS%20in
%20Simple%20Steps&text=We%20know%20that%20data%20is,the%20indexing
%20has%20been%20done
.
 Dense index
 Sparse index
 Multilevel index
 B+ tree index

You might also like