Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

RDMS 31 dec

29 December 2022 21:54

Data is information/facts recorded in electronic way / digital way.


Database : collection of interrelated data
Dbms is software from which you can access data and modify the data
Ex: oracle and sql

Information system : its collection of hardware software policies and access to


information
When we information are stored in flat files which can be controlled by os
Then application programs used to access the files

Advantage of file sys : we need physical files but to store everything on computers
but it is not necessary that all data should be on the same computer.

- Data is stored in centralized manner i.e. anyone can access..


- Simple relation btw complex data
- Integrating handling
- Backup and recovery

rdms Page 1
- Backup and recovery
Advantage :
1. Security [role based security]
2. Sharing of data
3. Avoid redundancy
4. Maintenance of integrity
5. Data independence

Database user :

Application developers :
who writes application to interact with database. Application program written in
Kobalt, java, c++, etc.

Sophisticated Users :They are those users who interact with the system without
writing the program instead they form their request in database query language.
They are the SQL programmers, who are going to deal directly with the database.
They write queries to delete or select or insert and update the database.

End users : are basically those people whose jobs require access to the database for
querying, updating, and generating reports. The database primarily exists for their
use

Database Administrator (DBA): is an individual or person responsible for controlling,


maintaining, coordinating, and operating a database management system.
Managing, securing, and taking care of the database systems is a prime
responsibility. They are responsible and in charge of authorizing access to the
database, coordinating, capacity, planning, installation, and monitoring uses, and
acquiring and gathering software and hardware resources as and when needed.
Their role also varies from configuration, database design, migration, security,
troubleshooting, backup, and data recovery.

Data model :

It is model to explain the layout of data and their relationship


Model gives us an idea of how the final system would look after it has been fully
implemented. It specifies the data items as well as the relationships between them.
In a database management system, data models are often used to show how data is
connected, stored, accessed, and changed. We portray the information using a set of
symbols and language so that members of an organisation may understand and
comprehend it and then communicate.

1. Hierarchical data model :

rdms Page 2
This concept uses a hierarchical tree structure to organise the data. The
hierarchy begins at the root, which contains root data, and then grows into a
tree as child nodes are added to the parent node.
One to many relationship , parent child relationship.

Problems :
• Relationships that are complex are not supported.
• Because it only supports one parent per child node, if we have a complex
relationship in which a child node needs to have two parents, we won’t be
able to describe it using this model.
• When a parent node is removed, the child node is removed as well.

2. Network model :
The main difference between this model and the hierarchical model is that any
record can have several parents in the network model. It uses a graph instead
of a hierarchical tree.

Many to many relationship.


• In comparison to the hierarchical model, data can be retrieved faster. This
is because the data in the network model is more related, and there may be
more than one path to a given node. As a result, the data can be accessed
in a variety of ways.
• Data integrity is present since there is a parent-child relationship. Any
changes to the parent record are mirrored in the child record.'
• Problems:
• As the number of relationships to be managed grows, the system may
get increasingly complicated. To operate with the model, a user must
have a thorough understanding of it.
• Any alteration, such as an update, deletion, or insertion, is extremely
difficult.
• Designing will be perfect.
3. Relational data model :

rdms Page 3
Relational Model
The data in this model is kept in the form of a table that is two-
dimensional. All of the data is kept in the form of rows and columns.
Tables are the foundation of a relational.
Popular Relational Database Management Systems:
• IBM – DB2 and Informix Dynamic Server
• Oracle – Oracle and RDB
• Microsoft – SQL Server and Access
• Sybase
Keys : normal attribute / variable . It uniquely identify two or more tuples [rows of
table]. This key values will be unique for each entity. Can be treated as candidate
key [ unique]
- primary key : [ unique + not null]
The PRIMARY KEY constraint uniquely identifies each record in a
table.
Primary keys must contain UNIQUE values, and cannot contain
NULL values.
A table can have only ONE primary key; and in the table, this
primary key can consist of single or multiple columns (fields).
[ composite ]

- foreign key : it's an attribute or set of attributes which take references to


primary key of same table or another table.
- In data base value should be same fk maintain referential integrity
- Super key : adding any key with candidate key is sk [candidate key is
minimal ]

rdms Page 4
Relation = table
Cardinality = no of rows in table
Tuple = row of table/ entity
Attributes = columns in table / characteristics of entity
Degree = no of column / attributes
Domain = range of attribute

Properties of relation :
a. No duplicate rows
b. Tuples are unordered.
c. Attributes are unordered
d. Attributes values are atomic [
An atomic attribute is always represented by a single value,
something which cannot divided further] name can't be atomic
value because
It has first name and last name. age can be atomic value.

rdms Page 5
Sql is command like language.

rdms Page 6
A data definition language (DDL) is a computer language used to create and
modify the structure of database objects in a database.

