0% found this document useful (0 votes)
23 views

DPA Lecture 4

Uploaded by

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

DPA Lecture 4

Uploaded by

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

L7 Data Processing and Analytics

Lecture 4: SQL and Transactions

Dr Ismail Alarab
[email protected]

www.bournemouth.ac.uk
Recap

- Creating, Deleting, Truncating, Altering Tables


- Data Types and Column Constraints
- Manipulating Data (Inserting, deleting)
- Retrieving Data (Select from)
- Aggregate Functions
- Conditional Columns
Unit Attendance

Scan Me!
Lecture Outline

➢Data Retrieval
➢Complex queries
➢Joins
➢Views
➢Security
➢Indexes
➢Data Dictionaries
➢Transactions
Complex Queries
Complex Queries

• Queries involving subqueries

• Subqueries realized as (<subquery>)

• Uncorrelated (simple) subqueries


– Subquery can run independently of main query

• Correlated subqueries
– Subquery depends on a value from parent query – cannot run independently
Subqueries

Who has a salary greater than Abel’s?


Subquery Syntax

► The subquery (inner query) executes once before the main query.

► The result of the subquery is used by the main query (outer query).
Using a Subquery
Subquery Rules

► Enclose subqueries in parentheses.


► Place subqueries on the right side of the comparison
condition.
► Use single-row operators with single-row subqueries and
use multiple-row operators with multiple-row subqueries.
Subqueries

select empno, ename from emp where sal > (select


avg(sal) from emp); Uncorrelated subquery
• Lists numbers and names of employees, whose salary is higher
than the average salary
Table alias

select empno, ename from emp emp1 where sal >


(select avg(sal) from emp where deptno =
emp1.deptno);
• Lists numbers and names of employees, whose salary is higher
than the average salary in their department Correlated subquery
Types of Subqueries
Single Row Subqueries

• Return only one row


• Use single-row comparison operators
“Having” Clause in Subqueries

• The Oracle server returns results into the HAVING clause of the main
query.
Multiple Row Subqueries

• Return more than one row


• Use multiple-row comparison operators
ANY Operator in Multiple-Row Subqueries
ALL Operator in Multiple-Row Subqueries
IN Operator in Multiple-Row Subqueries
Multiple-Table Queries

• Getting data from different tables, usually related by a


primary/foreign key relationship

• Usually called Joining

• Many ways of realising in SQL


– WHERE

– JOIN

– IN

– EXISTS
Obtaining Data From Multiple Tables
Cartesian Product
JOINS
“JOIN”

• (INNER) JOIN: Returns records that have matching values in


both tables
• LEFT (OUTER) JOIN: Return all records from the left table,
and the matched records from the right table
• RIGHT (OUTER) JOIN: Return all records from the right table,
and the matched records from the left table
• FULL (OUTER) JOIN: Return all records when there is a match
in either left or right table
Joining Tables

• Use a join to query data from more than one table.

• Write the join condition in the WHERE clause.


• Prefix the column name with the table name when the same column
name appears in more than one table.
INNER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
Branch Property
Branch (bNo, bCity) bNo bCity pNo pCity
Property (pNo, pCity) B003 Glasgow PA14 Aberdeen
B004 Bristol PL94 London
B002 London PG4 Glasgow

Full Outer Join


select * from Branch full join Property on
bCity = pCity
bNo bCity pNo pCity
B003 Glasgow PG4 Glasgow
B004 Bristol NULL NULL
B002 London PL94 London
NULL NULL PA14 Aberdeen
Joining More than Two Tables

To join n tables together, you need a minimum of n-1 join


conditions. For example, to join three tables, a minimum of two
joins is required.
Multiple Tables Queries

select ename from dept, emp where dept.deptno=emp.deptno


and dname='RESEARCH'
select ename from emp where deptno in
(select deptno from dept where dname='RESEARCH')

select ename from emp where exists (select * from dept


where dept.deptno=emp.deptno and dname='RESEARCH')

• List names of Research department's employees using JOIN, WHERE, IN


and EXISTS
Self Join
Self Join

Joining table to itself

• List names of all employees and their managers


select emp1.ename as manager, emp2.ename as employee
from emp emp1, emp emp2
where emp1.mgr(+)=emp2.empno

• Note manager and employee aliases


Using Tables Aliases

• Simpify queries by using table aliases.


Set Operations

Select all names and numbers of all salesmen and all employees
from departments based in Chicago
UNION (same to OR, can be faster)
select empno, ename from emp where job='SALESMAN‘
union
select empno, ename from emp, dept where
dept.deptno=emp.deptno and loc='CHICAGO'

