0% found this document useful (0 votes)
59 views53 pages

Day Wise Notes-1

Uploaded by

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

Day Wise Notes-1

Uploaded by

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

Introduction to databases

What is Data?
Collection of Raw material/facts/information/entities/attributes/values

Types Of Data
Structured data in structure manner/primitive/
Unstructured data format is not limitations
images-soundfiles-video-files-m

Partial Unstructued JSON, CSV

Database collection of data


Papers-books
files

Demerits
Data Management not good for large data sets-ba
Data Redundancy duplicacy
Data Inconsistency scattered data
Data Integrity accurate data in fasten way
Data Atomicity

Types of Databases OLTP/OLAP


Relational
Non-relational
OOPs data
cloud db
distributed
centralized
network db
no sql
hierarchical
personal db
multi module db
opeartional db
graph db
open src db
block chain
commercial db
time series db
data ware house
data lake
new sql

DBMS
Software--->User---->Create+Read+Update+Delete(CRUD)---->Database
Minimal Data Redundancy
Improved Data Consistency
Data Sharing
Enforced standards
Retrival of data is fast

ACID Rules
Atomicity-table is in atomic/ consistent state
Consistency-failure of data is there then all the inconsistent data is removed from db
Isolation-two or more transactions on the db
Durability-effect of the change is made in db

DBMS Architecture
3-levels
Physical Level 1-tier
Conceptual Level 2-tier
Application level 3-tier

Data Modeling
“A data model is a way of finding the tools for both
business and IT professionals, which uses a set of
symbols and text to precisely explain a subset of real
information to improve communication within the
organization and thereby lead to a more flexible and
stable application environment”

A data model is an idea which describes how the data


can be represented and accessed from software system
after its complete implementation

It is a simple abstraction of complex real world data


gathering environment
It defines data elements and relationships among various
data elements for a specified system
The main purpose of data model is to give an idea that
how final system or software will look like after
development is completed

Types of Data Models


Hierarchical DBMS Tree-node-root
Network DBMS Records
Relational DBMS
ER-Model
1:M Dept-Emp
1::1 Person-AadharID
M:1 Dept-College
M:M Emp-Proj

Keys
Super Keys
Primary Key
Unique Key
manner/primitive/rows-columns/rdbms/
ot limitations
ndfiles-video-files-mp3/mp4-

{
emp-id : 101,
emp-
name:'suhas'
} account

r large data sets-banking-social media data-organizational-unversity data

ta in fasten way
emp-id
101
102
removed from db
Airline Reservation Sy
physical storage structure of data in db Entities
entier database conceptually Passengers
View the database Airlines
Prices of Ticket
Flight

Studs---->Course Colleges----->University
Auth<--->Books Prod----->Orders
Emp-id Emp-naEmp-adEmp-dessal
10001

Employee-Student-University-Identity- format row-cou


emp-name salary
Suhas D. 20000
Abhay F. 30000
rline Reservation System

ssengers

ces of Ticket
datatypes
Data Type SQL
1 VARCHAR2(size [BYTE | CHAR]) DDL
1 NVARCHAR2(size) DML
2 NUMBER[(precision [, scale]]) 69.85 TCL
8 LONG 60000
12 DATE
21 BINARY_FLOAT
22 BINARY_DOUBLE
23 RAW(size)
24 LONG RAW
69 ROWID
96 CHAR [(size [BYTE | CHAR])]
96 NCHAR[(size)]
112 CLOB
112 NCLOB
113 BLOB
114 BFILE
180 TIMESTAMP [(fractional_seconds)]
181 TIMESTAMP [(fractional_seconds)] WITH TIME ZONE
182 INTERVAL YEAR [(year_precision)] TO MONTH
183 INTERVAL DAY [(day_precision)] TO SECOND[(fractional_seconds)]
208 UROWID [(size)]
231 TIMESTAMP [(fractional_seconds)] WITH LOCAL TIMEZONE
DDL Create table,Alter table,DROP,
DML Insert data into table
Update data Table DROP Table table name
Delete DROP Column alter table tablename drop column c
Truncate,where Contraints alter table tablename drop constrain
Multi Row Group By and Having clause
Joins and Subqueries
Delete Rollback not undo the structure of the table it is used w