Post quiz 1 : oracle , mysql , sybase are relational db and unify is not.
Prequiz 1 :

Sql : structural query language. Which is used to insert modify data in db


internally rdms is used.
Ddl : data definition language , which is used to create , alter , rename , drop table.
DDL ===> Defines the structure of database objects.
4 statements of ddl commands in sql
a. CREATE : create a new db obj
b. ALTER : modify existing db ob.
c. TRUNCATE : removes all data from db object.
d. DROP : removes db obj from database.

Data type : type of value stored in attributes/ variable.


Numeric data Type :
- Int for integer
- Smallint int
- Tiny int [ only positive values]
- Bit [ 0/1]

Char data types :

rdms Page 7
Char data types :
Char(n) : static memory allocation, size is fixed
Varchar2(n) : dynamic memory allocation, size can expand and sink depend on
data value.
Number(p): stores number of size p;
Number (p,s) : precision , scale == number and floating point
Date : DD-MON-YY. Stores date.

Only letters, underscore , number are valid, name should start with letter

Unique key can be multiple but it can only have a null value.
If you define a CHECK constraint on a column it will allow only certain values
for this column
Foreign key is used to enforce the link between the tables. The referenced
table is called the parent table while the table with the foreign key is called
the child table.

rdms Page 8
rdms Page 9
Truncate :
Removes all rows from table / data is only removed here
Cannot be done if table is linked with another table.
Syntax :
TRUNCATE TABLE TableName;
Ex : TRUNCATE TABLE Customer;
DROP :
○ Removes whole table structure from db.

Create a table in sql :

Desc tablename ----> discribe the existing table.

Alter: modifies the existing table.

Add columns :
ALTER TABLE tablename ADD columnname datatype

Remove column :
ALTER TABLE Tablename DROP COLUMN columnName

Modify data type :


ALTER TABLE TableName MODIFY columnName NewDatatype(size).

Modify data type size:


ALTER TABLE TableName MODIFY columnName NEWDatatype(size).

Add constraints:

Remove constraints :

rdms Page 10
Rename columns/table:
For column :
ALTER TABLE TableName RENAME COLUMN oldcolumnName TO newColumnname
For table :
ALTER TABLE TableName RENAME TO NewTableName;

Constraints : restriction/conditions on columns/attributes


1. Unique : no duplicate
2. Notnull : should not be leave empty
3. Primary key = unique + not null;
4. Check (columnname condition);
5. Foreign key.
6. Default : default value.

DATA MANIPULATION LANGUAGE :


Manipulation of data.
Insert
Update
Delete
Select.

Insert rows:
INSERT INTO TableName(col1,col2..coln) VALUES(val1,val2..valn)
Varchar , char and date values should be within single quote

Insert into tablename values(val1,val2….valn);


Update row :
UPDATE tablename SET col1 = val1, col2 = val2… coln = valn [where condtion];
UPDATE table_name
SET column_name1= value1, column_name2= value2
WHERE condition;

Where is the condition if we wont use all the value of that col will be update

DELETE ROW :
DELETE FROM TABLENAME [WHERE CONDITION]

rdms Page 11
Delete from tablename == delete every row from table.

Cascade : if delete row from parent table , child table will be deleted
Set null : if row from parent is deleted then then child table row is set with null.
Restrict : rejects the delete or update operation for parent table. This is default.

SYNTAX:
REFRENCES TABLENAME (COL_NAME)[ON DELETE REF_OPT]
Ref_opt : restrict | cascade | set null

SELECT *[COLMMN NAME] FROM TABLENAME [WHERE COND , OPR COND.]

Merge :

rdms Page 12
When we want to update , insert delete in same time we can do this with merge
It needs target table and source table

Data transaction : performing set of operation to do any tasks / work


Read = reading the data from data base.
Write = writing the data from db
commit is used to save dml statements in db.
Rollback : undo
Transaction should satisfy acid property :
ACID =
ATOMICITY : EITHER ALL OR NULL
CONSISTENCY: before start end the sum should be same.
ISOLATION: changing the parallel execution of task to serial , serial is always
consistence.
DURABILITY: change are made forever until updating happen.

Select statement :
Its used to retrieve data from one or more table.
The retrieved result Is stored in a temporary result table called result set
It can be helpful In retrieving :
- All rows from table
- Specific rows
- Specific values

rdms Page 13
- Specific values
Select * from tablename ; it will everything from table.
Select c1name,c2name from tablename;

We can use arithmetic operations in select :

- Select C1name|| 'string' || c2name


Its used concate string with rows values.
DISTINCT IN SELECT :
It is used to remove duplicate rows

rdms Page 14
In operator be used with any data type.

Values can't be compared with null

SELECT column1, column2, ...


FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

rdms Page 15
Asc is default but if we want to desc for another asc for another table we need to
mention