INTERSECT: Intersection of two sets (same to AND, can be


faster)
MINUS: Difference of two sets (same to AND NOT, can be
faster)
Dates In Oracle

• SQL2003 standard includes Date datatype for dates and


Datetime datatype for dates and time.
• Oracle has Date and Timestamp datatypes, both of whichcan
include date and time (Timestamp additionally includes
timezone information).
• Dates can be input in standard date format DD-Month-YY or
using to_date conversion function from other date formats.
• Simple comparisons can be made with =, <, > operators
Oracle Built-In Functions

• Numeric Functions (abs, round, etc.)


• Character Functions (concat, trim, etc.)
• Datetime functions
• Conversion functions

More below:
https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions001.htm
Managing a Database

• Creating views

• Security

• Indexes

• Data dictionary
Views
Views

• Views are “virtual” tables, which are created on the runtime using
the stored query.
• Views themselves do not contain data. They just act as a window
through which certain (not all) contents of a table can be viewed.
Create View

For example, suppose we want that the saleperson in your office


should not have access to the details of the salaries of the other
employees, but he needs such information as Emp_Name, Job and
Dept_Name. Then, we can create a view for the salesperson. This view
will contain only the required information and nothing more than that.
Similarly, we can create a view for the Manager, containing the
information, which he needs.
Syntax:
CREATE OR REPLACE VIEW <View Name> As <SELECT Statement>;

CREATE OR REPLACE VIEW salesperson AS


SELECT empno, ename, job, dname from emp,dept
WHERE emp.deptno=dept.deptno;
Create View
Define a view, CustCredLimit, that consists of a credit
limit(cLimit) and the number of customers who have this
limit (noOfCust):
create view CustCredLimit (cLimit, noOfCust) as
select creditLimit, count(custNo)
from Customer
group by creditLimit
Drop View
Remove the Appliance view from the database:
drop view Appliance
Advantages of Views

• Provide data independence (provided that the base tables are


changed in such a way that the view can still be derived from
the existing data)

• The same data can be viewed by different users in different


ways.

• Simplify the user's perception of the database.

• Provide a measure of security.

Note:The above advantages hold when views are used


for retrieval purposes only.
Views

• Rows can normally be inserted into, updated or deleted from a base table
using a view, subject to the following restrictions:
• If the view query contained SET, DISTINCT or GROUP BY or an aggregate
or analytic function, the base tables cannot be modified using the view.
• If the view query contains WITH CHECK OPTION, a row cannot be
inserted or updated if the view is unable to select the row.
• If there is a NOT NULL column, a row can only be inserted if a value is
supplied for that column in the INSERT command, or if a DEFAULT value
is specified in the CREATE TABLE command.
Sequences

A sequence is a database object used to generate sequence numbers for


rows in the tables. It can be used for producing unique primary key values. A
sequence is created using the CREATE SEQUENCE command.

CREATE SEQUENCE <Sequence_name>


[INCREMENT BY <integervalue>]
[STARTWITH <integervalue>]
[MINVALUE <integervalue>/NOMINVALUE]
[MAXVALUE <integervalue>/NOMAXVALUE];
[CYCLE/ NOCYCLE];
Sequence Creation

CREATE SEQUENCE Empcode Increment By 2 Start With 100;

INCREMENT BY clause is optional.


The default value for increment is 1.
NEXTVAL - to extract the next number in line from a specified sequence.
CURRVAL – to extract the current sequence number.

SELECT EmpCode.Nextval From Dual;

Insert into emp (empno, ename, job, doj, sal, deptno) Values (Empcode.nextval, ‘Mini’,
‘Manager’, ’12-MARO4’, 7000,10) ;
Security
Security

• SQL access control is built around the concepts of authorisation


identifiers, ownership and privileges.
• Authorisation identifiers are assigned to the database users by the DBA and
identify a user.
• Each object that is created in SQL has an owner.
• The owner can pass privileges to other users using the grant statement and
can revoke the privileges passed on using the revoke statement.
• The privileges that can be passed on are: select, delete, insert, update
and references.

grant { privilegeList | all }


on ObjectName
to { AuthorisationList | public }
Security

User Jones must be able to retrieve data from the SalesRep table:
grant select on SalesRep to Jones
Users Smith and Brown must be able to add new parts:
grant insert on Part to Smith, Brown

User Anderson must be able to change the name or address of