Order By
Group By
avg(sal) Having
min(sal)
max(sal)
le table name delete complete structure of the table along with the data
e tablename drop column columnname
e tablename drop constraint contraintname

ure of the table it is used with to get the undo the data part only.
Constraints
Primary key – Explain the primary key concept and show you how to use the primary key constraint to manage the primary

Foreign key – Introduce you to the foreign key concept and show you use the foreign key constraint to enforce the relations

NOT NULL constraint – Show you how to ensure a column that does not accept null values.

UNIQUE constraint – Discuss how to ensure data stored in a column or a group of columns is unique among rows within a ta

CHECK constraint – Walk you through the process of adding logic for checking data before storing them in tables.
to manage the primary key of a table.

to enforce the relationship between tables.

among rows within a table.

em in tables.
Day-4
Revise-DDL-DML-DCL
Rename-Alias
Difference between Truncate and Delete
Joins and Subqueries
TCL-commit Rollback Savepoint
Task - Case Study

DDL

Joins: Cross Product with a condition statement


Whenever you want to join two tables your at least one attribute should be same

Cross Join or Cartesian Product

R1 R2
A B C C D E
1 2 3 3 4 9
2 1 4 2 1 2
4 5 7
6 4 7

Natural or Inner Join


Department Table
Ename Address DeptNo. Name Eno.
Employee TRam Delhi D1 HR 1
Eno. Varun Mumbai D2 IT 2
1 Ravi Mumbai D3 Marketing 4
2 Amrit Delhi
3
4

find the emp names who are working in a particular department


If you want to join a table with itself
SID
Self Join

Student tabCID Year SID CID Year


C1 2016 S1 C1 2016
SID C2 2017 S2 C2 2017
S1 C3 2017 S3 C3 2017
S2
S3
CID

Here, SID and CID are Composite Primary Keys select Ename Emp,Dept where Emp.eno = Dept.eno and Emp.Add = D

Equi Join Department Table


Ename Add DeptNo. Location Eno.
Employee TRam Delhi D1 Delhi 1
Eno. Varun Mumbai D2 Pune 2
1 Ravi Mumbai D3 Patna 4
2 Amrit Delhi
3
4
it gives us matching values rows and rows which are in the left table

Left Outer Ename DeptNo. DeptNo. Dname Loc


Varun D1 D1 IT Mumbai
Eno. Amrit D2 D2 HR Hyderabad
E1 Ravi D1 D3 Finance Pune
E2 Nitin
E3
E4

Matching values
Right OuterEname DeptNo. DeptNo. Dname Loc
Varun D1 D1 IT Delhi
ENo. Amrit D2 D2 HR Hyderabad
E1 Ravi D3 D3 Finance Pune
E2 D4 Testing Bangalore
E3
Joins : To get the data from both the tables
Cross Join/ Cartesian Product Basic rule of joins is: cartesian produc
Natural/ Inner Join
Conditional Join
Equi
Self Left
Outer Right
Full

Parent-table Child Table


Table-1 Table-2 FK
PK-col1 PK of tbl1--col1
Student Course
Emp Dept
Prod Order

Select * FROM Table1 FULL JOIN Table2 ON Table1.id = Table2.id;

ould be same

R1 x R2
How many columns are there in both the tables? A B C
3+2 5 Columns 1 2 3
3x2 6 Rows 1 2 3
2 1 4
M+N 2 1 4
R1xR2 4 5 7
4 5 7
6 4 7
6 4 7

Select Ename, DeptNo. from Emp,Dept where emp.eno = dept.eno select Ename, DeptNo Emp
Employee Department
Eno. Ename DeptNo. Eno. Eno. Ename
1 Ram D1 1 1 Ram
1 Ram D2 2 2 Varun
1 Ram D3 4 4 Amrit
2 Varun D1 1
2 Varun D2 2
2 Varun D3 4
3 Ravi D1 1
3 Ravi D2 2
3 Ravi D3 4
4 Amrit D1 1
4 Amrit D2 2
4 Amrit D3 4
pt where Emp.eno = Dept.eno and Emp.Add = Dept.Location;

