SlideShare une entreprise Scribd logo
1  sur  106
Database
A collection of information organized in such a
way that a computer program can quickly
select desired pieces of data
Traditional Database
• Traditional databases are organized by fields,
records, and files
• A field is a single piece of information
• A record is one complete set of fields
• A file is a collection of records
Database Management System
collection of programs that enables you to enter,
organize, and select data in a database
Various functions of DBMS
• Manage the users and keep restrictions over
them
• Enable users to create, modify and access the
data
• Perform maintenance over the database
(Backing up, Performance tuning, etc)
Various DBMS
• dBase
• FoxPro
• MS-Access
• Oracle
• Sybase
• DB2
• MySQL
• SQL Server
Characteristics of good database system
• Good database is identified by ACID properties
• A – Atomicity
• C – Consistency
• I – Isolation
• D - Durability
Atomicity
• Atomicity refers to combining multiple transaction into single
transaction
• A group of transaction can be considered as a atomic (single)
transaction
• So the database system have to do all or do nothing
Example:
A is transferring Rs.1000 to B's account
Steps:
1) Deduct 1000 from A's account balance
2) Add 1000 to B's account balance.
If first step is done and due to some factors 2nd is not done, will lead to
serious error. So we should do all steps or do nothing
Oracle: savepoint, rollback and commit
Consistency
• System will provide the user to define some rules regarding the data.
(eg. Unique Key)
• Once rules defined, they are consistently maintained until the
database is deleted
Oracle: Primary Key, Unique, Not Null, Foreign Key, Cascade
Isolation
• Database systems are accessed by multiple users simultaneously.
• Every request is isolated from each other.
Eg: -
• Single Credit card account having two credit cards.
• Two cards are swiped simultaneously for amount equal to the credit
limit.
• Two requests reach the server simultaneously.
• But the requests are processed one by one (each request is isolated
from another)
Oracle : Record Locks
Durability
• Once data is stored and committed. And it was retrieved at a later
time, durability confirms that we will get the same data which was
stored earlier.
Oracle– Back up and transaction logs
Normalization
• Overall objective on normalization is to reduce redundancy
• Redundancy – Data repeatedly stored
• Normalization recommends to divide the data across multiple tables
to avoid redundancy
• When data is added, altered or deleted in one table it should
maintain the data consistency.
• Three important forms of normalization
1. First normal form (1NF)
2. Second normal form (2NF)
3. Third normal form (3NF)
First Normal Form (1NF)
"The domain of each attribute contains only atomic values, and
the value of each attribute contains only a single value from that
domain"
We Cannot have multiple values for a particular attribute (field) in
a single record
Name Skill
Raj C++, C#, MS SQL
Arun Java, Oracle
Against 1NF
Employee
Name Skill
Raj C++
Raj C#
Arun Java
Arun Oracle
Compliance with 1NF
Employee
Second Normal Form (2NF)
"a table is in 2NF if and only if it is in 1NF and no non-prime
attribute is dependent on any proper subset of any candidate key
of the table"
Prime – Key field used to identify the entire record (eg. Emp ID)
Non – Prime – Field that depends on Prime Key (eg. DOB)
Candidate Key – When two fields combine to form primary key
Against 2NF
Employee
Name Skill Location
Raj C++ Chennai
Raj C# Chennai
Arun Java Bangalore
Arun Oracle Bangalore
Compliance with 2NF
Employee Skill Employee Location
Name Skill
Raj C++
Raj C#
Arun Java
Arun Oracle
Name Location
Raj Chennai
Arun Bangalore
Third Normal Form (3NF)
"the entity is in second normal form and all the attributes in a
table are dependent on the primary key and only the primary
key""
Against 3NF
Employee
Name City PIN
Raj Chennai 600033
Arun Bangalore 400028
Arjun Chennai 600033
Compliance with 3NF
Employee Pin
Name PIN
Raj 600033
Arun 400028
Arjun 600033
PIN City
600033 Chennai
400028 Bangalore
Compliance with 3NF
Pin
Structured Query Language
• SQL is a standard devised by ANSI
• All DBMS will be following the standard and make some little alteration in it
• Four categories of SQL Statements
• DDL– Data Definition Language
• DML– Data Manipulation Language
• DCL– Data Control Language
• TCL– Transaction Control Language
• DRL or DQL – Data Retrieval or Query Language (With respect to user
rights it belongs to DML group)
DDL Statements
• Create/Modify/ Delete the following
• Table
• Views
• TRUNCATE records from a table
Data types
• Fixed Point Number
• NUMBER (<Width>, <Decimal Places>)
Input Data Specified As Stored As
7,456,123.89 NUMBER 7456123.89
7,456,123.89 NUMBER(*,1) 7456123.9
7,456,123.89 NUMBER(9) 7456124
7,456,123.89 NUMBER(9,2) 7456123.89
7,456,123.89 NUMBER(9,1) 7456123.9
7,456,123.89 NUMBER(6)
(not accepted,
exceeds precision)
7,456,123.89 NUMBER(7,-2) 7456100
Data types
Floating point numbers
Data Type Bytes
utilized
Precision
BINARY_FLOAT 4 7 Digits
BINARY_DOUBLE 8 14 Digits
Data types
Date & Time
Data Type Description Range
DATE Gregorian Date 01.01.0001 to 12.31.9999
TIMESTAMP hh:mm:ss[.nnnnnnnnn]
Data types
ASCII String
Data Type Description Maximum
CHAR(n) Fixed length string of total
length 'n'
2000 Ascii characters
VARCHAR(n) Variable length string 4000 Ascii characters
Data types
Unicode String
Data Type Description Maximum
NCHAR(n) Fixed length string of total
length 'n'
2000 Unicode characters
NVARCHAR(n) Variable length string 4000 Unicode characters
Create a Table
Usage:
CREATE TABLE <Table name> (
<FieldName1> <DataType> [<Constraint>],
<FieldName2> <DataType> [<Constraint>],
.
.
<FieldNameN> <DataType> [<Constraint>])
Create a Table
Constraints
NOT NULL --------- Don't Allow a null value.
UNIQUE --------- Values cannot be duplicated but it can allow one
null value
PRIMARY KEY --------- Values cannot be duplicated and even null is not
allowed.
CHECK ---------- Check for a condition
DEFAULT ----------- Set a default value if user don't provide a value
Create a Table…
Example
CREATE TABLE TblEmployee (
EmpID NUMBER(3) PRIMARY KEY,
EmpFName VARCHAR2(20) NOT NULL,
EmpMName VARCHAR2(20),
EmpLName VARCHAR2(20) NOT NULL);
Create a Table with named constraint
CREATE TABLE TblEmployee (
EmpID NUMBER(3) CONSTRAINT pkEmpID PRIMARY KEY,
EmpFName VARCHAR (20) NOT NULL,
EmpMName VARCHAR (20),
EmpLName VARCHAR (20) NOT NULL);
------- OR --------
CREATE TABLE TblEmployee (
EmpID NUMBER(3),
EmpFName VARCHAR2(20) NOT NULL,
EmpMName VARCHAR2(20),
EmpLName VARCHAR2(20) NOT NULL,
CONSTRAINT pkEmpID PRIMARY KEY(EmpID)
);
Declare at Column Level
Declare at Table Level
Foreign Key Constraint
CREATE TABLE TblDept (
DeptID NUMBER(3) PRIMARY KEY,
DeptName VARCHAR2(20) NOT NULL);
CREATE TABLE TblEmp(
EmpID NUMBER(3),
EmpName VARCHAR2(30),
DeptID NUMBER(3) DEFAULT 0,
CONSTRAINT pkEmpID PRIMARY KEY(EmpID),
CONSTRAINT fkDeptID
FOREIGN KEY (DeptID) REFERENCES TblDept(DeptID));
Default Constraint, DeptID
is set to 0 if no value
specified
Foreign Key Constraint…
DeptID DeptName
0 Unassigned
1 PRODUCTION
2 PURCHASE
3 SALES
4 HUMAN RESOURCES
Insert the following records in TblDept
Try to insert the value 5 for DeptID in TblEmp (See the error message)
Now insert the following values
EmpID EmpName DeptID
101 Andrews 1
102 James 3
103 Chris 4
104 Johnty 2
105 Johnson 3
Foreign Key Constraint…
Now Delete 104 from the Table TblEmp (It won't affect the Table TblDept)
EmpID EmpName DeptID
101 Andrews 1
102 James 3
103 Chris 4
105 Johnson 3
DeptID DeptName
0 Unassigned
1 PRODUCTION
2 PURCHASE
3 SALES
4 HUMAN RESOURCES
Foreign Key Constraint…
Now Delete 3,Sales Department from the table TblDept
(Cannot be deleted as It is referred by TblEmp)
But 2, Purchase Department can be deleted as it don't have any reference.
EmpID EmpName DeptID
101 Andrews 1
102 James 3
103 Chris 4
105 Johnson 3
DeptID DeptName
0 Unassigned
1 PRODUCTION
2 PURCHASE
3 SALES
4 HUMAN RESOURCES
Foreign Key Constraint…
ON DELETE CASCADE -------- All the records referring will get deleted
ON DELETE SET NULL -------- Referring Field will set to NULL
ON DELETE SET DEFAULT -------- Default value is assigned
ON DELETE CASCADE
ALTER TABLE TblEmp DROP CONSTRAINT fkDeptID
GO
ALTER TABLE TblEmp ADD CONSTRAINT
fkDeptID FOREIGN KEY (DeptID) REFERENCES TblDept(DeptID)
ON DELETE CASCADE
Now if 3,Sales Department is deleted from the table TblDept, All the
employees belonging to sales department are deleted.
EmpID EmpName DeptID
101 Andrews 1
102 James 3
103 Chris 4
105 Johnson 3
DeptID DeptName
0 Unassigned
1 PRODUCTION
2 PURCHASE
3 SALES
4 HUMAN RESOURCES
ON DELETE SET NULL
ALTER TABLE TblEmp DROP CONSTRAINT fkDeptID
GO
ALTER TABLE TblEmp ADD CONSTRAINT
fkDeptID FOREIGN KEY (DeptID) REFERENCES TblDept(DeptID)
ON DELETE SET NULL
Now if 3,Sales Department is deleted from the table TblDept, All the values 3 in
DeptID is set to NULL.
EmpID EmpName DeptID
101 Andrews 1
102 James NULL
103 Chris 4
105 Johnson NULL
DeptID DeptName
0 Unassigned
1 PRODUCTION
2 PURCHASE
3 SALES
4 HUMAN RESOURCES
ON DELETE SET DEFAULT
ALTER TABLE TblEmp DROP CONSTRAINT fkDeptID
GO
ALTER TABLE TblEmp ADD CONSTRAINT
fkDeptID FOREIGN KEY (DeptID) REFERENCES TblDept(DeptID)
ON DELETE SET DEFAULT
Now if 3,Sales Department is deleted from the table TblDept, All the values 3 in
DeptID is set to default value (0).
EmpID EmpName DeptID
101 Andrews 1
102 James 0
103 Chris 4
105 Johnson 0
DeptID DeptName
0 Unassigned
1 PRODUCTION
2 PURCHASE
3 SALES
4 HUMAN RESOURCES
Check Constraint
CREATE TABLE TblStudent(
RegNo Int PRIMARY KEY,
StudName Char(20) NOT NULL,
Mark NUMBER(3),
CONSTRAINT chkMark CHECK (Mark>=0 AND Mark <=100)
)
Mark field can take the
values only between 0 and
100
Alter Table
• Add a Column/Constraint
• Alter a Column (Constraint cannot be altered)
• Drop a Column/ Constraint
Add Column
ALTER TABLE TblEmp ADD EmpDOB DATE
or
ALTER TABLE TblEmp ADD (EmpDOB DATE,EmpDOJ DATE)
Alter Column
ALTER TABLE TblEmp MODIFY EmpName VARCHAR2(40)
Drop Column
ALTER TABLE TblEmp DROP COLUMN EmpDOB
Drop Table
Delete the entire table
Usage:
DROP TABLE <Table Name>
Eg.
DROP TABLE TblEmp
Warning
Table cannot be recovered
DML Statements
• Add records to the table (INSERT)
• Modify the record (UPDATE)
• Remove the record from the table (DELETE, TRUNCATE(DDL))
• Retrieve Information from a table (SELECT)
INSERT
INSERT INTO <TableName>(<Field1>, <Field2>,……..<Fieldn>)
VALUES(<Value1>,<Value2>,……<Valuen>)
• Field1 Value1, Field2 Value2 ….. Fieldn Valuen
• Data type of value and field should be matched
• Unspecified Fields will take NULL value or DEFAULT value as per table design
• If Constraint doesn't allow a NULL value for a unspecified field the record is not
inserted
Alternative version:
INSERT INTO <TableName> VALUES(<Value1>,<Value2>,……<Valuen>)
• Values are specified in the same order as that of table's fields order
• Number of values should be exactly matched
INSERT
Create the table
CREATE TABLE TblProduct (ProdID NUMBER(3), ProdName VARCHAR2(20),
LaunchDate Date, Unit VARCHAR2(5),
PricePerUnit NUMBER(9,2))
Insert Record
INSERT INTO TblProduct (ProdID,ProdName,LaunchDate,Unit,PricePerUnit)
VALUES(1,'Lavera',TO_DATE('01-Jan-1998'),'50g',1.15)
Or
INSERT INTO TblProduct VALUES(2,'Lavera',TO_DATE('22-May-2001'),'100g',1.95)
UPDATE
UPDATE <TableName> SET <Field Name1>= <Value1>,
<Field Name2>=<Value2>,
.
.
<Field Name3>=<Value3>
WHERE <Condition>
Warning:
If you exclude the WHERE condition, Entire records will take the given value
Example
Set the cost of Product 5 as $1.65
UPDATE TblProduct SET PricePerUnit=1.65 WHERE ProdID=5
Increase the cost of all products by 15 Cents
UPDATE TblProduct SET PricePerUnit=PricePerUnit+0.15
DELETE
DELETE FROM <TableName> WHERE <Condition>
Warning:
DELETE FROM <TableName> (Without WHERE condition) will delete all the records
Example
Delete Product 6
DELETE FROM TblProduct WHERE ProdID=6
Delete all record
DELETE FROM TblProduct
Use TRUNCATE to delete all records
TRUNCATE TABLE TblProduct
DROP TABLE will delete entire table
But TRUNCATE will delete only the records
DELETE vs TRUNCATE
S No. TRUNCATE DELETE
1 DDL Command DML Command
2 Locks the entire table before
deletion
Locks row by row to delete each record
3 WHERE Condition cannot be used WHERE can be used to selectively
delete the records
4 Never activates a TRIGGER Activates TRIGGER ever deletion of a
row
5 No. of Transactions=1 No of Transactions= No. of rows
deleted
6 High speed process Slow process
INDEX
• Indexes are background objects that are used to retrieve the data fast
• Updating the records slows down as the process involves updating the index
Usage:
CREATE INDEX <Index Name> ON <TableName>
(<Field1> [ASC|DESC],
<Field2>[ASC|DESC],
…
<Fieldn>[ASC|DESC])
Example
CREATE INDEX IdxEmpName ON TblEmp(EmpLName, EmpFName)
DROP an INDEX
DROP INDEX <Index Name> ON <Table Name>
SELECT
CREATE TABLE TblEmpDemo ( EmpID NUMBER(3), EmpFName
VARCHAR2(25), EmpLName VARCHAR2(25), Gender CHAR(1), DOB
Date, DOJ Date, PayPerDay NUMBER(9,2), EmpCity VARCHAR2 (20));
SELECT
INSERT INTO TblEmpDemo VALUES (1, 'Sebastien', 'Porter', 'M', TO_DATE('21-Dec-1974'), TO_DATE( '01-Mar-1999'),
100, 'Austin');
INSERT INTO TblEmpDemo VALUES (2, 'Suzie', 'Hoak', 'F', TO_DATE( '26-Jul-1978'), TO_DATE( '15-Feb-2007') , 80,
'Denver');
INSERT INTO TblEmpDemo VALUES (3, 'Antoinette', 'Clark', 'M', TO_DATE( '07-Aug-1977') , TO_DATE( '23-Mar-2010'),
110, 'New York');
INSERT INTO TblEmpDemo VALUES (4, 'Koko', 'Domba', 'M', TO_DATE( '01-May-1984'), TO_DATE( '01-May-2011'), 85 ,
'Austin');
INSERT INTO TblEmpDemo VALUES (5, 'Janet ', 'West' , 'F', TO_DATE( '14-Jan-1981') , TO_DATE( '12-Dec-1999'), 90,
'Houston');
INSERT INTO TblEmpDemo VALUES (6, 'Catherine', 'Chang', 'F', TO_DATE( '11-Apr-1979') , TO_DATE( '12-Dec-1980'),
100 , 'New York');
INSERT INTO TblEmpDemo VALUES (7, 'Nehemiah', 'Den', 'M', TO_DATE( '05-Dec-1975') , TO_DATE( '05-Jan-1994') ,120,
'Austin');
INSERT INTO TblEmpDemo VALUES (8, 'Sherryl' , 'Dsouza', 'F', TO_DATE( '08-May-1991'), TO_DATE( '03-Feb-2011'), 75,
'New York');
INSERT INTO TblEmpDemo VALUES (9, 'Santos', 'Pacheco', 'M', TO_DATE( '03-Jun-1985'), TO_DATE( '12-Jan-2005'), 90,
'Denver');
INSERT INTO TblEmpDemo VALUES (10, 'Ruby', 'DeGaram', 'F', TO_DATE( '01-Jun-1982'), TO_DATE( '01-Apr-2004'),
110, 'Houston');
INSERT INTO TblEmpDemo VALUES (11, 'Carole', 'Chance', 'F', TO_DATE( '05-Feb-1990'), TO_DATE( '05-Jan-2010'), 80,
'Houston');
INSERT INTO TblEmpDemo VALUES (12, 'Justin', 'Vittas', 'M', TO_DATE( '27-Jun-1983'), TO_DATE( '24-Jun-2004'), 100,
'New York');
SELECT
Usage: (Simple Version)
SELECT <FieldName1> [AS <Alias1>],
<FieldName2> [AS <Alias2>],
.
.
<FieldNamen> [AS <Aliasn>] FROM <Table Name>
SELECT
Select all rows and all columns form the table
SELECT * FROM TblEmpDemo
SELECT
Select all rows and specified columns with alias
SELECT EmpID AS "Emp ID", EmpFName || EmpLName AS Name, DOB, DOJ,
EmpCity AS City FROM TblEmpDemo
SELECT
Print the salary table for a month having 23 working days
SELECT EmpID AS "Emp ID",
EmpFName AS Name,
PayPerDay*23 AS Payable FROM TblEmpDemo
SELECT
Usage: (Filtering records using WHERE)
SELECT <FieldName1> [AS <Alias1>],
<FieldName2> [AS <Alias2>],
.
<FieldNamen> [AS <Aliasn>] FROM <Table Name> WHERE <Condition>
Operators Allowed in the WHERE Clause
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column
SELECT
Select Employees whose PayPerDay is more than 100 dollars
SELECT * FROM TblEmpDemo WHERE PayPerDay >= 100
SELECT
Select Employees who are from Austin
SELECT * FROM TblEmpDemo WHERE EmpCity = 'Austin'
SELECT
Select Employees who are not from Austin
SELECT * FROM TblEmpDemo WHERE EmpCity <> 'Austin'
SELECT
Select Employees who joined between the fiscal year 2003-04
SELECT * FROM TblEmpDemo WHERE DOJ BETWEEN TO_DATE('01-Oct-2003') AND
TO_DATE('30-Sep-2004')
SELECT
Select Employees whose first name starting with S
SELECT * FROM TblEmpDemo WHERE EmpFName LIKE 'S%'
SELECT
Select Employees whose first name having second letter a
SELECT * FROM TblEmpDemo WHERE EmpFName LIKE '_a%'
SELECT
Select Employees whose first name having second letter a
SELECT EmpFName,EmpCity FROM TblEmpDemo
WHERE EmpCity IN ('Denver','Houston')
EMPFNAME EMPCITY
------------------------- --------------------
Suzie Denver
Janet Houston
Santos Denver
Ruby Houston
Carole Houston
SELECT
SELECT (ORDER BY)
Usage: (Grouping records using ORDER BY)
SELECT <FieldName1> [AS <Alias1>],
<FieldName2> [AS <Alias2>],
.
<FieldNamen> [AS <Aliasn>] FROM <Table Name> ORDER BY <FieldName>
[ASC|DESC]
SELECT
Select Employees in the order of DOB (Eldest first)
SELECT * FROM TblEmpDemo ORDER BY DOB
SELECT
Select Employees in the order of DOB (Youngest First)
SELECT * FROM TblEmpDemo ORDER BY DOB DESC
SELECT
Select Employees in the order of PayPerDay and DOJ (If PayPerDay is repeated
then it uses the DOJ to select the next record)
SELECT * FROM TblEmpDemo ORDER BY PayPerDay, DOJ
SELECT
SELECT DISTINCT
Usage: (Delist the duplicate value)
SELECT DISTINCT <FieldName1> [AS <Alias1>],
<FieldName2> [AS <Alias2>],
.
<FieldNamen> [AS <Aliasn>] FROM <Table Name>
SELECT
List all the cities from which our Employees from
SELECT DISTINCT EmpCity FROM TblEmpDemo
List all the cities from which our Employees from and also separate gender wise
SELECT DISTINCT EmpCity, Gender FROM TblEmpDemo
From Austin and Houston, We have only MALE Employee(s)
From Denver and New York, Both MALE and FEMALE exists
SELECT
SELECT (Using function)
• COUNT - Count the records with respect to some condition
• SUM - Applied for a numerical field, to sum the existing values
• AVG - Compute the average of all the values
• MIN - Find the minimum value of a field
• MAX - Get the maximum
SELECT
Count all the employees we have
SELECT COUNT(*) AS EmpCount FROM TblEmpDemo
Count all the Male employees we have
SELECT COUNT(*) AS MaleEmpCount FROM TblEmpDemo WHERE Gender='M'
Count the total number of cities we have employees from
SELECT COUNT(DISTINCT EmpCity) AS CityCount FROM TblEmpDemo
SELECT
Find total amount paid all the employees per day
SELECT SUM(PayPerDay) AS TotalPay FROM TblEmpDemo
Find the average pay of male employees
SELECT AVG(PayPerDay) AS MaleAvgPay FROM TblEmpDemo WHERE Gender='M'
Find the Max pay
SELECT MAX(PayPerDay) AS MaxPay FROM TblEmpDemo
SELECT
SUB-QUERIES or NESTED QUERIES
A query that exists within another query is called subquery
A subquery nested in the outer SELECT statement has the following components:
• A regular SELECT query including the regular select list components.
⁻ Using a SELECT statement as a column name
• A regular FROM clause including one or more table or view names.
⁻ Getting Data from multiple tables, similar to JOINS
⁻ Also known as EQUI JOIN
• An optional WHERE clause.
⁻ Using SELECT statement in the WHERE clause
• An optional GROUP BY clause.
• Using Aggregate function in columns and group by a particular field
• An optional HAVING clause
• Further filter the result after applying the GROUP BY clause
SELECT
CREATE TABLE AccMaster( AccNo Char(5),
FName VARCHAR2(25), LName VARCHAR2 (25),
Gender CHAR(1),
RefAccNo CHAR(5),
OpenDate DATE,
CurrBal NUMBER(9,2),
CONSTRAINT pkAccNo PRIMARY KEY(AccNo));
CREATE TABLE AccTrans(
TransID NUMBER(5),
TransDate DATE,
AccNo CHAR(5),
Amount NUMBER(9,2), TransType CHAR(1),
CONSTRAINT pkTransID PRIMARY KEY(TransID),
CONSTRAINT fkAccNo FOREIGN KEY(AccNo)
REFERENCES AccMaster(AccNo));
SELECT
INSERT INTO AccMaster VALUES ('56001', 'James', 'Carlton', 'M', NULL,
TO_DATE('05-Oct-2005'),1500);
INSERT INTO AccMaster VALUES ('56002','Chrissy','Arlene','F','56001', TO_DATE('04-
Jan-2006'),1200);
INSERT INTO AccMaster VALUES ('56003','Eldridge','Powers','M','56001',
TO_DATE('24-Jul-2006'),1700);
INSERT INTO AccMaster VALUES ('56004', 'Hobert', 'Spampinato', 'M', '56002',
TO_DATE('21-Feb-2007'),1300);
INSERT INTO AccMaster VALUES('56005','Gloria','Wright','F','56003', TO_DATE('07-
Apr-2008'),1900);
SELECT
INSERT INTO AccTrans VALUES (1, TO_DATE('05-Oct-2005'),'56001',500,'D');
INSERT INTO AccTrans VALUES (2, TO_DATE('01-Dec-2005'),'56001',1500,'D');
INSERT INTO AccTrans VALUES (3, TO_DATE('04-Jan-2006'),'56002',2000,'D');
INSERT INTO AccTrans VALUES (4, TO_DATE('05-Feb-2006'),'56001',400,'W');
INSERT INTO AccTrans VALUES (5, TO_DATE('15-Feb-2006'),'56002',200,'W');
INSERT INTO AccTrans VALUES (6, TO_DATE('24-Jul-2006'),'56003',1000,'D');
INSERT INTO AccTrans VALUES (7, TO_DATE('15-Aug-2006'),'56001',100,'W');
INSERT INTO AccTrans VALUES (8, TO_DATE('29-Aug-2006'),'56002',200,'D');
INSERT INTO AccTrans VALUES (9, TO_DATE('12-Sep-2006'),'56003',300,'W');
INSERT INTO AccTrans VALUES (10, TO_DATE('23-Dec-2006'),'56002',800,'W');
INSERT INTO AccTrans VALUES (11, TO_DATE('21-Feb-2007'),'56004',2000,'D');
INSERT INTO AccTrans VALUES (12, TO_DATE('10-Mar-2007'),'56004',200,'W');
INSERT INTO AccTrans VALUES (13, TO_DATE('01-Apr-2008'),'56004',1000,'D');
INSERT INTO AccTrans VALUES (14, TO_DATE('07-Apr-2008'),'56005',100,'D');
INSERT INTO AccTrans VALUES (15, TO_DATE('01-Feb-2009'),'56004',1900,'W');
INSERT INTO AccTrans VALUES (16, TO_DATE('01-May-2009'),'56005',100,'D');
INSERT INTO AccTrans VALUES (17, TO_DATE('01-Jan-2010'),'56005',700,'D');
SELECT
Include the sub-query as a list component
List all the account holders name along with the referrers name.
SELECT A.AccNo,A.FName,
(SELECT B.FName FROM AccMaster B WHERE A.RefAccNo = B.AccNo)
FROM AccMaster A
SELECT
SELECT query involving more than one table
List all the Transactions and also include the account holder name.
SELECT A.TransID ,A.AccNo,B.FName,A.TransType,A.Amount
FROM AccTrans A,AccMaster B
WHERE A.AccNo=B.AccNo
SELECT AccTrans.TransID
,AccTrans.AccNo,AccMaster.FName,AccTrans.TransType,AccTrans.Amount
FROM AccTrans ,AccMaster
WHERE AccTrans.AccNo=AccMaster.AccNo
SELECT TransID ,AccTrans.AccNo,FName,TransType,Amount
FROM AccTrans ,AccMaster
WHERE AccTrans.AccNo=AccMaster.AccNo
This
technique is
also known
as EQUI JOIN
SELECT
SELECT
WHERE…IN..
(Check if the value exist in the list)
Find the Employee who is getting highest pay.
SELECT EmpID,EmpFName,PayPerDay FROM TblEmpDemo
WHERE PayPerDay IN (SELECT MAX(PayPerDay) FROM TblEmpDemo)
SELECT
WHERE…NOT IN..
(Check if the value not exist in the list)
Find the Customer who never made any transaction in the year 2006
SELECT AccNo,FName FROM AccMaster WHERE AccNo NOT IN
(SELECT AccNo FROM AccTrans WHERE TO_CHAR(TransDate,'YYYY')='2006')
SELECT
WHERE..ALL/ SOME/ ANY
• A relational operator can be used to compare with…..
• ALL ---- All the values (internally AND operation)
• ANY or SOME ---- At least One value (internally OR operation)
List employees whose salary are above average
SELECT * FROM TblEmpDemo WHERE PayPerDay >=
ALL (SELECT AVG(PayPerDay) FROM TblEmpDemo)
SELECT
GROUP BY & HAVING
GROUP BY clause used to apply an aggregate function (SUM, AVG, MAX..) with
respect to some field
Eg.
Total transaction by each customer (both credit and debit)
SELECT AccNo, SUM(Amount) FROM AccTrans GROUP BY AccNo
WHERE can be used to apply filter before aggregation
Total deposit done by each customer
SELECT AccNo, SUM(Amount) FROM AccTrans
WHERE TransType='D' GROUP BY AccNo
HAVING can be used to apply filter after aggregation
List of customers those who done total deposits more than Rs.1500
SELECT AccNo, SUM(Amount) FROM AccTrans WHERE TransType='D'
GROUP BY AccNo HAVING SUM(Amount) >= 1500
JOINS
JOINS
Inner Join Outer Join
Left Outer
Join
Right
Outer Join
Full Outer
join
Cross join
INNER JOIN
This join returns rows when there is at least one match in both the tables.
INNER JOIN
SalesEmp
EmpID EmpName
1 Hansen
2 Svendson
3 Pettersen
Orders
OrderID OrderNo EmpID
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34762 7
SELECT SalesEmp.EmpName, Orders.OrderNo FROM SalesEmp INNER JOIN
Orders ON SalesEmp.EmpID=Orders.EmpID
EmpName OrderNo
Hansen 22456
Hansen 24562
Pettersen 77895
Pettersen 44678
LEFT OUTER JOIN
This join returns all the rows from the left table in conjunction with the matching
rows from the right table. If there are no columns matching in the right table, it
returns NULL values.
If WHERE condition is included saying, right table's column is null then, it will
return only the rows which don't have a match
LEFT OUTER JOIN ….
SalesEmp
EmpID EmpName
1 Hansen
2 Svendson
3 Pettersen
Orders
OrderID OrderNo EmpID
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34762 7
SELECT SalesEmp.EmpName, Orders.OrderNo
FROM SalesEmp LEFT OUTER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID
EmpName OrderNo
Hansen 22456
Hansen 24562
Svendson NULL
Pettersen 77895
Pettersen 44678
LEFT OUTER JOIN.. WHERE NULL
SalesEmp
EmpID EmpName
1 Hansen
2 Svendson
3 Pettersen
Orders
OrderID OrderNo EmpID
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34762 7
SELECT SalesEmp.EmpName, Orders.OrderNo
FROM SalesEmp LEFT OUTER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID
WHERE Orders.EmpID IS NULL
EmpName OrderNo
Svendson NULL
RIGHT OUTER JOIN
This join returns all the rows from the right table in conjunction with the
matching rows from the left table. If there are no columns matching in the left
table, it returns NULL values.
If WHERE condition is included saying, left table's column is null then, it will
return only the rows which don't have a match
RIGHT OUTER JOIN ….
SalesEmp
EmpID EmpName
1 Hansen
2 Svendson
3 Pettersen
Orders
OrderID OrderNo EmpID
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34762 7
SELECT SalesEmp.EmpName, Orders.OrderNo
FROM SalesEmp RIGHT OUTER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID
EmpName OrderNo
Hansen 22456
Hansen 24562
Pettersen 77895
Pettersen 44678
NULL 34762
RIGHT OUTER JOIN WHERE NULL ….
SalesEmp
EmpID EmpName
1 Hansen
2 Svendson
3 Pettersen
Orders
OrderID OrderNo EmpID
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34762 7
SELECT SalesEmp.EmpName, Orders.OrderNo
FROM SalesEmp RIGHT OUTER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID
WHERE SalesEmp.EmpID IS NULL
EmpName OrderNo
NULL 34762
FULL OUTER JOIN
This join combines left outer join and right outer join. It returns row from either
table when the conditions are met and returns null value when there is no match.
If WHERE condition is included saying, left table's or left table's column is null
then, matching records are ignored
FULL OUTER JOIN
SalesEmp
EmpID EmpName
1 Hansen
2 Svendson
3 Pettersen
Orders
OrderID OrderNo EmpID
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34762 7
SELECT SalesEmp.EmpName, Orders.OrderNo
FROM SalesEmp FULL OUTER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID
EmpName OrderNo
Hansen 22456
Hansen 24562
Pettersen 77895
Pettersen 44678
NULL 34762
Svendson NULL
FULL OUTER JOIN
SalesEmp
EmpID EmpName
1 Hansen
2 Svendson
3 Pettersen
Orders
OrderID OrderNo EmpID
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34762 7
SELECT SalesEmp.EmpName, Orders.OrderNo
FROM SalesEmp FULL OUTER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID
WHERE SalesEmp.EmpID IS NULL OR Orders.EmpID IS NULL
EmpName OrderNo
NULL 34762
Svendson NULL
CROSS JOIN ….
Alpha
AlphaCol
A
B
C
Numerals
NumCol
1
2
3
SELECT Alpha.AlphaCol,Numerals.NumCol
FROM Alpha CROSS JOIN Numerals
AlphaCol NumCol
A 1
A 2
A 3
B 1
B 2
B 3
C 1
C 2
C 3
UNION & UNION ALL
Alpha
AlphaCol
A
B
C
Numerals
NumCol
1
2
3
SELECT AlphaCol FROM Alpha
UNION
SELECT NumCol FROM Numerals
AlphaCol
A
B
C
1
2
3
Note:
First tables column Name(s) will be taken
UNION will list only distinct values
UNION ALL will list all values even if duplicate exists
Practical Learning(I)
ID Name Age Salary
1 Abe 61 140000
2 Bob 34 44000
5 Chris 34 40000
7 Dan 41 52000
8 Ken 57 115000
11 Joe 38 38000
ID Name City Industry Type
4 Samsonic pleasant J
6 Panasung oaktown J
7 Samony jackson B
9 Orange Jackson B
Number order_date cust_id salesperson_id Amount
10 8/2/96 4 2 540
20 1/30/99 4 8 1800
30 7/14/95 9 1 460
40 1/29/98 7 2 2400
50 2/3/98 6 7 600
60 3/2/98 6 7 720
70 5/6/98 9 7 150
Orders
SalesEmp
Customer
Practical Learning(I)
Write a query to find…
a. The names of all salespeople that have an order with Samsonic.
b. The names of all salespeople that do not have any order with Samsonic.
c. The names of salespeople that have 2 or more orders.
Practical Learning(II)
User
UserID
UserName
PhoneNum
LoginHistory
UserID
LoginDate
1. Write a SQL query that returns the name, phone number and most recent
date for any user that has logged in over the last 30 days
2. Write a SQL query to determine which user had never logged in before
VIEWS
• View is a virtual table that contains columns from one or more tables
• View is an precompiled object, which holds a query.
• It can be used as a table for another query.
• Used to reduce the complexity of large queries
CREATE VIEW EmpOrders
AS
SELECT SalesEmp.EmpName, Orders.OrderNo
FROM SalesEmp INNER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID
VIEWS
Select VIEW like a table
SalesEmp
EmpID EmpName
1 Hansen
2 Svendson
3 Pettersen
Orders
OrderID OrderNo EmpID
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34762 7
SELECT * FROM EmpOrders
EmpName OrderNo
Hansen 22456
Hansen 24562
Pettersen 77895
Pettersen 44678
PL/SQL
• Programming language of Oracle
• PL/SQL stands for Procedural Language / Structured Query Language
• Developed by oracle to enhance the features of SQL
• PL/SQL Modules can be executed from SQL Plus or even from any front end
(Java)
• Front end developers can expect better performance when compared to
sending a raw DML statement over a network (PL/SQL program is a
precompiled and become a part of database)
PL/SQL
/* Simple PL/SQL program */
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
PL/SQL
/* Accessing Tables in PL/SQL */
DECLARE
mProdID TblProduct.ProdID%TYPE;
mProdName TblProduct.ProdName%TYPE;
BEGIN
SELECT ProdID,ProdName INTO mProdID,mProdName FROM
TblProduct WHERE ProdID=2;
dbms_output.put_line('Product ID=' || mProdID || ' Product Name='
|| mProdName);
END;
/
Create variables with
data type compatible
with the table's field
data type
STORED PROCEDURES
• Stored Procedure is a sequence of sql code (program) which can be called
whenever required
• It can take parameters (input/ output)
• When created, it becomes part of the database and pre-compiled
CREATE OR REPLACE PROCEDURE <Procedure Name>
([<Param1> <Data Type> [IN | OUT | IN OUT]]
[<Param2> <Data Type> [IN | OUT | IN OUT]]
….
[<ParamN> <Data Type> [IN | OUT | IN OUT]])
IS
[<Variable1> <Data Type>]
[<Variable2> <Data Type>]
…..
[<VariableN> <Data Type>]
BEGIN
<Code>
END
STORED PROCEDURES
CREATE OR REPLACE PROCEDURE ListCustomer
IS
mAccNo AccMaster.AccNo%type;
mFName AccMaster.FName%type;
mCurrBal AccMaster.CurrBal%type;
CURSOR cAccMaster
IS SELECT AccNo, FName, CurrBal FROM AccMaster;
BEGIN
OPEN cAccMaster;
dbms_output.put_line('Acc No Name Balance');
LOOP
FETCH cAccMaster into mAccNo, mFName, mCurrBal;
EXIT WHEN cAccMaster%notfound;
dbms_output.put_line(mAccNo || ' ' || mFName || ' ' ||
mCurrBal);
END LOOP;
CLOSE cAccMaster;
END;
/
Execute this procedure by
>EXEC ListCustomer
STORED PRCEDURE
Assignment
Consider the banking database
AccMast and AccTrans
Create a procedure called DoTrans taking parameter Account No, Amount, Type
('D'/'W')
• Generate TransID
• Insert record in AccTrans
• Update the AccMast, the current balance of the specified account number
FUNCTIONS
CREATE FUNCTION <Function Name>
([<Param1> <Data Type>],
[<Param2> <Data Type>],
….
[<ParamN> <Data Type>])
RETURNS <Data Type>
AS
BEGIN
<Code>
RETURN <Variable> |<Value>
END;
/
FUNCTIONS
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number
IS
total number(2) := 0;
BEGIN
SELECT count(*) into total FROM AccMaster;
RETURN total;
END;
/
Execute this function by
>select totalcustomers() from dual
STORED PROCEDURE vs FUNCTIONS
Sl. No. Stored Procedure Functions
1 SP can return multiple values Function can return only
one value
2 Transaction is allowed (INSERT/
UPDATE/ DELETE)
Transaction not allowed
3 It can have input & output
parameter
Only input parameter
4 SP can call a function and
another SP
Function can call another
function but not a stored
procedure
5 Exception Handling is
supported
Not supported
TRIGGERS
• Triggers are special kind of stored procedures that executes in response to
certain database action like INSERT/ UPDATE/ DELETE
• Triggers cannot be explicitly invoked like SP or Functions
• Types of Triggers
• BEFORE INSERT|UPDATE|DELETE ---- Fired before the given process
• AFTER INSERT|UPDATE|DELETE ---- Fired after the process
TRIGGERS
Consider an example in the employee table, we are maintaining a separate table for
the relieved, TblOldEmpDemo
CREATE TABLE TblOldEmpDemo (
EmpID NUMBER(3), EmpFName VARCHAR2(25),Gender CHAR(1),DOR DATE)
CREATE OR REPLACE TRIGGER TrgDeleteEmp AFTER DELETE ON TblEmpDemo
FOR EACH ROW
BEGIN
INSERT INTO TblOldEmpDemo VALUES
(:Old.EmpID,:Old.EmpFName,:Old.Gender, SYSDATE);
END;
/

Contenu connexe

Tendances (19)

1 ddl
1 ddl1 ddl
1 ddl
 
Dbms record
Dbms recordDbms record
Dbms record
 
SQL DDL
SQL DDLSQL DDL
SQL DDL
 
Oracle 11g SQL Overview
Oracle 11g SQL OverviewOracle 11g SQL Overview
Oracle 11g SQL Overview
 
Sql intro & ddl 1
Sql intro & ddl 1Sql intro & ddl 1
Sql intro & ddl 1
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
 
Sql commands
Sql commandsSql commands
Sql commands
 
New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012 New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 
Introduction to mysql part 1
Introduction to mysql part 1Introduction to mysql part 1
Introduction to mysql part 1
 
Database Overview
Database OverviewDatabase Overview
Database Overview
 
MariaDB Temporal Tables
MariaDB Temporal TablesMariaDB Temporal Tables
MariaDB Temporal Tables
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
R Get Started I
R Get Started IR Get Started I
R Get Started I
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 
R Get Started II
R Get Started IIR Get Started II
R Get Started II
 
Sql
SqlSql
Sql
 

Similaire à Dbms &amp; oracle

Aioug vizag oracle12c_new_features
Aioug vizag oracle12c_new_featuresAioug vizag oracle12c_new_features
Aioug vizag oracle12c_new_featuresAiougVizagChapter
 
In memory databases presentation
In memory databases presentationIn memory databases presentation
In memory databases presentationMichael Keane
 
Data Warehousing with Amazon Redshift
Data Warehousing with Amazon RedshiftData Warehousing with Amazon Redshift
Data Warehousing with Amazon RedshiftAmazon Web Services
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersJonathan Levin
 
Tutorial On Database Management System
Tutorial On Database Management SystemTutorial On Database Management System
Tutorial On Database Management Systempsathishcs
 
Amazon Redshift Deep Dive - February Online Tech Talks
Amazon Redshift Deep Dive - February Online Tech TalksAmazon Redshift Deep Dive - February Online Tech Talks
Amazon Redshift Deep Dive - February Online Tech TalksAmazon Web Services
 
[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13AnusAhmad
 
Data Warehousing in the Era of Big Data
Data Warehousing in the Era of Big DataData Warehousing in the Era of Big Data
Data Warehousing in the Era of Big DataAmazon Web Services
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.pptMARasheed3
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 
MS SQL Server.ppt
MS SQL Server.pptMS SQL Server.ppt
MS SQL Server.pptQuyVo27
 

Similaire à Dbms &amp; oracle (20)

IR SQLite Session #1
IR SQLite Session #1IR SQLite Session #1
IR SQLite Session #1
 
Unit - II.pptx
Unit - II.pptxUnit - II.pptx
Unit - II.pptx
 
DBMS Chapter-3.ppsx
DBMS Chapter-3.ppsxDBMS Chapter-3.ppsx
DBMS Chapter-3.ppsx
 
Aioug vizag oracle12c_new_features
Aioug vizag oracle12c_new_featuresAioug vizag oracle12c_new_features
Aioug vizag oracle12c_new_features
 
In memory databases presentation
In memory databases presentationIn memory databases presentation
In memory databases presentation
 
Sql for dbaspresentation
Sql for dbaspresentationSql for dbaspresentation
Sql for dbaspresentation
 
Data Warehousing with Amazon Redshift
Data Warehousing with Amazon RedshiftData Warehousing with Amazon Redshift
Data Warehousing with Amazon Redshift
 
Deep Dive on Amazon Redshift
Deep Dive on Amazon RedshiftDeep Dive on Amazon Redshift
Deep Dive on Amazon Redshift
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for Developers
 
Deep Dive on Amazon Redshift
Deep Dive on Amazon RedshiftDeep Dive on Amazon Redshift
Deep Dive on Amazon Redshift
 
Tutorial On Database Management System
Tutorial On Database Management SystemTutorial On Database Management System
Tutorial On Database Management System
 
Amazon Redshift Deep Dive - February Online Tech Talks
Amazon Redshift Deep Dive - February Online Tech TalksAmazon Redshift Deep Dive - February Online Tech Talks
Amazon Redshift Deep Dive - February Online Tech Talks
 
Deep Dive on Amazon Redshift
Deep Dive on Amazon RedshiftDeep Dive on Amazon Redshift
Deep Dive on Amazon Redshift
 
[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13
 
Data Warehousing in the Era of Big Data
Data Warehousing in the Era of Big DataData Warehousing in the Era of Big Data
Data Warehousing in the Era of Big Data
 
Deep Dive on Amazon Redshift
Deep Dive on Amazon RedshiftDeep Dive on Amazon Redshift
Deep Dive on Amazon Redshift
 
Oracle notes
Oracle notesOracle notes
Oracle notes
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.ppt
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
MS SQL Server.ppt
MS SQL Server.pptMS SQL Server.ppt
MS SQL Server.ppt
 

Dernier

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Dernier (20)

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

Dbms &amp; oracle

  • 1. Database A collection of information organized in such a way that a computer program can quickly select desired pieces of data
  • 2. Traditional Database • Traditional databases are organized by fields, records, and files • A field is a single piece of information • A record is one complete set of fields • A file is a collection of records
  • 3. Database Management System collection of programs that enables you to enter, organize, and select data in a database Various functions of DBMS • Manage the users and keep restrictions over them • Enable users to create, modify and access the data • Perform maintenance over the database (Backing up, Performance tuning, etc)
  • 4. Various DBMS • dBase • FoxPro • MS-Access • Oracle • Sybase • DB2 • MySQL • SQL Server
  • 5. Characteristics of good database system • Good database is identified by ACID properties • A – Atomicity • C – Consistency • I – Isolation • D - Durability
  • 6. Atomicity • Atomicity refers to combining multiple transaction into single transaction • A group of transaction can be considered as a atomic (single) transaction • So the database system have to do all or do nothing Example: A is transferring Rs.1000 to B's account Steps: 1) Deduct 1000 from A's account balance 2) Add 1000 to B's account balance. If first step is done and due to some factors 2nd is not done, will lead to serious error. So we should do all steps or do nothing Oracle: savepoint, rollback and commit
  • 7. Consistency • System will provide the user to define some rules regarding the data. (eg. Unique Key) • Once rules defined, they are consistently maintained until the database is deleted Oracle: Primary Key, Unique, Not Null, Foreign Key, Cascade
  • 8. Isolation • Database systems are accessed by multiple users simultaneously. • Every request is isolated from each other. Eg: - • Single Credit card account having two credit cards. • Two cards are swiped simultaneously for amount equal to the credit limit. • Two requests reach the server simultaneously. • But the requests are processed one by one (each request is isolated from another) Oracle : Record Locks
  • 9. Durability • Once data is stored and committed. And it was retrieved at a later time, durability confirms that we will get the same data which was stored earlier. Oracle– Back up and transaction logs
  • 10. Normalization • Overall objective on normalization is to reduce redundancy • Redundancy – Data repeatedly stored • Normalization recommends to divide the data across multiple tables to avoid redundancy • When data is added, altered or deleted in one table it should maintain the data consistency. • Three important forms of normalization 1. First normal form (1NF) 2. Second normal form (2NF) 3. Third normal form (3NF)
  • 11. First Normal Form (1NF) "The domain of each attribute contains only atomic values, and the value of each attribute contains only a single value from that domain" We Cannot have multiple values for a particular attribute (field) in a single record Name Skill Raj C++, C#, MS SQL Arun Java, Oracle Against 1NF Employee Name Skill Raj C++ Raj C# Arun Java Arun Oracle Compliance with 1NF Employee
  • 12. Second Normal Form (2NF) "a table is in 2NF if and only if it is in 1NF and no non-prime attribute is dependent on any proper subset of any candidate key of the table" Prime – Key field used to identify the entire record (eg. Emp ID) Non – Prime – Field that depends on Prime Key (eg. DOB) Candidate Key – When two fields combine to form primary key Against 2NF Employee Name Skill Location Raj C++ Chennai Raj C# Chennai Arun Java Bangalore Arun Oracle Bangalore Compliance with 2NF Employee Skill Employee Location Name Skill Raj C++ Raj C# Arun Java Arun Oracle Name Location Raj Chennai Arun Bangalore
  • 13. Third Normal Form (3NF) "the entity is in second normal form and all the attributes in a table are dependent on the primary key and only the primary key"" Against 3NF Employee Name City PIN Raj Chennai 600033 Arun Bangalore 400028 Arjun Chennai 600033 Compliance with 3NF Employee Pin Name PIN Raj 600033 Arun 400028 Arjun 600033 PIN City 600033 Chennai 400028 Bangalore Compliance with 3NF Pin
  • 14. Structured Query Language • SQL is a standard devised by ANSI • All DBMS will be following the standard and make some little alteration in it • Four categories of SQL Statements • DDL– Data Definition Language • DML– Data Manipulation Language • DCL– Data Control Language • TCL– Transaction Control Language • DRL or DQL – Data Retrieval or Query Language (With respect to user rights it belongs to DML group)
  • 15. DDL Statements • Create/Modify/ Delete the following • Table • Views • TRUNCATE records from a table
  • 16. Data types • Fixed Point Number • NUMBER (<Width>, <Decimal Places>) Input Data Specified As Stored As 7,456,123.89 NUMBER 7456123.89 7,456,123.89 NUMBER(*,1) 7456123.9 7,456,123.89 NUMBER(9) 7456124 7,456,123.89 NUMBER(9,2) 7456123.89 7,456,123.89 NUMBER(9,1) 7456123.9 7,456,123.89 NUMBER(6) (not accepted, exceeds precision) 7,456,123.89 NUMBER(7,-2) 7456100
  • 17. Data types Floating point numbers Data Type Bytes utilized Precision BINARY_FLOAT 4 7 Digits BINARY_DOUBLE 8 14 Digits
  • 18. Data types Date & Time Data Type Description Range DATE Gregorian Date 01.01.0001 to 12.31.9999 TIMESTAMP hh:mm:ss[.nnnnnnnnn]
  • 19. Data types ASCII String Data Type Description Maximum CHAR(n) Fixed length string of total length 'n' 2000 Ascii characters VARCHAR(n) Variable length string 4000 Ascii characters
  • 20. Data types Unicode String Data Type Description Maximum NCHAR(n) Fixed length string of total length 'n' 2000 Unicode characters NVARCHAR(n) Variable length string 4000 Unicode characters
  • 21. Create a Table Usage: CREATE TABLE <Table name> ( <FieldName1> <DataType> [<Constraint>], <FieldName2> <DataType> [<Constraint>], . . <FieldNameN> <DataType> [<Constraint>])
  • 22. Create a Table Constraints NOT NULL --------- Don't Allow a null value. UNIQUE --------- Values cannot be duplicated but it can allow one null value PRIMARY KEY --------- Values cannot be duplicated and even null is not allowed. CHECK ---------- Check for a condition DEFAULT ----------- Set a default value if user don't provide a value
  • 23. Create a Table… Example CREATE TABLE TblEmployee ( EmpID NUMBER(3) PRIMARY KEY, EmpFName VARCHAR2(20) NOT NULL, EmpMName VARCHAR2(20), EmpLName VARCHAR2(20) NOT NULL);
  • 24. Create a Table with named constraint CREATE TABLE TblEmployee ( EmpID NUMBER(3) CONSTRAINT pkEmpID PRIMARY KEY, EmpFName VARCHAR (20) NOT NULL, EmpMName VARCHAR (20), EmpLName VARCHAR (20) NOT NULL); ------- OR -------- CREATE TABLE TblEmployee ( EmpID NUMBER(3), EmpFName VARCHAR2(20) NOT NULL, EmpMName VARCHAR2(20), EmpLName VARCHAR2(20) NOT NULL, CONSTRAINT pkEmpID PRIMARY KEY(EmpID) ); Declare at Column Level Declare at Table Level
  • 25. Foreign Key Constraint CREATE TABLE TblDept ( DeptID NUMBER(3) PRIMARY KEY, DeptName VARCHAR2(20) NOT NULL); CREATE TABLE TblEmp( EmpID NUMBER(3), EmpName VARCHAR2(30), DeptID NUMBER(3) DEFAULT 0, CONSTRAINT pkEmpID PRIMARY KEY(EmpID), CONSTRAINT fkDeptID FOREIGN KEY (DeptID) REFERENCES TblDept(DeptID)); Default Constraint, DeptID is set to 0 if no value specified
  • 26. Foreign Key Constraint… DeptID DeptName 0 Unassigned 1 PRODUCTION 2 PURCHASE 3 SALES 4 HUMAN RESOURCES Insert the following records in TblDept Try to insert the value 5 for DeptID in TblEmp (See the error message) Now insert the following values EmpID EmpName DeptID 101 Andrews 1 102 James 3 103 Chris 4 104 Johnty 2 105 Johnson 3
  • 27. Foreign Key Constraint… Now Delete 104 from the Table TblEmp (It won't affect the Table TblDept) EmpID EmpName DeptID 101 Andrews 1 102 James 3 103 Chris 4 105 Johnson 3 DeptID DeptName 0 Unassigned 1 PRODUCTION 2 PURCHASE 3 SALES 4 HUMAN RESOURCES
  • 28. Foreign Key Constraint… Now Delete 3,Sales Department from the table TblDept (Cannot be deleted as It is referred by TblEmp) But 2, Purchase Department can be deleted as it don't have any reference. EmpID EmpName DeptID 101 Andrews 1 102 James 3 103 Chris 4 105 Johnson 3 DeptID DeptName 0 Unassigned 1 PRODUCTION 2 PURCHASE 3 SALES 4 HUMAN RESOURCES
  • 29. Foreign Key Constraint… ON DELETE CASCADE -------- All the records referring will get deleted ON DELETE SET NULL -------- Referring Field will set to NULL ON DELETE SET DEFAULT -------- Default value is assigned
  • 30. ON DELETE CASCADE ALTER TABLE TblEmp DROP CONSTRAINT fkDeptID GO ALTER TABLE TblEmp ADD CONSTRAINT fkDeptID FOREIGN KEY (DeptID) REFERENCES TblDept(DeptID) ON DELETE CASCADE Now if 3,Sales Department is deleted from the table TblDept, All the employees belonging to sales department are deleted. EmpID EmpName DeptID 101 Andrews 1 102 James 3 103 Chris 4 105 Johnson 3 DeptID DeptName 0 Unassigned 1 PRODUCTION 2 PURCHASE 3 SALES 4 HUMAN RESOURCES
  • 31. ON DELETE SET NULL ALTER TABLE TblEmp DROP CONSTRAINT fkDeptID GO ALTER TABLE TblEmp ADD CONSTRAINT fkDeptID FOREIGN KEY (DeptID) REFERENCES TblDept(DeptID) ON DELETE SET NULL Now if 3,Sales Department is deleted from the table TblDept, All the values 3 in DeptID is set to NULL. EmpID EmpName DeptID 101 Andrews 1 102 James NULL 103 Chris 4 105 Johnson NULL DeptID DeptName 0 Unassigned 1 PRODUCTION 2 PURCHASE 3 SALES 4 HUMAN RESOURCES
  • 32. ON DELETE SET DEFAULT ALTER TABLE TblEmp DROP CONSTRAINT fkDeptID GO ALTER TABLE TblEmp ADD CONSTRAINT fkDeptID FOREIGN KEY (DeptID) REFERENCES TblDept(DeptID) ON DELETE SET DEFAULT Now if 3,Sales Department is deleted from the table TblDept, All the values 3 in DeptID is set to default value (0). EmpID EmpName DeptID 101 Andrews 1 102 James 0 103 Chris 4 105 Johnson 0 DeptID DeptName 0 Unassigned 1 PRODUCTION 2 PURCHASE 3 SALES 4 HUMAN RESOURCES
  • 33. Check Constraint CREATE TABLE TblStudent( RegNo Int PRIMARY KEY, StudName Char(20) NOT NULL, Mark NUMBER(3), CONSTRAINT chkMark CHECK (Mark>=0 AND Mark <=100) ) Mark field can take the values only between 0 and 100
  • 34. Alter Table • Add a Column/Constraint • Alter a Column (Constraint cannot be altered) • Drop a Column/ Constraint Add Column ALTER TABLE TblEmp ADD EmpDOB DATE or ALTER TABLE TblEmp ADD (EmpDOB DATE,EmpDOJ DATE) Alter Column ALTER TABLE TblEmp MODIFY EmpName VARCHAR2(40) Drop Column ALTER TABLE TblEmp DROP COLUMN EmpDOB
  • 35. Drop Table Delete the entire table Usage: DROP TABLE <Table Name> Eg. DROP TABLE TblEmp Warning Table cannot be recovered
  • 36. DML Statements • Add records to the table (INSERT) • Modify the record (UPDATE) • Remove the record from the table (DELETE, TRUNCATE(DDL)) • Retrieve Information from a table (SELECT)
  • 37. INSERT INSERT INTO <TableName>(<Field1>, <Field2>,……..<Fieldn>) VALUES(<Value1>,<Value2>,……<Valuen>) • Field1 Value1, Field2 Value2 ….. Fieldn Valuen • Data type of value and field should be matched • Unspecified Fields will take NULL value or DEFAULT value as per table design • If Constraint doesn't allow a NULL value for a unspecified field the record is not inserted Alternative version: INSERT INTO <TableName> VALUES(<Value1>,<Value2>,……<Valuen>) • Values are specified in the same order as that of table's fields order • Number of values should be exactly matched
  • 38. INSERT Create the table CREATE TABLE TblProduct (ProdID NUMBER(3), ProdName VARCHAR2(20), LaunchDate Date, Unit VARCHAR2(5), PricePerUnit NUMBER(9,2)) Insert Record INSERT INTO TblProduct (ProdID,ProdName,LaunchDate,Unit,PricePerUnit) VALUES(1,'Lavera',TO_DATE('01-Jan-1998'),'50g',1.15) Or INSERT INTO TblProduct VALUES(2,'Lavera',TO_DATE('22-May-2001'),'100g',1.95)
  • 39. UPDATE UPDATE <TableName> SET <Field Name1>= <Value1>, <Field Name2>=<Value2>, . . <Field Name3>=<Value3> WHERE <Condition> Warning: If you exclude the WHERE condition, Entire records will take the given value Example Set the cost of Product 5 as $1.65 UPDATE TblProduct SET PricePerUnit=1.65 WHERE ProdID=5 Increase the cost of all products by 15 Cents UPDATE TblProduct SET PricePerUnit=PricePerUnit+0.15
  • 40. DELETE DELETE FROM <TableName> WHERE <Condition> Warning: DELETE FROM <TableName> (Without WHERE condition) will delete all the records Example Delete Product 6 DELETE FROM TblProduct WHERE ProdID=6 Delete all record DELETE FROM TblProduct Use TRUNCATE to delete all records TRUNCATE TABLE TblProduct DROP TABLE will delete entire table But TRUNCATE will delete only the records
  • 41. DELETE vs TRUNCATE S No. TRUNCATE DELETE 1 DDL Command DML Command 2 Locks the entire table before deletion Locks row by row to delete each record 3 WHERE Condition cannot be used WHERE can be used to selectively delete the records 4 Never activates a TRIGGER Activates TRIGGER ever deletion of a row 5 No. of Transactions=1 No of Transactions= No. of rows deleted 6 High speed process Slow process
  • 42. INDEX • Indexes are background objects that are used to retrieve the data fast • Updating the records slows down as the process involves updating the index Usage: CREATE INDEX <Index Name> ON <TableName> (<Field1> [ASC|DESC], <Field2>[ASC|DESC], … <Fieldn>[ASC|DESC]) Example CREATE INDEX IdxEmpName ON TblEmp(EmpLName, EmpFName) DROP an INDEX DROP INDEX <Index Name> ON <Table Name>
  • 43. SELECT CREATE TABLE TblEmpDemo ( EmpID NUMBER(3), EmpFName VARCHAR2(25), EmpLName VARCHAR2(25), Gender CHAR(1), DOB Date, DOJ Date, PayPerDay NUMBER(9,2), EmpCity VARCHAR2 (20));
  • 44. SELECT INSERT INTO TblEmpDemo VALUES (1, 'Sebastien', 'Porter', 'M', TO_DATE('21-Dec-1974'), TO_DATE( '01-Mar-1999'), 100, 'Austin'); INSERT INTO TblEmpDemo VALUES (2, 'Suzie', 'Hoak', 'F', TO_DATE( '26-Jul-1978'), TO_DATE( '15-Feb-2007') , 80, 'Denver'); INSERT INTO TblEmpDemo VALUES (3, 'Antoinette', 'Clark', 'M', TO_DATE( '07-Aug-1977') , TO_DATE( '23-Mar-2010'), 110, 'New York'); INSERT INTO TblEmpDemo VALUES (4, 'Koko', 'Domba', 'M', TO_DATE( '01-May-1984'), TO_DATE( '01-May-2011'), 85 , 'Austin'); INSERT INTO TblEmpDemo VALUES (5, 'Janet ', 'West' , 'F', TO_DATE( '14-Jan-1981') , TO_DATE( '12-Dec-1999'), 90, 'Houston'); INSERT INTO TblEmpDemo VALUES (6, 'Catherine', 'Chang', 'F', TO_DATE( '11-Apr-1979') , TO_DATE( '12-Dec-1980'), 100 , 'New York'); INSERT INTO TblEmpDemo VALUES (7, 'Nehemiah', 'Den', 'M', TO_DATE( '05-Dec-1975') , TO_DATE( '05-Jan-1994') ,120, 'Austin'); INSERT INTO TblEmpDemo VALUES (8, 'Sherryl' , 'Dsouza', 'F', TO_DATE( '08-May-1991'), TO_DATE( '03-Feb-2011'), 75, 'New York'); INSERT INTO TblEmpDemo VALUES (9, 'Santos', 'Pacheco', 'M', TO_DATE( '03-Jun-1985'), TO_DATE( '12-Jan-2005'), 90, 'Denver'); INSERT INTO TblEmpDemo VALUES (10, 'Ruby', 'DeGaram', 'F', TO_DATE( '01-Jun-1982'), TO_DATE( '01-Apr-2004'), 110, 'Houston'); INSERT INTO TblEmpDemo VALUES (11, 'Carole', 'Chance', 'F', TO_DATE( '05-Feb-1990'), TO_DATE( '05-Jan-2010'), 80, 'Houston'); INSERT INTO TblEmpDemo VALUES (12, 'Justin', 'Vittas', 'M', TO_DATE( '27-Jun-1983'), TO_DATE( '24-Jun-2004'), 100, 'New York');
  • 45. SELECT Usage: (Simple Version) SELECT <FieldName1> [AS <Alias1>], <FieldName2> [AS <Alias2>], . . <FieldNamen> [AS <Aliasn>] FROM <Table Name>
  • 46. SELECT Select all rows and all columns form the table SELECT * FROM TblEmpDemo
  • 47. SELECT Select all rows and specified columns with alias SELECT EmpID AS "Emp ID", EmpFName || EmpLName AS Name, DOB, DOJ, EmpCity AS City FROM TblEmpDemo
  • 48. SELECT Print the salary table for a month having 23 working days SELECT EmpID AS "Emp ID", EmpFName AS Name, PayPerDay*23 AS Payable FROM TblEmpDemo
  • 49. SELECT Usage: (Filtering records using WHERE) SELECT <FieldName1> [AS <Alias1>], <FieldName2> [AS <Alias2>], . <FieldNamen> [AS <Aliasn>] FROM <Table Name> WHERE <Condition> Operators Allowed in the WHERE Clause Operator Description = Equal <> Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern IN To specify multiple possible values for a column
  • 50. SELECT Select Employees whose PayPerDay is more than 100 dollars SELECT * FROM TblEmpDemo WHERE PayPerDay >= 100
  • 51. SELECT Select Employees who are from Austin SELECT * FROM TblEmpDemo WHERE EmpCity = 'Austin'
  • 52. SELECT Select Employees who are not from Austin SELECT * FROM TblEmpDemo WHERE EmpCity <> 'Austin'
  • 53. SELECT Select Employees who joined between the fiscal year 2003-04 SELECT * FROM TblEmpDemo WHERE DOJ BETWEEN TO_DATE('01-Oct-2003') AND TO_DATE('30-Sep-2004')
  • 54. SELECT Select Employees whose first name starting with S SELECT * FROM TblEmpDemo WHERE EmpFName LIKE 'S%'
  • 55. SELECT Select Employees whose first name having second letter a SELECT * FROM TblEmpDemo WHERE EmpFName LIKE '_a%'
  • 56. SELECT Select Employees whose first name having second letter a SELECT EmpFName,EmpCity FROM TblEmpDemo WHERE EmpCity IN ('Denver','Houston') EMPFNAME EMPCITY ------------------------- -------------------- Suzie Denver Janet Houston Santos Denver Ruby Houston Carole Houston
  • 57. SELECT SELECT (ORDER BY) Usage: (Grouping records using ORDER BY) SELECT <FieldName1> [AS <Alias1>], <FieldName2> [AS <Alias2>], . <FieldNamen> [AS <Aliasn>] FROM <Table Name> ORDER BY <FieldName> [ASC|DESC]
  • 58. SELECT Select Employees in the order of DOB (Eldest first) SELECT * FROM TblEmpDemo ORDER BY DOB
  • 59. SELECT Select Employees in the order of DOB (Youngest First) SELECT * FROM TblEmpDemo ORDER BY DOB DESC
  • 60. SELECT Select Employees in the order of PayPerDay and DOJ (If PayPerDay is repeated then it uses the DOJ to select the next record) SELECT * FROM TblEmpDemo ORDER BY PayPerDay, DOJ
  • 61. SELECT SELECT DISTINCT Usage: (Delist the duplicate value) SELECT DISTINCT <FieldName1> [AS <Alias1>], <FieldName2> [AS <Alias2>], . <FieldNamen> [AS <Aliasn>] FROM <Table Name>
  • 62. SELECT List all the cities from which our Employees from SELECT DISTINCT EmpCity FROM TblEmpDemo List all the cities from which our Employees from and also separate gender wise SELECT DISTINCT EmpCity, Gender FROM TblEmpDemo From Austin and Houston, We have only MALE Employee(s) From Denver and New York, Both MALE and FEMALE exists
  • 63. SELECT SELECT (Using function) • COUNT - Count the records with respect to some condition • SUM - Applied for a numerical field, to sum the existing values • AVG - Compute the average of all the values • MIN - Find the minimum value of a field • MAX - Get the maximum
  • 64. SELECT Count all the employees we have SELECT COUNT(*) AS EmpCount FROM TblEmpDemo Count all the Male employees we have SELECT COUNT(*) AS MaleEmpCount FROM TblEmpDemo WHERE Gender='M' Count the total number of cities we have employees from SELECT COUNT(DISTINCT EmpCity) AS CityCount FROM TblEmpDemo
  • 65. SELECT Find total amount paid all the employees per day SELECT SUM(PayPerDay) AS TotalPay FROM TblEmpDemo Find the average pay of male employees SELECT AVG(PayPerDay) AS MaleAvgPay FROM TblEmpDemo WHERE Gender='M' Find the Max pay SELECT MAX(PayPerDay) AS MaxPay FROM TblEmpDemo
  • 66. SELECT SUB-QUERIES or NESTED QUERIES A query that exists within another query is called subquery A subquery nested in the outer SELECT statement has the following components: • A regular SELECT query including the regular select list components. ⁻ Using a SELECT statement as a column name • A regular FROM clause including one or more table or view names. ⁻ Getting Data from multiple tables, similar to JOINS ⁻ Also known as EQUI JOIN • An optional WHERE clause. ⁻ Using SELECT statement in the WHERE clause • An optional GROUP BY clause. • Using Aggregate function in columns and group by a particular field • An optional HAVING clause • Further filter the result after applying the GROUP BY clause
  • 67. SELECT CREATE TABLE AccMaster( AccNo Char(5), FName VARCHAR2(25), LName VARCHAR2 (25), Gender CHAR(1), RefAccNo CHAR(5), OpenDate DATE, CurrBal NUMBER(9,2), CONSTRAINT pkAccNo PRIMARY KEY(AccNo)); CREATE TABLE AccTrans( TransID NUMBER(5), TransDate DATE, AccNo CHAR(5), Amount NUMBER(9,2), TransType CHAR(1), CONSTRAINT pkTransID PRIMARY KEY(TransID), CONSTRAINT fkAccNo FOREIGN KEY(AccNo) REFERENCES AccMaster(AccNo));
  • 68. SELECT INSERT INTO AccMaster VALUES ('56001', 'James', 'Carlton', 'M', NULL, TO_DATE('05-Oct-2005'),1500); INSERT INTO AccMaster VALUES ('56002','Chrissy','Arlene','F','56001', TO_DATE('04- Jan-2006'),1200); INSERT INTO AccMaster VALUES ('56003','Eldridge','Powers','M','56001', TO_DATE('24-Jul-2006'),1700); INSERT INTO AccMaster VALUES ('56004', 'Hobert', 'Spampinato', 'M', '56002', TO_DATE('21-Feb-2007'),1300); INSERT INTO AccMaster VALUES('56005','Gloria','Wright','F','56003', TO_DATE('07- Apr-2008'),1900);
  • 69. SELECT INSERT INTO AccTrans VALUES (1, TO_DATE('05-Oct-2005'),'56001',500,'D'); INSERT INTO AccTrans VALUES (2, TO_DATE('01-Dec-2005'),'56001',1500,'D'); INSERT INTO AccTrans VALUES (3, TO_DATE('04-Jan-2006'),'56002',2000,'D'); INSERT INTO AccTrans VALUES (4, TO_DATE('05-Feb-2006'),'56001',400,'W'); INSERT INTO AccTrans VALUES (5, TO_DATE('15-Feb-2006'),'56002',200,'W'); INSERT INTO AccTrans VALUES (6, TO_DATE('24-Jul-2006'),'56003',1000,'D'); INSERT INTO AccTrans VALUES (7, TO_DATE('15-Aug-2006'),'56001',100,'W'); INSERT INTO AccTrans VALUES (8, TO_DATE('29-Aug-2006'),'56002',200,'D'); INSERT INTO AccTrans VALUES (9, TO_DATE('12-Sep-2006'),'56003',300,'W'); INSERT INTO AccTrans VALUES (10, TO_DATE('23-Dec-2006'),'56002',800,'W'); INSERT INTO AccTrans VALUES (11, TO_DATE('21-Feb-2007'),'56004',2000,'D'); INSERT INTO AccTrans VALUES (12, TO_DATE('10-Mar-2007'),'56004',200,'W'); INSERT INTO AccTrans VALUES (13, TO_DATE('01-Apr-2008'),'56004',1000,'D'); INSERT INTO AccTrans VALUES (14, TO_DATE('07-Apr-2008'),'56005',100,'D'); INSERT INTO AccTrans VALUES (15, TO_DATE('01-Feb-2009'),'56004',1900,'W'); INSERT INTO AccTrans VALUES (16, TO_DATE('01-May-2009'),'56005',100,'D'); INSERT INTO AccTrans VALUES (17, TO_DATE('01-Jan-2010'),'56005',700,'D');
  • 70. SELECT Include the sub-query as a list component List all the account holders name along with the referrers name. SELECT A.AccNo,A.FName, (SELECT B.FName FROM AccMaster B WHERE A.RefAccNo = B.AccNo) FROM AccMaster A
  • 71. SELECT SELECT query involving more than one table List all the Transactions and also include the account holder name. SELECT A.TransID ,A.AccNo,B.FName,A.TransType,A.Amount FROM AccTrans A,AccMaster B WHERE A.AccNo=B.AccNo SELECT AccTrans.TransID ,AccTrans.AccNo,AccMaster.FName,AccTrans.TransType,AccTrans.Amount FROM AccTrans ,AccMaster WHERE AccTrans.AccNo=AccMaster.AccNo SELECT TransID ,AccTrans.AccNo,FName,TransType,Amount FROM AccTrans ,AccMaster WHERE AccTrans.AccNo=AccMaster.AccNo This technique is also known as EQUI JOIN
  • 73. SELECT WHERE…IN.. (Check if the value exist in the list) Find the Employee who is getting highest pay. SELECT EmpID,EmpFName,PayPerDay FROM TblEmpDemo WHERE PayPerDay IN (SELECT MAX(PayPerDay) FROM TblEmpDemo)
  • 74. SELECT WHERE…NOT IN.. (Check if the value not exist in the list) Find the Customer who never made any transaction in the year 2006 SELECT AccNo,FName FROM AccMaster WHERE AccNo NOT IN (SELECT AccNo FROM AccTrans WHERE TO_CHAR(TransDate,'YYYY')='2006')
  • 75. SELECT WHERE..ALL/ SOME/ ANY • A relational operator can be used to compare with….. • ALL ---- All the values (internally AND operation) • ANY or SOME ---- At least One value (internally OR operation) List employees whose salary are above average SELECT * FROM TblEmpDemo WHERE PayPerDay >= ALL (SELECT AVG(PayPerDay) FROM TblEmpDemo)
  • 76. SELECT GROUP BY & HAVING GROUP BY clause used to apply an aggregate function (SUM, AVG, MAX..) with respect to some field Eg. Total transaction by each customer (both credit and debit) SELECT AccNo, SUM(Amount) FROM AccTrans GROUP BY AccNo WHERE can be used to apply filter before aggregation Total deposit done by each customer SELECT AccNo, SUM(Amount) FROM AccTrans WHERE TransType='D' GROUP BY AccNo HAVING can be used to apply filter after aggregation List of customers those who done total deposits more than Rs.1500 SELECT AccNo, SUM(Amount) FROM AccTrans WHERE TransType='D' GROUP BY AccNo HAVING SUM(Amount) >= 1500
  • 77. JOINS JOINS Inner Join Outer Join Left Outer Join Right Outer Join Full Outer join Cross join
  • 78. INNER JOIN This join returns rows when there is at least one match in both the tables.
  • 79. INNER JOIN SalesEmp EmpID EmpName 1 Hansen 2 Svendson 3 Pettersen Orders OrderID OrderNo EmpID 1 77895 3 2 44678 3 3 22456 1 4 24562 1 5 34762 7 SELECT SalesEmp.EmpName, Orders.OrderNo FROM SalesEmp INNER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID EmpName OrderNo Hansen 22456 Hansen 24562 Pettersen 77895 Pettersen 44678
  • 80. LEFT OUTER JOIN This join returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values. If WHERE condition is included saying, right table's column is null then, it will return only the rows which don't have a match
  • 81. LEFT OUTER JOIN …. SalesEmp EmpID EmpName 1 Hansen 2 Svendson 3 Pettersen Orders OrderID OrderNo EmpID 1 77895 3 2 44678 3 3 22456 1 4 24562 1 5 34762 7 SELECT SalesEmp.EmpName, Orders.OrderNo FROM SalesEmp LEFT OUTER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID EmpName OrderNo Hansen 22456 Hansen 24562 Svendson NULL Pettersen 77895 Pettersen 44678
  • 82. LEFT OUTER JOIN.. WHERE NULL SalesEmp EmpID EmpName 1 Hansen 2 Svendson 3 Pettersen Orders OrderID OrderNo EmpID 1 77895 3 2 44678 3 3 22456 1 4 24562 1 5 34762 7 SELECT SalesEmp.EmpName, Orders.OrderNo FROM SalesEmp LEFT OUTER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID WHERE Orders.EmpID IS NULL EmpName OrderNo Svendson NULL
  • 83. RIGHT OUTER JOIN This join returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values. If WHERE condition is included saying, left table's column is null then, it will return only the rows which don't have a match
  • 84. RIGHT OUTER JOIN …. SalesEmp EmpID EmpName 1 Hansen 2 Svendson 3 Pettersen Orders OrderID OrderNo EmpID 1 77895 3 2 44678 3 3 22456 1 4 24562 1 5 34762 7 SELECT SalesEmp.EmpName, Orders.OrderNo FROM SalesEmp RIGHT OUTER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID EmpName OrderNo Hansen 22456 Hansen 24562 Pettersen 77895 Pettersen 44678 NULL 34762
  • 85. RIGHT OUTER JOIN WHERE NULL …. SalesEmp EmpID EmpName 1 Hansen 2 Svendson 3 Pettersen Orders OrderID OrderNo EmpID 1 77895 3 2 44678 3 3 22456 1 4 24562 1 5 34762 7 SELECT SalesEmp.EmpName, Orders.OrderNo FROM SalesEmp RIGHT OUTER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID WHERE SalesEmp.EmpID IS NULL EmpName OrderNo NULL 34762
  • 86. FULL OUTER JOIN This join combines left outer join and right outer join. It returns row from either table when the conditions are met and returns null value when there is no match. If WHERE condition is included saying, left table's or left table's column is null then, matching records are ignored
  • 87. FULL OUTER JOIN SalesEmp EmpID EmpName 1 Hansen 2 Svendson 3 Pettersen Orders OrderID OrderNo EmpID 1 77895 3 2 44678 3 3 22456 1 4 24562 1 5 34762 7 SELECT SalesEmp.EmpName, Orders.OrderNo FROM SalesEmp FULL OUTER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID EmpName OrderNo Hansen 22456 Hansen 24562 Pettersen 77895 Pettersen 44678 NULL 34762 Svendson NULL
  • 88. FULL OUTER JOIN SalesEmp EmpID EmpName 1 Hansen 2 Svendson 3 Pettersen Orders OrderID OrderNo EmpID 1 77895 3 2 44678 3 3 22456 1 4 24562 1 5 34762 7 SELECT SalesEmp.EmpName, Orders.OrderNo FROM SalesEmp FULL OUTER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID WHERE SalesEmp.EmpID IS NULL OR Orders.EmpID IS NULL EmpName OrderNo NULL 34762 Svendson NULL
  • 89. CROSS JOIN …. Alpha AlphaCol A B C Numerals NumCol 1 2 3 SELECT Alpha.AlphaCol,Numerals.NumCol FROM Alpha CROSS JOIN Numerals AlphaCol NumCol A 1 A 2 A 3 B 1 B 2 B 3 C 1 C 2 C 3
  • 90. UNION & UNION ALL Alpha AlphaCol A B C Numerals NumCol 1 2 3 SELECT AlphaCol FROM Alpha UNION SELECT NumCol FROM Numerals AlphaCol A B C 1 2 3 Note: First tables column Name(s) will be taken UNION will list only distinct values UNION ALL will list all values even if duplicate exists
  • 91. Practical Learning(I) ID Name Age Salary 1 Abe 61 140000 2 Bob 34 44000 5 Chris 34 40000 7 Dan 41 52000 8 Ken 57 115000 11 Joe 38 38000 ID Name City Industry Type 4 Samsonic pleasant J 6 Panasung oaktown J 7 Samony jackson B 9 Orange Jackson B Number order_date cust_id salesperson_id Amount 10 8/2/96 4 2 540 20 1/30/99 4 8 1800 30 7/14/95 9 1 460 40 1/29/98 7 2 2400 50 2/3/98 6 7 600 60 3/2/98 6 7 720 70 5/6/98 9 7 150 Orders SalesEmp Customer
  • 92. Practical Learning(I) Write a query to find… a. The names of all salespeople that have an order with Samsonic. b. The names of all salespeople that do not have any order with Samsonic. c. The names of salespeople that have 2 or more orders.
  • 93. Practical Learning(II) User UserID UserName PhoneNum LoginHistory UserID LoginDate 1. Write a SQL query that returns the name, phone number and most recent date for any user that has logged in over the last 30 days 2. Write a SQL query to determine which user had never logged in before
  • 94. VIEWS • View is a virtual table that contains columns from one or more tables • View is an precompiled object, which holds a query. • It can be used as a table for another query. • Used to reduce the complexity of large queries CREATE VIEW EmpOrders AS SELECT SalesEmp.EmpName, Orders.OrderNo FROM SalesEmp INNER JOIN Orders ON SalesEmp.EmpID=Orders.EmpID
  • 95. VIEWS Select VIEW like a table SalesEmp EmpID EmpName 1 Hansen 2 Svendson 3 Pettersen Orders OrderID OrderNo EmpID 1 77895 3 2 44678 3 3 22456 1 4 24562 1 5 34762 7 SELECT * FROM EmpOrders EmpName OrderNo Hansen 22456 Hansen 24562 Pettersen 77895 Pettersen 44678
  • 96. PL/SQL • Programming language of Oracle • PL/SQL stands for Procedural Language / Structured Query Language • Developed by oracle to enhance the features of SQL • PL/SQL Modules can be executed from SQL Plus or even from any front end (Java) • Front end developers can expect better performance when compared to sending a raw DML statement over a network (PL/SQL program is a precompiled and become a part of database)
  • 97. PL/SQL /* Simple PL/SQL program */ DECLARE message varchar2(20):= 'Hello, World!'; BEGIN dbms_output.put_line(message); END; /
  • 98. PL/SQL /* Accessing Tables in PL/SQL */ DECLARE mProdID TblProduct.ProdID%TYPE; mProdName TblProduct.ProdName%TYPE; BEGIN SELECT ProdID,ProdName INTO mProdID,mProdName FROM TblProduct WHERE ProdID=2; dbms_output.put_line('Product ID=' || mProdID || ' Product Name=' || mProdName); END; / Create variables with data type compatible with the table's field data type
  • 99. STORED PROCEDURES • Stored Procedure is a sequence of sql code (program) which can be called whenever required • It can take parameters (input/ output) • When created, it becomes part of the database and pre-compiled CREATE OR REPLACE PROCEDURE <Procedure Name> ([<Param1> <Data Type> [IN | OUT | IN OUT]] [<Param2> <Data Type> [IN | OUT | IN OUT]] …. [<ParamN> <Data Type> [IN | OUT | IN OUT]]) IS [<Variable1> <Data Type>] [<Variable2> <Data Type>] ….. [<VariableN> <Data Type>] BEGIN <Code> END
  • 100. STORED PROCEDURES CREATE OR REPLACE PROCEDURE ListCustomer IS mAccNo AccMaster.AccNo%type; mFName AccMaster.FName%type; mCurrBal AccMaster.CurrBal%type; CURSOR cAccMaster IS SELECT AccNo, FName, CurrBal FROM AccMaster; BEGIN OPEN cAccMaster; dbms_output.put_line('Acc No Name Balance'); LOOP FETCH cAccMaster into mAccNo, mFName, mCurrBal; EXIT WHEN cAccMaster%notfound; dbms_output.put_line(mAccNo || ' ' || mFName || ' ' || mCurrBal); END LOOP; CLOSE cAccMaster; END; / Execute this procedure by >EXEC ListCustomer
  • 101. STORED PRCEDURE Assignment Consider the banking database AccMast and AccTrans Create a procedure called DoTrans taking parameter Account No, Amount, Type ('D'/'W') • Generate TransID • Insert record in AccTrans • Update the AccMast, the current balance of the specified account number
  • 102. FUNCTIONS CREATE FUNCTION <Function Name> ([<Param1> <Data Type>], [<Param2> <Data Type>], …. [<ParamN> <Data Type>]) RETURNS <Data Type> AS BEGIN <Code> RETURN <Variable> |<Value> END; /
  • 103. FUNCTIONS CREATE OR REPLACE FUNCTION totalCustomers RETURN number IS total number(2) := 0; BEGIN SELECT count(*) into total FROM AccMaster; RETURN total; END; / Execute this function by >select totalcustomers() from dual
  • 104. STORED PROCEDURE vs FUNCTIONS Sl. No. Stored Procedure Functions 1 SP can return multiple values Function can return only one value 2 Transaction is allowed (INSERT/ UPDATE/ DELETE) Transaction not allowed 3 It can have input & output parameter Only input parameter 4 SP can call a function and another SP Function can call another function but not a stored procedure 5 Exception Handling is supported Not supported
  • 105. TRIGGERS • Triggers are special kind of stored procedures that executes in response to certain database action like INSERT/ UPDATE/ DELETE • Triggers cannot be explicitly invoked like SP or Functions • Types of Triggers • BEFORE INSERT|UPDATE|DELETE ---- Fired before the given process • AFTER INSERT|UPDATE|DELETE ---- Fired after the process
  • 106. TRIGGERS Consider an example in the employee table, we are maintaining a separate table for the relieved, TblOldEmpDemo CREATE TABLE TblOldEmpDemo ( EmpID NUMBER(3), EmpFName VARCHAR2(25),Gender CHAR(1),DOR DATE) CREATE OR REPLACE TRIGGER TrgDeleteEmp AFTER DELETE ON TblEmpDemo FOR EACH ROW BEGIN INSERT INTO TblOldEmpDemo VALUES (:Old.EmpID,:Old.EmpFName,:Old.Gender, SYSDATE); END; /