customers:
grant update on Customer (custName, custAddress) to Anderson

All users must be able to retrieve part numbers, description and


categories:
grant select on Part (partNo, description, category) to public

User Wilson must be able to change the structure of the Customer


table:
grant alter on Customer to Wilson
Security

User Wilson must have all privileges on the SalesRep, Customer


and Order tables:
grant all on SalesRep, Customer, Order to Wilson

Permit sales rep 3 (Mary Jones) to access any data concerning her customers
but do not permit her to access data concerning any other customers:

create view MJCustomers as


select *
from Customer
where repNo = 3

grant select on MJCustomers to Mary Jones


User Wilson is no longer allowed to retrieve data from the SalesRep table:
revoke select on SalesRep from Wilson
Indexes
Indexes
• Index is a way to store and search records in the table.
• Indexes are used to improve the speed with which the records can be located
and retrieved from the table.
• The index of a table is a separate file that has two columns:
1. A column on which the index is created.
2. The number of the record in which the corresponding row is found.
With this ROWID, Oracle can search for the data on disk rapidly.
• Makes certain types of retrieval more efficient.
• Occupies additional disk space.
• Must be updated whenever corresponding data is updated.
• Suitable for large tables or tables with frequent read operations, so indexes
will reduce the amount of data that needs to be scanned.
• Reduce the FULL TABLE SCAN
Create Index
Create a unique index (it does not allow duplicate values for
indexed columns) called CustInd1 on the custNo column of the
Customer table:
create unique index CustInd1 on Customer (custNo)

Create an index called CustInd2 on the repNo column of the


Customer table:
create index CustInd2 on Customer (repNo)

Create an index for the Customer table on the combination of


descending credit limit and customer name:
create index CustInd3 on Customer (creditLimit desc,
custName)

Delete index CustInd1: drop index CustInd1


Data Dictionaries
Oracle Data Dictionary
• A collection of tables and views which acts as a reference guide
the information content of the entire database

• The view DICTIONARY (DICT) acts as a contents listing for the


data dictionary

• Use select to retrieve information from the data dictionary

• Sample tables and views:


– USER_CONSTRAINTS
– USER_TABLES
– ALL_VIEWS
– ALL_INDEXES
Transactions
Transactions

DBMS uses the idea of transactions to manage the operation


of a database.

Definition
– "A collection of operations that performs a single
logical function in a database application." (Korth)

It could be a single SQL command, a collection of SQL


commands, or an entire program.
Example

Money transfer between two bank accounts.

Consists of two update operations.


■ Remove money from account A
■ Add money to account B.

The database is:


■ in a consistent state before the first operation
■ in a consistent state after the second operation
Example
What happens if the computer system fails after the first
update operation, but before the second?

A DBMS must be able to guarantee that :


– all of the operations in the transaction complete
successfully,
or that
– none of them complete successfully.

Therefore: A transaction is a group of operations that are


treated as a unit as far as the users of the database are
concerned.
Problems

Computer systems fail because of?


– Software errors
– Hardware errors
– Communication errors
– Conflicting programs
– Malicious damage

A DBMS must survive a system failure, because


– It must not lose data
– It must be left in a consistent state
What does that mean for transactions?

The DBMS has no way of knowing which operations are


grouped into transactions.

It has to be told by the user (or the user's program).


SQL provides the following commands for this:
■ COMMIT
■ ROLLBACK

The first valid SQL command will start a transaction,


and it ends with a COMMIT
Results

Transactions have two possible outcomes


– Commit
• A successful transaction is committed, putting the database
into a new consistent state.
• All changes to the database are permanent.
• They can now be seen by other users of the database.
– Rollback
• A failed transaction is rolled back, returning the database to
the last consistent state.
• All changes to the database since the last commit are
undone.
● DDL statements (ALTER and CREATE) will COMMIT any open
transactions before executing.
Ideal Properties for a transaction (ACID)

Atomicity
– A transaction is treated as indivisible.
– Other users never see the results of a partially completed
transaction.

Consistency
– A transaction takes a database from one consistent state to
another.
– During a transaction, the database does not need to be
consistent.
Ideal Properties of a transaction (ACID)

Isolation / Independence
– Transactions are kept isolated from all other transactions until
they either commit or rollback.

Durability
– Changes made during a transaction are permanent once the
transaction commits.
Further Reading

Connolly & Begg chapters 6, 8, 2

Oracle documentation
https://docs.oracle.com/database/121/CNCPT/sqllangu.htm#CNCPT015
Questions?

You might also like