Unique in select statement in select;

=====================================================================

Function :
A block of code that sometimes take argument and always return a value.

Single- row : also called scalar func. , operates on single row only return a
result.

rdms Page 16
Character function .

Conact (string,string);

Substr(string , -3) == last 3 char

rdms Page 17
SELECT CEILING(25.00) AS CeilValue;
Return the smallest integer value that is greater than or equal to a number:
From <https://www.w3schools.com/sql/func_sqlserver_ceiling.asp>
Return the largest integer value that is equal to or less than
25.75: 26

SELECT FLOOR(25.75) AS FloorValue;From


<https://www.w3schools.com/sql/func_sqlserver_floor.asp> 25

Round value :

Round the number to 2 decimal places:

SELECT ROUND(235.415, 2) AS RoundValue;

If number >=5 round

From <https://www.w3schools.com/sql/func_sqlserver_round.asp>

In trunc() we don't check the next ele

Select trunc(35.6782,2) == 35.67

Selectc trunc(35.6782,3) == 35.678

-1 10th place make zero and check the 10-1th place to round it

Arithmetic opr can be done with dates also


A number can be added to date
Or a no can be subtracted from a date

rdms Page 18
Or a no can be subtracted from a date
These opr can also done between two dates

Answers:
1. 11/20/2018 it will only round after 13 hours completed .
2. 11/20/2018
3. 12/01/2018 as in sysdate 20 dec half of month completed
4. 12/01/2018 as in sysdate 20 dec half of month completed
5. 12/01/2018 as in sysdate 20 dec half of month completed
6. 11/01/2018 as '11/15/2018' as round will done only after 16.

1. 11/01/2018 as '11/15/2018' as round will done only after 16.


2. 12/01/2018 as '11/6/2018' as round will done only after 16.
3. 01/01/2019 as '11/15/2018' is half month completed
4. 01/01/2018 as 06/15/2018 as round will happen after 7 / july.
5. 01/01/2019 as 07/15/2018 as round will happen after 7 / july.
6. Days will check the start date of week if its smaller than first day will
Be the result else next week day.

Conversion function ();


To string to date = TO_DATE('DATE_IN_STRING','DDMMYYY');