he left table select eno,ename,dname,loc from emp,dept left outer join on (Emp.deptno = dept.deptno)

Eno. Ename Dname Loc


E1 Varun IT Mumbai
E2 Amrit HR Hyderabad
E3 Ravi IT Mumbai
E4 Nitin Null Null
Eno Ename Dname Loc
E1 Varun IT Delhi
E2 Amrit HR Hyderabad
E3 Ravi Finance Pune
Null Null Testing Bangalore
of joins is: cartesian product + a condition

C D E
3 4 9
2 1 2
3 4 9
2 1 2
3 4 9
2 1 2
3 4 9
2 1 2

select Ename, DeptNo Emp INNER JOIN Dept

DeptNo.
D1
D2
D3
o = dept.deptno)
Subquery Query within a query

OuterQuery ( Inner Query)

1) Write a query to display max salary from table


select max(salary) from Emp;
50000

2) Write a query to display name of the employee who has the maximum salalry
select Ename from Emp where Salar(select max(salary) from Emp); Varun
50000
3) Write a query to display second highest salary
select max(salary) from emp where Salary IN (select salary from emp where Salary <> (select max(s

select * from emp where exists (Select * from dept where dept.EID = emp.EID);

Rules that Subqueries must follow:


•A subquery must be enclosed in parentheses.
•A subquery must be placed on the right side of the comparison operator.
•Subqueries cannot manipulate their results internally, therefore ORDER BY clause cannot be ad
•Use single-row operators with single-row subqueries.
•If a subquery (inner query) returns a null value to the outer query, the outer query will not retu

What is a subquery in Oracle?


In Oracle, a subquery is a query within a query. You can create subqueries within your SQL statements.
These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT clause.

WHERE clause
Most often, the subquery will be found in the WHERE clause. These subqueries are also called nested subqueries.

FROM clause
A subquery can also be found in the FROM clause. These are called inline views.

Correlated Subquery :
Correlated Query is nothing but the subquery whose output is depending on the inner query used
Correlated query is the query which is executed after the outer query is executed.
The outer query is always dependent on inner query.
The approach of the correlated subquery is bit different than normal subqueries.
In normal subqueries the inner queries are executed first and then the outer query is executed
But in Correlated Subquery outer query is always dependent on inner query so first outer query is e
Correlated Subqueries always uses operator like Exist,Not
“Correlated Queries are also called as Synchronized queries…”

Select * from Employee E where Not exist


(Select Department_no From Department D where E.Employee_id=D.Employee_ID);

Execution of above query:


Step 1:
Select * from Employee E ;
It will fetch the all employees
Step 2:
The First Record of the Employee second query is executed and output is given to first query.
(Select Department_no From Department D where E.Employee_id=D.Employee_ID);
Step 3:
Step 2 is repeated until and unless all output is been fetched.

Nested Subqueries:
The Subqueries are called as nested subqueries when another subquery is used in where or having condition of the Outer Que
The Execution of Nested suubquery always follows bottom up approach.
Real Life Example:
Select * from Employee
where Employee_No Exist
(Select * from Employee
where Department_Name=
(Select Department_Name from Employee where Department_Name=’OBIEE’));
Execution of Query:
Step 1:
Executed Bottom query:
Select Department_Name from Employee where Department_Name=’OBIEE’;
Step 2:
Executed The Second Query which is above bottom query:
Select * from Employee
where Department_Name=’OBIEE’;
Step 3:
Excecuted the Top Query
Select * from Employee
where Employee_No Exist
(Select * from Employee
where Department_Name=’OBIEE’);

Scalar Sub-queries :
Definition of Scalar Subquery:
A scalar sub-query expression is a sub-query that returns exactly one column value from one row.
What if the oracle failed to return scalar sub-query?There are some specific conditions.
Usages of Scalar Query :
1.The scalar sub-queries are most used for removing the outer joins.
2.If user want to aggregate multiple tables then scalar sub-queries are useful.
3.Table insertion based on other table values.
Real Life Example:
If user want to find out the Department_name and Number_of_Departments using scalar query you can use following express
Select D.Department_name(Select Count(E.Department_name) From Employee E Where E.Department_no=D.De
ary <> (select max(salary) from emp));

lause cannot be added into a subquery. You can use an ORDER BY clause in the main SELECT statement (oute

query will not return any rows when using certain comparison operators in a WHERE clause

nested subqueries.

e inner query used in that query.


ery is executed
first outer query is executed then inner query is executed.Exist,IN,Not IN.

ndition of the Outer Query.


an use following expression :
Department_no=D.Department_no;
ECT statement (outer query) which will be the last clause.
The Basics of Inline View
An inline view is not a real view but a subquery in the FROM clause of a SELECT state
SELECT
column_list
FROM
table;
In the FROM clause, you can specify a table from which you want to query data.

Besides a table, you can use a subquery as shown in the following example:

SELECT
column_list
FROM
(
SELECT
*
FROM
table_name
) t;

The subquery specified in the FROM clause of a query is called an inline view.

Limitations
Oracle allows an unlimited number of subqueries in the FROM clause.
of a SELECT statement.

query data.

ine view.
schemaname.S
Creating Other Schema Objects tudents

Logical
Physical

Username-ORA1
Grant all privileges to ORA1 ORACLE

View
Index Students-View1-
along with courses

Sequences
Synonyms
Students-View2-
along with courses
RollNO Sub
schemaname.S
tudents
RollNO Sub Marks
Admno Course

Username-Priyanka

ORACLE

Products Tables Student


Departmen
ts Courses
Empp RollNo enroll no college na Sub1
Students
10KB
iew1-
courses

2KB
Students-View2-
along with courses Students-View3-
along with marks RollNo Sub1 Sub2 Marks-1 Marks-2
Sub2 Marks-1 Marks-2
What is a VIEW in Oracle?
An Oracle VIEW, in essence, is a virtual table that does not physically exist.
a view is a “virtual” table whose data is the result of a stored query, which is derived each time when you q

A view is a virtual table because you can use it like a table in your SQL queries.
Every view has columns with data types so you can execute a query against views
or manage their contents (with some restrictions) using the INSERT, UPDATE, DELETE, and MERGE stateme
Unlike a table, a view does not store any data.
View only behaves like a table.
And it is just a named query stored in the database.
When you query data from a view, Oracle uses this stored query to retrieve the data from the underlying ta

SELECT * FROM customer

When to use the Oracle view

You can use views in many cases for different purposes. The most common uses of views are as follows:

Simplifying data retrieval. CREATE VIEW salesman AS SELECT * FR


Maintaining logical data independence. The view returns only employees whos
Implementing data security. SELECT * FROM salesman;
To drop the salesman view:
More on Oracle View DROP VIEW salesman;

Creating a view – use the CREATE VIEW statement to create a new view.
Drop a view – use the DROP VIEW statement to drop a view from the database.
Updatable views – discuss how to create updatable views.
Inline views – learn how to use inline views to simplify complex queries and condense several separate q
WITH CHECK OPTION – how to protect the view using the WITH CHECK OPTION clause of the CREATE VIEW
Materialized view – covers the materialized views that help you improve query response times.
ach time when you query against the view.

and MERGE statements.

rom the underlying tables.

ws are as follows:

sman AS SELECT * FROM employees WHERE job_title = 'Sales Representative';


nly employees whose job titles are Sales Representative.

e several separate queries into one query.


of the CREATE VIEW command.
Oracle Index
Oracle index is one of the effective tools for boost the query performance.
To use it effectively, you must understand it correctly. This section helps you understand and use Oracle indexes to
Creating a new index – show you how to use the CREATE INDEX statement to create an index for one or more colu
Removing an index – learn how to remove an existing index by using the DROP INDEX statement.
Unique index – use unique indexes to enforce the uniqueness of values in the index column or columns.
Function-based index – speed up queries that involve expression which consists of functions.
Bitmap index – use bitmap index on a column or columns that have few distinct values, or low cardinality.

An index is a performance-tuning method of allowing faster retrieval of records.


An index creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-tree inde

When you create a new table with a primary key, Oracle automatically creates a new index for the primary key colu
Unlike other database systems, Oracle does not automatically create an index for the foreign key columns.

CREATE INDEX
SQL> CREATE IND
CREATE INDEX ename_index ON Employees(first_name);
Index created.
Removing an index SQL> EXPLAIN PL
To remove an index, you use the DROP INDEX statement: 2 SELECT * FRO
DROP INDEX index_name; 3 WHERE first_na

Explained.
Creating an index on multiple columns example This explains the exe
CREATE INDEX emp_name_indx1 ON employees(last_name,first_name);
SQL> SELECT
2 PLAN_TABL
3 FROM
4 TABLE(DBM

PLAN_TABLE_OU
-------------------------
| 0 | SELECT STAT
00:00:01 |

| 1 | TABLE ACCE
00:00:01 |

|* 2 | INDEX RAN
00:00:01 |
use Oracle indexes to speed up your queries.
ex for one or more columns in a table.

r columns.

w cardinality.

cle creates B-tree indexes.

r the primary key columns.

SQL> CREATE INDEX ename_index ON Employees(first_name);

Index created.

SQL> EXPLAIN PLAN FOR


2 SELECT * FROM Employees
3 WHERE first_name = 'Steven';

Explained.

This explains the execution plan into the plan_table table.

SQL> SELECT
2 PLAN_TABLE_OUTPUT
3 FROM
4 TABLE(DBMS_XPLAN.DISPLAY());

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 69 | 2 (0)|
00:00:01 |

| 1 | TABLE ACCESS BY INDEX ROWID| EMPLOYEES | 1| 69 | 2 (0)|


00:00:01 |

|* 2 | INDEX RANGE SCAN | ENAME_INDEX | 1| | 1 (0)|


00:00:01 |
SEQUENCES : Database Schema /Object
To provide the automated no to fields using squences.
Used for number sequencing
To create a unique numbers which acts as a primary key
For eg : Rollno, Empid, courseid

SYNTAX : CREATE SEQUENCE sequnce_name ALTER SEQUNECE sequence_name INCREMEN


MINVALUE minval
MAXVALUE maxval
START WITH value/num
INCREMENT BY value/num
CYCLE/NOCYCLE
CACHE value;(min cache value is 2) / NOCACHE

DROP: DROP SEQUENCE sequence_name;

CACHE : CACHE mentioned that how many no of sequence values will be stored
and they are stored in memory for faster access.

CYCLE: ITRATION of seuence value


NOCYCLE: NO ITERATIONS of sequnce value
Customer
cid cname add
10 AA BB
uence_name INCREMENT BY newvalue; 20 NN GG
30 DD LL
40
50
10
Synonyms
Oracle synonyms that help you create aliases for schema objects such as tables, views, materialized views, sequenc
Oracle synonyms that help you create aliases for schema objects such as tables, views, materialized views, sequenc
use synonyms when you are granting access to an object from another schema and you don't want the users to hav
Synonyms provide a level of security by hiding the name and owner of a schema object such as a table or a view.
provide
Synonymslocation
createtransparency for remote
a level of abstraction objects
of the of a distributed
underlying database.
schema objects so that you can rename and move of the un

without affecting the applications based on the synonyms.


Synonyms can be public or private.
A public synonym is accessible to every user in a database and owned by a specified group named PUBLIC
A private synonym is stored a specific schema owned by a specific user and available only to that user.

Create synonym – show you how to create a new synonym for a table.
Drop a synonym – describe how to drop a synonym from the database.

CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name


FOR [schema .] object_name [@ dblink];

The name of the object for which you are creating the synonym. It can be one of the following:
table
view
sequence CREATE PUBLIC SYNONYM suppliers
stored procedure FOR app.suppliers;
function
package Drop synonym
materialized view DROP PUBLIC SYNONYM suppliers;
java class schema object
user-defined object
synonym

Advantages of Oracle synonyms


First, synonyms allow you to change complicated and lengthy names with simplified aliases.
It is very helpful if you work with legacy systems. So instead of referring to a table like human_resources.employee_locations
Second, synonyms can help backward compatibility for legacy applications
For example, you rename a table but do not want to affect the current applications that currently use the table.
To keep the applications working properly, you can create a synonym that has the same name as the old name of the table.
Third, synonyms help move objects between schemas, even databases, without breaking the existing code.
s, materialized views, sequences, procedures, and stored function.
s, materialized views, sequences, procedures, and stored function.
u don't want the users to have to worry about knowing which schema owns the object.
ct such as a table or a view.
an rename and move of the underlying objects

med PUBLIC

n_resources.employee_locations, you can use offices.

ntly use the table.


e as the old name of the table.
ing the existing code.
NON – ANSI format joins: (oracle 8i joins)
When we are retrieving data from multiple tables based on the “WHERE” clause condition
then we called a NON-ANSI format join.
NON-ANSI joins are not portable. They are again classified into three types are as follows.

Equi Join
Non-Equi Join
Self Join
The syntax for NON-ANSI joins:
SELECT * FROM TABLE NAME1, TABLE NAME2 WHERE <JOIN CONDITION>;

ANSI format joins: (oracle 9i joins)


When we are retrieving data from multiple tables with “on” / “using” clause conditions then we called as t
from one database to another database) They are again classified as follows.

Inner Join
Outer Join (Left Outer Join, Right Outer Join, and Full Outer Join)
Cross Join (or) Cartesian Join
Natural Join
Syntax for ANSI joins:
SELECT * FROM <TABLE NAME1> <JOIN KEY> <TABLE NAME2 > ON <JOIN CONDITION>;

Examples to understand JOINs in Oracle:


We are going to use the following Course and Student tables to understand JOINs in Oracle with examples.
Examples to understand JOINs in Oracle

Please use the below SQL script to create and populate the Course and Student tables with the required sa

CREATE TABLE Course (


CourseId INT PRIMARY KEY,
CourseName VARCHAR(15),
CourseFee INT
);
INSERT INTO Course (CourseId, CourseName, CourseFee) VALUES (10, 'Oracle', 3500);
INSERT INTO Course (CourseId, CourseName, CourseFee) VALUES (20, 'MySQL', 3000);
INSERT INTO Course (CourseId, CourseName, CourseFee) VALUES (30, 'SQL Server', 4500);
CREATE TABLE Student (
StudentId INT PRIMARY KEY,
StudentName VARCHAR(15),
CourseId INT
);
INSERT INTO Student (StudentId, StudentName, CourseId) VALUES (1001, 'James', 10);
INSERT INTO Student (StudentId, StudentName, CourseId) VALUES (1002, 'Smith', 20);
INSERT INTO Student (StudentId, StudentName, CourseId) VALUES (1003, 'Warner', 30);
INSERT INTO Student (StudentId, StudentName, CourseId) VALUES (1004, 'Sara', 10);
INSERT INTO Student (StudentId, StudentName, CourseId) VALUES (1005, 'Pam', 20);
EQUI Join in Oracle:
Retrieving data from multiple tables based on “equal operator ( = ) ” is called an EQUI join. When we use E
column (or) common field name is no need to be the same name (but recommend). The common column

When we perform any join operation between tables there is no need to have a relationship(optional) (i.e.
only matching data/matching rows.

SELECT CNAME, BATCHCODE FROM BATCHES B, COURSES C


WHERE C.CCODE = B.CCODE (+);

//Above query have NON-ANSI join


SELECT CNAME, BATCHCODE FROM BATCHES B, COURSES C
WHERE C.CCODE = B.CCODE (+);

//Above query have NON-ANSI join


use condition

re as follows.

conditions then we called as the join as ANSI format join. ANSI joins are portability (move

NDITION>;

OINs in Oracle with examples.

ent tables with the required sample data.

e', 3500);
L', 3000);
erver', 4500);

mes', 10);
mith', 20);
arner', 30);
ra', 10);
am', 20);

d an EQUI join. When we use EQUI join between two (or) more than two tables the common
mmend). The common column (or) common field datatype must be matched.

ve a relationship(optional) (i.e. primary key & foreign key relation). EQUI join always retrieves

You might also like