rdms Page 19
TO_DATE : CONVERTS STRING TO DATE.
SYNATX : TO_date(DATE_IN_STRING', FROMAT);

TO_NUMBER : CONVERTS STRING TO NO.


SYNTAX : TO_NUMBER("NUMBER IN STRING , "FORMAT");
SELECT TO_NUMBER('1233.5',9999.99)FROM DUAL;

TO_CHAR(NUMBER/DATE TO STRING)
SYNTAX : TO_CHAR(NUMBER OR DATE , FORMAT);

rdms Page 20
If else case

Case clause :
Multiple condition :

rdms Page 21
rdms Page 22
If we remove default / else value then null value will be return

NVL function : work with null

Its used to tackle null values :


Nvl (exp1 , exp2) : if exp1 is not null then exp1 will return else exp2;
Nvl2(exp1,exp2,exp3) : if exp1 is null then exp3 will return else exp2 will
return;
Ifnull(exp, value) = if exp is null thrn it will return value
Coalesce(exp1,exp2,exp3…..expn) : it will return first not null exp;

Multi row :aggregate , operates on multiple row and return a result for multi
rows:

rdms Page 23
It takes n no of i/p and returns single op.

Group function ignores null values;

Sum : select sum(rows) [as result] from tablename;


Max :
Min :
Avg :
The AVG() function returns the average value of a numeric column.

Count :
The COUNT() function returns the number of rows that matches a specified
Criterion
Count(*) count all rows;

rdms Page 24
Grouping identical data in groups , it is used with select

Note : select onlyexpg or aggegate function from tablename group by


onlyexpg;

Where ------group by --------------order by .

If we use group by then it select we have to use that same attribute.

Where clause is used for all rows in table but not in group by then we use
'having

rdms Page 25
Group by is used without distinct works as distinct
But group shows the result in order wise
================================================================

Join & sub- queries :


To get data from two or more table we use join
There must be at least common attribute in two table.
Join = Cross product + someCondition

Types :

Natural join : select att from t1 natural join t2;


[Select attribute from t1,t2 where t1.ca = t2.ea;]
T1,t2 is cross product == first ele of t1 multiply with all rows of t2

If t1 has m rows n t2 has n


Total rows in cross product will be MxN

rdms Page 26
Self -join : table joins with itself ,

We make alias for table and then use it.

Equi join : also called inner join


Note : In natural join we can equal only common attribute but in equi join we
can Eqaul any attributes from t1,t2;

rdms Page 27
Natural joins return mactching values from t1,t2
Note : in equi join returns rows only when there
Is at least one row from both the table matches the
Join condition

Outer join : natural join + right/left table.

Left outer:

Right join : gives priority to right table ;

rdms Page 28
Using clause : as in natural join if attr from t1,t2 matches then join happens,
In using clause if two or more att matches from t1 and t2 then we can decide
Join , It provides more flexiblity

rdms Page 29
rdms Page 30
In natural join we used to write only common attribute.
And by using clause also we write common clause but
By using ON we can use conditions also and equality

Multiple join :

rdms Page 31
Sub query :

Subquey is also called as inner query or inner select and outer is called outer
query and outer select

rdms Page 32
Subquery : inner query should be enclosed by ()
We can't use order by in inner query but we can use group by.

We use = , < , <= , >= <> when inner queries return single value.

For multi rows we use :


In : matches the row and return
Any : its used to compare

rdms Page 33
It will bring salary of emp greater than 1600 ======= greater than > all

rdms Page 34
rdms Page 35
\

Everytime outer queery runs inner inner query also runs


Inner query take values from outer query

rdms Page 36
Inner query take values from outer query
=====================================================================
DCL command :
Its used to allow users to access and manipulate data base.

Object can be table , view , index, synonyms


Object privilege vary from obj to obj
Owner can give access to their objs.

Two main command dcl


GRANT to grant a privilege to user :
Grant cmd can be used in combination of select , update , insert , delete ,
alter. Grant can be removed using revoke cmd.
the public is used to permit access to all the users.

From <https://www.geeksforgeeks.org/difference-between-grant-and-revoke/>

Revoke to remove a privilege from user

View :
This object is used in the database to create a type of view of the database. It
is a logical view based on one or more tables or even another view. A view
does not contain any data of its own but is used to view data in other tables.
The view is based on a table, and that table is known as the base table. The
data dictionary stores the view as a SELECT statement

When we want to execute some function and create some functions we


Like we make macros in programming to copy paste the code every time we
Get the complex query , like that SQL provides feature called view where we
can store query in database whenever we need we call the view and it do the
Operation internally view doesn’t contain any value. Virtual table .

Create view customtable as


Select att1,att2. from [select…]

rdms Page 37
Select att1,att2. from [select…]

1. Query is allowed. Ex : select * from {view} custumTable.


2. Update view def [create or replace].
3. Update is restrict [ when view is created based on multiple table/complex
view]
4. If base the table is deleted then view will not be deleted but if we use it for
another table it might throw an error.

Removing view :
Syntax --- Drop view view_name;

Views advantage :
Security
Simple
Abstraction

Top n analysis:

rdms Page 38
Top n analysis:
Top-N queries ask for the n smallest or largest values of a column. Both
smallest and largest values sets are considered Top-N queries. Following this
type of searching technique could save lot of time and complexities. Top-N
analysis are useful in cases where the need is to display only the n bottom-
most or the n top-
most records from a table based on a condition. This result set can be used
for further analysis.

From <https://www.geeksforgeeks.org/sql-top-n-queries/>

Sequence :

It generates unique number automatically.


It is shared obj : it can be used for other tables as well
It is used for primary key and unique keys

By default cache is 20

=---------------------------
CREATE SEQUENCE sequence_name
START WITH initial_value

rdms Page 39
START WITH initial_value
INCREMENT BY increment_value
MINVALUE minimum value
MAXVALUE maximum value
CYCLE|NOCYCLE ;
sequence_name: Name of the sequence.
initial_value: starting value from where the sequence
starts.
Initial_value should be greater than or equal
to minimum value and less than equal to maximum
value.
increment_value: Value by which sequence will
increment itself.
Increment_value can be positive or negative.
minimum_value: Minimum value of the sequence.
maximum_value: Maximum value of the sequence.
cycle: When sequence reaches its set_limit
it starts from beginning.
nocycle: An exception will be thrown
if sequence exceeds its max_value.

From <https://www.geeksforgeeks.org/sql-sequences/>

rdms Page 40
Synomys:

Drop synoym sysosymname;

Index :

Improves in fast retrieval


Index is not free. i.e take storage.

rdms Page 41
1. Clustered Index :
Clustered index is created only when both the following
conditions satisfy –
5. The data or file, that you are moving into secondary
memory should be in sequential or sorted order.
6. There should be a key value, meaning it can not have
repeated values.

Whenever you apply clustered indexing in a table, it will


perform sorting in that table only. You can create only
one clustered index in a table like primary key. Clustered
index is as same as dictionary where the data is
arranged by alphabetical order.
If you apply primary key to any column, then automatically it will become
clustered index.

From <https://www.geeksforgeeks.org/difference-between-clustered-and-non-clustered-
index/>

From <https://www.geeksforgeeks.org/difference-between-clustered-and-non-clustered-
index/>

rdms Page 42

You might also like