Sei sulla pagina 1di 53

H2O Overview

TEST & DEVELOP


ENVIRONMENT

PRODUCTION
ENVIRONMENT
PRE-PRODUCTION
ENVIRONMENT

ORABE

WEBLOGIC WEBLOGIC_DBA
OraGP

OraMON PORT01
OraBE
CARTE
Ora121 CARTE_DBA

DATABASES
Database users

OWNER USERS They contain all database objects and they must not have
privileges (e.g. weblogic_dba and carte_dba). Generally they
are locked.
APPLICATIVE USERS They have only the grant to a role through which they have
the system privilege of CREATE SESSION and they can
manipulate the objects of related owner schema.
DEVELOP USERS They have all the necessary privileges through CONNECT
and RESOURCE roles. They also be able to manipulate test
objects.

WEBLOGIC_DBA WLROLE WEBLOGIC AS

Passwords of applicative and develop users expire every 45 days and after
expiry date there are 5 days to change it (through an 8i or higher client). The
sixth day users will be lockes automatically. This is the tipical profile.
Database objects

„ TABLES are the basic units for data storage in the


database.
„ VIEWS are customized presentations of data from one or
more tables. They provide an additional security
level reducing the informations that can be
visualized. They are managed like tables.
„ MATERIALIZED VIEWS are used to replicate data in distributed
environments and syncronize the updates.
„ INDEXES are optional structures that allow performance
improvement of queries.
„ SEQUENCES are generators of sequencial numbers. They are
usefull to generate unique number in multi-user
environments.
„ SYNONYMS are alias for database objects.
„ PL/SQL BLOCKS they provides an isolation level between
application and database (we will see them later).
Default Grants & Synonyms
According to personal requirement, owner schemas can have default
synonyms and grants for every new objects.

OBJECTS GRANTS SYNONYMS

Function – procedure – package execute yes

Table select, insert,update,delete yes

Sequence select yes

View select no

„ GRANTS are done to a role


„ SYNONYMS are created for the applicative user.
Principles of Relational Model
The basic unit of a relational database is the TABLE. Every table represents a
logical entity, while the contraints represent relations between the tables. Tables
must be normalized, in order to have a managable and efficient structure, both in
term of performance and in term of space usage.

CODE LAST_NAME FIRST_NAME ... DEPT_ID DEPT_NAME ... ... ...

EMPLOYEE DEPARTMENT

At table level it is possible to define some integrity constraints that allow to


associate to every table some logical rules. 1
Integrity Constraints

„ PRIMARY KEY PK identifies a row uniquely. PK can be composed by more


than one column, but it is better short ones.

CODE LAST_N FIRST_ ... DEPT_ID DEPT_ID DEPT_N ... ... ...

PK EMPLOYEE FK PK DEPARTMENT

„ FOREIGN KEY FK is a relation between two tables. A foreign key can be null,
but it must reference a unique or primary key. If referenced
key is composite, foreign key must have the same structure.
Integrity Constraints

„ UNIQUE KEY While PK is a functional constraint, UQ is used to define


application logic. UQ must be unique but it allows null
values.

„ NOT NULL By default every column can be NULL, otherwise a not null
constraint can be defined on a column.

„ CHECK KEY CK allows forcing an integrity rule based on a logical


expression, that can’t be achieved through the other kind
of constraints.

Don’t re-invent database functionalities (e.g. integrity


constraints or built-in functions), but let the database
do what it does best.
Using SQL

„ Structured Query Language (SQL) is the set of statements using


which all programs and users access data in an Oracle database.

„ The purpose of SQL is to provide an interface to a relational


database and all SQL statements are instructions to the database.

„ SQL differs from general-purpose programming languages like C


and BASIC.

„ A complete Oracle documentation is aviable at link


http://dcorats/oradoc/
SQL Data Types
Each literal or column value manipulated by Oracle has a data type.

CHAR (size) Used to store fixed length character data of length size. Max size
size is 2000 bytes.

VARCHAR2 (size) Used to store a variable-


variable-length character string having maximum length size
bytes. The maximum size is 4000 bytes
NUMBER (p, s) Used to store a number having a precision p and scale s. p is the
the total length
of numbers excluding the decimal and s is the maximum number of digits after
the decimal. The maximum precision is 38.
DATE Used to store dates (and times). Valid dates range from 01/01/4712
01/01/4712 BC to
31/12/9999 AD.
TIMESTAMP (p) It represents a date and a time, including fractional seconds. The
The precision can
be from 0 to 9 and the default è 6. There is also an additional data type
TIMESTAMP (p) WITH TIME ZONE that adds time zone information.
RAW (size) Used to store raw binary data of length size bytes.
CLOB Character data up to 4 gigabytes.
BLOB Binary data up to 4 gigabytes.
BFILE Binary data stored in an external file.
SQL Statements

SELECT Data retrieval Retrives data from the database.

INSERT Data Manipulation Enters new rows, changes existing rows, and removes
DELETE Language (DML) unwanted rows from tables in the database, respectively. Use
the MERGE statement to select rows from one table for update
UPDATE or insertion into another table.
MERGE
CREATE Data Definition Sets up, changes, and removes data structures from tables.
ALTER Language (DDL)
DROP
TRUNCATE
COMMIT Transaction Manages the changes made by DML statements. Changes to
ROLLBACK Control the data can be grouped together into logical transactions.

GRANT Data Control Gives or removes access rights to both the Oracle database
REVOKE Language (DCL) and the structures within it.
SQL*Plus Overview

„ SQL*Plus is an interactive and batch query tool that is installed with every
Oracle Server or Client installation.

„ It has a command-line user interface; it has its own commands and it allows
enter and execute SQL, PL/SQL and operating system commands.

„ You can use SQL*Plus to generate reports and to output the results to text
file, to screen, or to HTML file for browsing on the Internet.

SQL> conn bsgd9@teorabe


Enter password: *****
Connected.

SQL> disc
Disconnected from Oracle9i Enterprise Edition Release
9.2.0.4.0 - 64bit Production
With the Partitioning option
JServer Release 9.2.0.4.0 - Production
Tables Used in the course
For our examples we will use the two simple tables of employees and
departments of a company:

SQL> set lines 80

SQL> desc EMP


Name Null? Type
----------------------------------------- -------- ----------------------------
EMP_ID NOT NULL NUMBER(6)
FIRST_NAME VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(25)
EMAIL NOT NULL VARCHAR2(25)
PHONE_NUMBER VARCHAR2(20)
HIRE_DATE NOT NULL DATE
JOB_ID NOT NULL VARCHAR2(10)
SALARY NUMBER(8,2)
COMMISSION_PCT NUMBER(2,2)
MANAGER_ID NUMBER(6)
DEPT_ID NUMBER(4)

SQL> desc DEPT


Name Null? Type
----------------------------------------- -------- ----------------------------
DEPT_ID NOT NULL NUMBER(4)
DEPT_NAME NOT NULL VARCHAR2(30)
MANAGER_ID NUMBER(6)
LOCATION_ID NUMBER(4)
Writing SELECT Statements
To extract data from the database you need to use the SELECT statement. You
can use a SELECT statement to do the following:

„ Projection Choose the columns in a table that you want the query to
return. You can choose as few or as many columns of the
table as you require.
„ Selection Choose the rows in a table that you want the query to return.
You can use various criteria to restrict the rows that you see.
„ Join Bring together data stored in different tables by creating a link
through a column that appears in both tables.

SELECT [DISTINCT] {*|column|expression [alias],...}


FROM table
[WHERE condition(s)]
[GROUP BY group_by_expression]
[ORDER BY column];
Retriving all columns
Assume that you want to display all of the columns of information stored in the
DEPARTMENTS table. This is the simplest use of the SELECT statement in SQL.

SQL> SELECT * FROM dept;

DEPT_ID DEPT_NAME MANAGER_ID LOCATION_ID


---------- ------------------------------ ---------- -----------
10 Administration 200 1700
20 Marketing 201 1800
50 Shipping 124 1500
60 IT 103 1400
80 Sales 149 2500
90 Executive 100 1700
110 Accounting 205 1700
190 Contracting 1700

8 rows selected.
Creating a Projection
Assume that you want to display only two columns (e.g DEPARTMENT_ID and
LOCATION_ID) of data stored in the DEPARTMENTS table. This “projection” is a
typical use of the SELECT statement in SQL.
SQL> SELECT dept_id, location_id from dept; SQL> SELECT dept_id AS Dept, location_id location
2 from dept;
DEPT_ID LOCATION_ID
---------- ----------- DEPT LOCATION
10 1700 ---------- -----------
20 1800 10 1700
50 1500 20 1800
60 1400 50 1500
80 2500 60 1400
90 1700 80 2500
110 1700 90 1700
190 1700 110 1700
190 1700
8 rows selected. 8 rows selected.

SQL> SELECT dept_id as "Dept Id",location_id "Location#"


2 FROM dept; Column Alias

When displaying the result of a query, SQL*Plus


Dept Id Location#
---------- -----------
10 1700 normally uses the name of the selected column
as the column heading. You can change a
20 1800
50 1500
60 1400 column heading by using a column alias.
80
90
2500
1700 By default, alias headings appear in uppercase. If
110 1700 the alias is case sensitive or if it contains spaces
190 1700
or special characters such as # or $, enclose it in
8 rows selected. double quotation marks ("" ).
("").
Arithmetic Expressions
You may need to modify the way in which data is displayed, perform calculations,
or look at what-if scenarios. You can do so by using arithmetic expressions. An
arithmetic expression may contain column names, constant numeric values, and
the arithmetic operators.
SQL> SELECT last_name, salary, commission_pct,
SQL> SELECT last_name, salary, salary+300 2 salary*commission_pct comm_month
2 from emp; 3 from emp;

LAST_NAME SALARY SALARY+300 LAST_NAME SALARY COMMISSION_PCT COMM_MONTH


------------------------- ---------- ---------- -------------- ---------- -------------- --------------
King 24000 24300 King 24000
Kochhar 1700 2000 Kochhar 1700
De Haan 17000 17300 De Haan 17000
Hunold 9000 9300 Hunold 9000
Ernst 6000 6300 Ernst 6000
Lorentz 4200 4500 Lorentz 4200
Mourgos 5800 6100 Mourgos 5800
Rajs 3500 3800 Rajs 3500
Davies 3100 3400 Davies 3100
Matos 2600 2900 Matos 2600
Vargas 2500 2800 Vargas 2500
Zlotkey 10500 10800 Zlotkey 10500 .2 2100
Abel 11000 11300 Abel 11000 .3 3300
Taylor 8600 8900 Taylor 8600 .2 1720
Grant 7000 7300 Grant 7000 .15 1050
Whalen 4400 4700 Whalen 4400
Hartstein 13000 13300 Hartstein 13000
Fay 6000 6300 Fay 6000
Higgins 12000 12300 Higgins 12000
Gietz 8300 8600 Gietz 8300

20 rows selected. 20 rows selected.


Operators Precedence
If an arithmetic expression contains more than one operator:

„ multiplication and division are evaluated first.


„ sum and different have a lower precedence.
„ for operators with the same priority, evaluation is done from left to right.
Use parentheses for every doubt.
SQL> SELECT last_name, salary, (100+salary)*12 FROM emp;
SQL> SELECT last_name, salary, 100+salary*12 FROM emp;
LAST_NAME SALARY (100+SALARY)*12
------------------------- ---------- ---------------
LAST_NAME SALARY 100+SALARY*12
King 24000 289200
------------------------- ---------- -------------
Kochhar 1700 21600
King 24000 288100
De Haan 17000 205200
Kochhar 1700 20500
Hunold 9000 109200
De Haan 17000 204100
Ernst 6000 73200
Hunold 9000 108100
Lorentz 4200 51600
Ernst 6000 72100
Mourgos 5800 70800
Lorentz 4200 50500
Rajs 3500 43200
Mourgos 5800 69700
Davies 3100 38400
Rajs 3500 42100
Matos 2600 32400
Davies 3100 37300
Vargas 2500 31200
Matos 2600 31300
Zlotkey 10500 127200
Vargas 2500 30100
Abel 11000 133200
Zlotkey 10500 126100
Taylor 8600 104400
Abel 11000 132100
Grant 7000 85200
Taylor 8600 103300
Whalen 4400 54000
Grant 7000 84100
Hartstein 13000 157200
Whalen 4400 52900
Fay 6000 73200
Hartstein 13000 156100
Higgins 12000 145200
Fay 6000 72100
Gietz 8300 100800
Higgins 12000 144100
Gietz 8300 99700
20 rows selected.
20 rows selected.
The Concatenation Operator
Through the concatenation operator (||) you can link columns to other columns,
arithmetic expressions, or constant values to create a character expression.
SQL> SELECT first_name || last_name AS "Names" SQL> SELECT last_name ||' is a '|| job_id
2 FROM emp; 2 AS "Employee Details" FROM emp;
Names Employee Details
--------------------------------------------- -----------------------------------------
StevenKing King is a AD_PRES
NeenaKochhar Kochhar is a AD_VP
LexDe Haan De Haan is a AD_VP
AlexanderHunold Hunold is a IT_PROG
BruceErnst Ernst is a IT_PROG
DianaLorentz Lorentz is a IT_PROG
KevinMourgos Mourgos is a ST_MAN
TrennaRajs Rajs is a ST_CLERK
CurtisDavies Davies is a ST_CLERK
RandallMatos Matos is a ST_CLERK
PeterVargas Vargas is a ST_CLERK
EleniZlotkey Zlotkey is a SA_MAN
EllenAbel Abel is a SA_REP
JonathonTaylor Taylor is a SA_REP
KimberelyGrant Grant is a SA_REP
JenniferWhalen Whalen is a AD_ASST
MichaelHartstein Hartstein is a MK_MAN
PAtFay Fay is a MK_REP
ShelleyHiggins Higgins is a AC_MGR
WilliamGietz Gietz is a AC_ACCOUNT
20 rows selected. 20 rows selected.
Duplicate Rows
The default display of queries is all rows, including duplicate rows. To eliminate
duplicate rows in the result, include the DISTINCT keyword in the SELECT clause
immediately after the SELECT keyword.
SQL> SELECT dept_id FROM emp;

DEPT_ID
----------
90
90 SQL> SELECT DISTINCT dept_id FROM emp;
90
60 DEPT_ID
60 ----------
60 10
50 20
50 50
50 60
50 80
50 90
80 110
80
80
8 rows selected.
10
20
20
110
110

20 rows selected.
Restricting Data
You use a WHERE clause to restrict the rows returned by a query. A WHERE
clause contains a condition that must be met and can compare values in
columns, literal values, arithmetic expressions, or functions.
Operators
SQL> SELECT last_name, job_id, dept_id FROM emp
2 WHERE dept_id = 90 ; = Equal to
> Greater than
LAST_NAME JOB_ID DEPT_ID
------------------------- ---------- ---------- >= Greater than or equal to
King AD_PRES 90 < Less than
Kochhar AD_VP 90 <= Less than or equal to
De Haan AD_VP 90 <> Not equal to

SQL> SELECT last_name, manager_id FROM emp WHERE last_name='Ernst';

LAST_NAME MANAGER_ID
------------------------- ----------
Ernst 103 Character strings and dates in
the WHERE clause must be
SQL> SELECT last_name, manager_id FROM emp WHERE last_name='ernst'; enclosed in single quotation
no rows selected
marks (’ ’). All character and
SQL> SELECT last_name, manager_id FROM emp date searches are case
2 WHERE LOWER (last_name) = ‘ernst'; sensitive.
LAST_NAME MANAGER_ID
------------------------- ----------
Ernst 103
BETWEEN, IN & IS NULL Operators

SQL> SELECT last_name, salary FROM emp WHERE salary BETWEEN 9000 AND 17000;

LAST_NAME SALARY
------------------------- ----------
De Haan 17000
Hunold 9000
Zlotkey 10500
Abel 11000
Hartstein 13000
Higgins 12000

6 rows selected.

SQL> SELECT emp_id, last_name, salary, manager_id FROM emp


2 WHERE manager_id IN (100, 102, 103);

EMP_ID LAST_NAME SALARY MANAGER_ID


---------- ------------------------- ---------- ----------
101 Kochhar 1700 100
102 De Haan 17000 100
103 Hunold 9000 102
104 Ernst 6000 103
107 Lorentz 4200 103
124 Mourgos 5800 100
149 Zlotkey 10500 100
201 Hartstein 13000 100 A null value means that
8 rows selected.
the value is unavailable,
unassigned, unknown, or
SQL> SELECT first_name, manager_id from emp where manager_id IS NULL; inapplicable. You cannot
FIRST_NAME MANAGER_ID test with (=) because a
-------------------- ---------- null value cannot be equal
or unequal to any value.
Steven
LIKE Operator
You may not always know the exact search condition. You can select rows that
match a character pattern by using the LIKE operator. You can use two symbols
to construct the search string:

„ the percentage sign (%) represents any sequence of zero or more


characters.
„ the underscore (_) represents any single character.

SQL> SELECT last_name, salary, job_id FROM emp WHERE job_id LIKE 'M%';

LAST_NAME SALARY JOB_ID


------------------------- ---------- ----------
Hartstein 13000 MK_MAN
Fay 6000 MK_REP

SQL> SELECT last_name FROM emp WHERE last_name LIKE '_a%';

LAST_NAME
-------------------------
Matos

SQL> SELECT last_name, job_id FROM emp WHERE job_id LIKE '%K\_%' ESCAPE'\';

LAST_NAME JOB_ID
------------------------- ----------
Hartstein MK_MAN
Fay MK_REP
Logical Operators
A logical operator combines the result of two or more component conditions
to produce additional or alternative conditions or to invert the result of a single
condition. Three logical operators are available in SQL: AND, OR and NOT.

SQL> SELECT emp_id, last_name, job_id, salary FROM emp


2 WHERE salary >= 1100 AND job_id='ST_CLERK';

EMP_ID LAST_NAME JOB_ID SALARY


---------- ------------------------- ---------- ----------
141 Rajs ST_CLERK 3500 SQL> SELECT first_name, job_id FROM emp
142 Davies ST_CLERK 3100 2 WHERE job_id NOT IN
143 Matos ST_CLERK 2600 3 ('ST_CLERK','SA_REP','IT_PROG');
144 Vargas ST_CLERK 2500
FIRST_NAME JOB_ID
-------------------- ----------
SQL> SELECT emp_id, last_name, job_id, salary FROM emp Steven AD_PRES
2 WHERE salary >= 12000 OR job_id = 'ST_CLERK'; Neena AD_VP
Lex AD_VP
EMP_ID LAST_NAME JOB_ID SALARY Kevin ST_MAN
---------- ------------------------- ---------- ---------- Eleni SA_MAN
100 King AD_PRES 24000 Jennifer AD_ASST
102 De Haan AD_VP 17000 Michael MK_MAN
141 Rajs ST_CLERK 3500 PAt MK_REP
142 Davies ST_CLERK 3100 Shelley AC_MGR
143 Matos ST_CLERK 2600 William AC_ACCOUNT
144 Vargas ST_CLERK 2500
201 Hartstein MK_MAN 13000 10 rows selected.
205 Higgins AC_MGR 12000

8 rows selected.
Roles of Precedence
„ Oracle evaluates operators with higher precedence.
„ For operators with equal precedence, expression is evaluated from left to right.
„ Comparison operators are evaluated first; then in order of decreasing priority
we have NOT, AND, OR operators.

SQL> SELECT last_name,manager_id, job_id


2 FROM emp
3 WHERE manager_id = 100
4 OR manager_id = 124
5 AND job_id = 'ST_CLERK'; SQL> SELECT last_name,manager_id, job_id FROM emp
2 WHERE (manager_id = 100 OR manager_id = 124)
LAST_NAME MANAGER_ID JOB_ID 3 AND job_id = 'ST_CLERK';
------------------------- ---------- --------
Kochhar 100 AD_VP LAST_NAME MANAGER_ID JOB_ID
De Haan 100 AD_VP ------------------------- ---------- ----------
Mourgos 100 ST_MAN Rajs 124 ST_CLERK
Rajs 124 ST_CLERK Davies 124 ST_CLERK
Davies 124 ST_CLERK Matos 124 ST_CLERK
Matos 124 ST_CLERK Vargas 124 ST_CLERK
Vargas 124 ST_CLERK
Zlotkey 100 SA_MAN
Hartstein 100 MK_MAN

9 rows selected.
Sorting Data
You can use the ORDER BY clause to sort the rows. You must place the ORDER
BY clause last and you can specify a column, an expression or an alias to sort by.

Null values are displayed last for ascending sequences and first for
descending sequences.
SQL> SELECT last_name, dept_id, salary FROM emp SQL> SELECT emp_id, last_name,salary*12 annsal FROM emp
2 ORDER BY dept_id, salary DESC ; 2 ORDER BY annsal;

LAST_NAME DEPT_ID SALARY EMP_ID LAST_NAME ANNSAL


------------------------- ---------- ---------- ---------- ------------------------- ----------
Whalen 10 4400 101 Kochhar 20400
Hartstein 20 13000 144 Vargas 30000
Fay 20 6000 143 Matos 31200
Mourgos 50 5800 142 Davies 37200
Rajs 50 3500 141 Rajs 42000
Davies 50 3100 107 Lorentz 50400
Matos 50 2600 200 Whalen 52800
Vargas 50 2500 124 Mourgos 69600
Hunold 60 9000 104 Ernst 72000
Ernst 60 6000 202 Fay 72000
Lorentz 60 4200 178 Grant 84000
Abel 80 11000 206 Gietz 99600
Zlotkey 80 10500 176 Taylor 103200
Taylor 80 8600 103 Hunold 108000
King 90 24000 149 Zlotkey 126000
De Haan 90 17000 174 Abel 132000
Kochhar 90 1700 205 Higgins 144000
Higgins 110 12000 201 Hartstein 156000
Gietz 110 8300 102 De Haan 204000
Grant 7000 100 King 288000

20 rows selected. 20 rows selected.


Oracle Built-in Functions

There are two distinct types of functions:

„ Single-row functions
Single-row functions operate on single rows only and return one result per
row. There are different types of single-row functions.

„ Multi-row functions
Multiple-row functions manipulate groups of rows to give one result per
group of rows.
Single-row Functions

Character Number

Single-row
functions

Conversion Date

We will work with:

„ NULL values
„ Dates
„ Characters.
Null Values Conversion
• A null value is a value that is unassigned, unknown. It is not the same as a
zero or a space: zero is a number and a space is a character.
• If any column value in an arithmetic expression is null, the result is null.
• The NVL function provides a mechanism to deal with null values.
SQL> SELECT last_name NAME,job_id, SQL> SELECT last_name, job_id,
2 12*salary*(1+commission_pct) sal_tot FROM emp; 2 12*salary*(1+NVL(commission_pct,0)) sal_tot FROM emp;

NAME JOB_ID SAL_TOT LAST_NAME JOB_ID SAL_TOT


------------------------- ---------- ---------- ------------------------- ---------- ----------
King AD_PRES King AD_PRES 288000
Kochhar AD_VP Kochhar AD_VP 20400
De Haan AD_VP De Haan AD_VP 204000
Hunold IT_PROG Hunold IT_PROG 108000
Ernst IT_PROG Ernst IT_PROG 72000
Lorentz IT_PROG Lorentz IT_PROG 50400
Mourgos ST_MAN Mourgos ST_MAN 69600
Rajs ST_CLERK Rajs ST_CLERK 42000
Davies ST_CLERK Davies ST_CLERK 37200
Matos ST_CLERK Matos ST_CLERK 31200
Vargas ST_CLERK Vargas ST_CLERK 30000
Zlotkey SA_MAN 151200 Zlotkey SA_MAN 151200
Abel SA_REP 171600 Abel SA_REP 171600
Taylor SA_REP 123840 Taylor SA_REP 123840
Grant SA_REP 96600 Grant SA_REP 96600
Whalen AD_ASST Whalen AD_ASST 52800
Hartstein MK_MAN Hartstein MK_MAN 156000
Fay MK_REP Fay MK_REP 72000
Higgins AC_MGR Higgins AC_MGR 144000
Gietz AC_ACCOUNT Gietz AC_ACCOUNT 99600

20 rows selected. 20 rows selected.


Working with Date
„ Oracle database stores dates in an internal numeric format: century, year,
month, day, hours, minutes, seconds.
„ The default display date format is DD-MON-RR.
„ Because the database stores dates as numbers, you can use arithmetic
operators to perform calculations such as addition and subtraction on dates.

SQL> SELECT last_name, hire_date, hire_date+30 "NEW DATE" FROM emp WHERE last_name='Grant';

LAST_NAME HIRE_DATE NEW DATE


------------------------- --------- ---------
Grant 24-MAY-99 23-JUN-99

SQL> SELECT last_name, (SYSDATE-hire_date)/7 "WEEKS AT WORK" FROM emp WHERE dept_id =10;

LAST_NAME WEEKS AT WORK


------------------------- -------------
Whalen 871.629897
Working with Dates
You can use the TO_CHAR function to convert a date from the default format
(DD-MON-RR) to the one that you specify.
SQL> select last_name, TO_CHAR(hire_date, 'Month DDTH, YYYY') as HIREDATE from emp where job_id = 'IT_PROG';

LAST_NAME HIREDATE
------------------------- --------------------
Hunold January 03RD, 1990
Ernst May 21ST, 1991
Lorentz February 07TH, 1999

SQL> select last_name, manager_id, salary, TO_CHAR(hire_date, 'YYYY-MON-DD') as HIREDATE from emp
2 where hire_date like '%90';

LAST_NAME MANAGER_ID SALARY HIREDATE


------------------------- ---------- ---------- -----------
Hunold 102 9000 1990-JAN-03

SQL> select last_name, TO_CHAR(hire_date, 'fmdd "of" Month YYYY hh24:mi:ss') as HIREDATE from emp;

LAST_NAME HIREDATE
------------------------- -------------------------------------------
King 17 of June 1987 0:0:0
Kochhar 21 of September 1989 0:0:0
De Haan 13 of January 1993 0:0:0
Hunold 3 of January 1990 0:0:0
Ernst 21 of May 1991 0:0:0
Lorentz 7 of February 1999 0:0:0
....
20 rows selected.
Working with Characters
A string can be converted to either a number or a date using TO_NUMBER
or TO_DATE functions.

SQL> SELECT TO_NUMBER('1000')+salary AS NEW_SALARY


2 FROM emp
3 WHERE last_name = 'Matos';

SALARY NEW_SALARY
------- ----------
2600 3600

SQL> SELECT last_name, hire_date


2 FROM emp
3 WHERE hire_date = TO_DATE('May 24, 1999','Month DD, YYYY');

LAST_NAME HIRE_DATE
------------------------- ---------
Grant 24-MAY-99
Multi-rows Functions
Unlike single-row functions, group functions operate on sets of rows to give one
result per group. Grouping functions are:
„ AVG
„ COUNT
„ MAX/MIN
„ SUM

SQL> SELECT AVG(commission_pct), SQL> SELECT COUNT(*),


2 AVG(NVL(commission_pct,0)) 2 FROM emp;
3 FROM emp;
COUNT(*)
AVG(COMMISSION_PCT) AVG(NVL(COMMISSION_PCT,0)) ----------
------------------- --------------------------
.2125 .0425 20

SQL> SELECT COUNT(*),


SQL> SELECT TO_CHAR(MIN(hire_date),'DD-MON-YYYY') OLDER,
2 COUNT(dept_id),
2 TO_CHAR(MAX(hire_date),'DD-MON-YYYY') YOUNGER
3 COUNT(DISTINCT(dept_id))
3 FROM emp;
4 FROM emp;
OLDER YOUNGER
COUNT(*) COUNT(DEPT_ID) COUNT(DISTINCT(DEPT_ID))
----------- -----------
---------- -------------- ------------------------
17-JUN-1987 29-JAN-2000
20 19 7
Groups of Data
„ Use the GROUP BY clause to divide the rows in a table into groups
„ Use the HAVING clause to filter on group function.
„ When using the GROUP BY clause, make sure that all columns in the
SELECT list that are not in the group functions are included in the GROUP
BY clause, otherwise an Oracle error occurs.
SQL> SELECT dept_id, count(*) FROM emp;
SELECT dept_id, count(*)
*
ERROR at line 1:
ORA-00937: not a single-group group function
SQL> SELECT dept_id, AVG(salary) FROM emp
2 HAVING AVG(salary)>7000
SQL> SELECT dept_id, count(*) FROM emp
3 GROUP BY dept_id;
2 GROUP BY dept_id;

DEPT_ID COUNT(*) DEPT_ID AVG(SALARY)


---------- ----------- ---------- -----------
10 1 20 9500
20 2 80 10033.3333
50 5 90 14233.3333
60 3 110 10150
80 3
90 3
110 2
1

8 rows selected.
Joining Tables
When you require data from more than one table in the database, you use a
join condition. Rows in one table can be joined to rows in another table
according to common values existing in corresponding columns. Typically, when
rows are joined using a common value, the column in the first table is a primary
key and the column in the second table is a foreign key.

SELECT table1.column1, table2.column2


FROM table1, table2
WHERE table1.column1 = table2.column2

There are many types of joins:

„ Natural join „ Outer join


„ Cartesian join „ Full outer join
„ Self join
Natural Join
SQL> SELECT e.emp_id, e.last_name, e.dept_id, d.dept_id, d.dept_name FROM emp e, dept d WHERE e.dept_id=d.dept_id ;
EMP_ID LAST_NAME DEPT_ID DEPT_ID DEPT_NAME
---------- ------------------------- ---------- ---------- --------------------------
100 King 90 90 Executive
101 Kochhar 90 90 Executive
102 De Haan 90 90 Executive
103 Hunold 60 60 IT
104 Ernst 60 60 IT
107 Lorentz 60 60 IT
124 Mourgos 50 50 Shipping
141 Rajs 50 50 Shipping
142 Davies 50 50 Shipping
143 Matos 50 50 Shipping
144 Vargas 50 50 Shipping
149 Zlotkey 80 80 Sales
174 Abel 80 80 Sales
176 Taylor 80 80 Sales
200 Whalen 10 10 Administration
201 Hartstein 20 20 Marketing
202 Fay 20 20 Marketing
205 Higgins 110 110 Accounting
206 Gietz 110 110 Accounting

19 rows selected.

SQL> SELECT last_name,job_id, emp.dept_id, dept.dept_name FROM emp, dept


2 WHERE emp.dept_id=dept.dept_id AND job_id IN ('SA_REP','MK_REP');

LAST_NAME JOB_ID DEPT_ID DEPT_NAME


------------------------- ---------- ---------- ------------------------------
Abel SA_REP 80 Sales
Taylor SA_REP 80 Sales
Fay MK_REP 20 Marketing
Cartesian Product
When a join condition is invalid or omitted completely, the result is a cartesian
product in which all combinations of rows are displaied. All rows in the first table
are joined to all rows in the second table. A cartesian product tends to generate
a large number of rows and its result id raraely usedfull.
SQL> SELECT last_name, dept_name dept_name FROM emp, dept;

LAST_NAME DEPT_NAME
------------------------- ------------------------------
King Administration
Kochhar Administration
De Haan Administration
Hunold Administration
Ernst Administration
Lorentz Administration
Mourgos Administration
Rajs Administration
Davies Administration
Matos Administration
Vargas Administration
Zlotkey Administration
Abel Administration
Taylor Administration
Grant Administration
Whalen Administration
Hartstein Administration
Fay Administration
Higgins Administration
....
160 rows selected.
Self Join
Sometimes you need to join a table to itself. This type of a join is called as self
join. For example, to find the name of each employee’s manager, you need to
join the EMP table to itself:
SQL> SELECT worker.last_name || ' works for ' || manager.last_name
2 FROM emp worker, emp manager WHERE worker.manager_id = manager.emp_id ;

WORKER.LAST_NAME||'WORKSFOR'||MANAGER.LAST_NAME
-------------------------------------------------------------
Kochhar works for King
De Haan works for King
Hunold works for De Haan
Ernst works for Hunold
Lorentz works for Hunold
Mourgos works for King
Rajs works for Mourgos
Davies works for Mourgos
Matos works for Mourgos
Vargas works for Mourgos
Zlotkey works for King
Abel works for Zlotkey
Taylor works for Zlotkey
Grant works for Zlotkey
Whalen works for Kochhar
Hartstein works for King
Fay works for Hartstein
Higgins works for Kochhar
Gietz works for Higgins

19 rows selected.
Outer Join
SQL> select e.dept_id,d.dept_id
SQL> select e.dept_id,d.dept_id
2 from emp e, dept d
2 from emp e, dept d
3 where e.dept_id(+) = d.dept_id;
3 where e.dept_id=d.dept_id;
DEPT_ID DEPT_ID
DEPT_ID DEPT_ID
---------- ----------
---------- ----------
10 10
90 90
20 20
90 90
20 20
90 90
50 50
60 60
50 50
60 60
50 50
60 60
50 50
50 50
50 50
50 50
60 60
50 50
60 60
50 50
60 60
50 50
80 80
80 80
80 80
80 80
80 80
80 80
90 90
10 10
90 90
20 20
90 90
20 20
110 110
110 110
110 110
110 110
190
19 rows selected.
20 rows selected.
Full Outer Join
SQL> select e.dept_id,d.dept_id
2 from emp e full outer join dept d
3 on (e.dept_id=d.dept_id);

DEPT_ID DEPT_ID
---------- ----------
90 90
90 90
90 90
60 60
60 60
60 60
50 50
50 50
50 50
50 50
50 50
80 80
80 80
80 80

10 10
20 20
20 20
110 110
110 110
190

21 rows selected.
Writing Subqueries
Suppose that you want to write a query to find out who earns a salary greater
than Hartstein’s salary. To solve this problem, you need two queries: one query to
find out what Hartstein earns and a second query to find out who earns more
than that amount. You can solve this problem by combining the two queries,
placing one query inside the other query. An inner query, or subquery, returns
a value that is used by the outer query or main query.

SQL> SELECT last_name FROM emp


2 WHERE salary > (SELECT salary FROM emp WHERE last_name='Hartstein');

FIRST_NAME
-----------------
King
De Haan
Single-row Subqueries
A single-row subquery returns one row from the inner SELECT statement. This
type of subquery uses a single-row operator as listed in the slide.

SQL> SELECT last_name, job_id FROM emp


2 WHERE job_id = (SELECT job_id FROM emp WHERE emp_id = 103);

LAST_NAME JOB_ID
------------------------- ----------
Hunold IT_PROG
Ernst IT_PROG
Lorentz IT_PROG

SQL> SELECT last_name, job_id, salary FROM emp


2 WHERE salary = (SELECT MIN(salary) FROM emp);

LAST_NAME JOB_ID SALARY


------------------------- ---------- ----------
Kochhar AD_VP 1700
Multiple-row Subqueries
One common error in subqueries is more than one row returned for a single-row
subquery.
SQL> SELECT last_name, job_id, salary FROM emp
2 WHERE salary = (SELECT MAX(salary) FROM emp GROUP BY dept_id);
WHERE salary = (SELECT MAX(salary) FROM emp GROUP BY dept_id)
*
ERROR at line 2:
ORA-01427: single-row subquery returns more than one row

Subqueries that return more than one row are called multiple-row subqueries and
they must use a multiple-row operator.
SQL> SELECT last_name, job_id, salary FROM emp
2 WHERE salary IN (SELECT MAX(salary) FROM emp GROUP BY dept_id);

LAST_NAME JOB_ID SALARY


------------------------- ---------- ----------
Whalen AD_ASST 4400
Mourgos ST_MAN 5800
Grant SA_REP 7000
Hunold IT_PROG 9000
Abel SA_REP 11000
Higgins AC_MGR 12000
Hartstein MK_MAN 13000
King AD_PRES 24000

8 rows selected.
Manipulating Structures & Data
SQL> create table MY_DEPT
2 (dept_id NUMBER(4) PRIMARY KEY,
3 dept_name VARCHAR2(30) NOT NULL,
4 manager_id NUMBER(6),
5 location_id NUMBER(4));
Table created.

SQL> insert into MY_DEPT (dept_id, dept_name, manager_id, location_id) values (10,'Administration',200,1700);
1 row created.

SQL> insert into MY_DEPT (dept_id, dept_name, manager_id, location_id) select * from dept where dept_id=20;
1 row created.

SQL> create table emp_history as select * from emp;


Table created.

SQL> select count(*) from emp_history;

COUNT(*)
----------
20

SQL> UPDATE emp_history SET dept_id = 60 WHERE emp_id = 206; SQL> DELETE FROM emp_history
1 row updated. 2 WHERE emp_id = 206;
1 rows deleted.
SQL> UPDATE emp
2 SET job_id = (SELECT job_id FROM emp WHERE emp_id = 205),
SQL> truncate table emp_history;
3 salary = (SELECT salary FROM emp WHERE emp_id = 205)
4 WHERE emp_id = 124;
Table truncated.
1 row updated.
SQL> drop table emp_history;
Table dropped.
Multiple Inserts
SQL> create table sal_history
2 (emp_id NUMBER(6) primary key,
3 hire_date DATE NOT NULL,
4 salary NUMBER(8,2));
Table created.

SQL> create table mgr_history


2 (emp_id NUMBER(6) primary key,
3 manager_id NUMBER(6),
4 hire_date DATE);
Table created.

SQL> insert all


2 into sal_history values (empid,hiredate,sal)
3 into mgr_history values (empid,mgrid,hiredate)
4 select emp_id empid,hire_date hiredate, salary sal, manager_id mgrid
5 from emp where emp_id > 200;

8 rows created.

SQL> delete from sal_history;


4 rows deleted.

SQL> delete from mgr_history;


4 rows deleted.

SQL> insert all


2 when hiredate < to_date('01-01-1990','dd-mm-yyyy') then into sal_history values
(empid,hiredate,sal)
3 when hiredate < to_date('01-01-1990','dd-mm-yyyy') then into mgr_history values
(empid,mgrid,sysdate)
4 select emp_id empid,hire_date hiredate, salary sal, manager_id mgrid
5 from emp;

6 rows created.
MERGE Statements
„ MERGE statement allows you to update or insert a row conditionally into a
table. The decision whether to update or insert into the target table is based
on a condition in the ON clause.
„ you need both INSERT and UPDATE privileges on the target table and the
SELECT privilege on the source table.

„ MERGE statement is a suitable alternative approach to use PL/SQL loops and


multiple DML statements.

SQL> select count(*) from sal_history;

COUNT(*)
----------
3

SQL> merge into sal_history eh using emp e on (eh.emp_id=e.emp_id)


2 when matched then update set eh.salary = e.salary + 100
3 when not matched then insert (emp_id,hire_date,salary) values (e.emp_id,e.hire_date,e.salary);
20 rows merged.

SQL> select count(*) from sal_history;

COUNT(*)
----------
20
Database Transactions
„ Database users access the database in two ways:

„ read operations (SELECT statement)


„ write operations (INSERT, UPDATE, DELETE statements).

„ The Oracle Server ensures data consistency based on transactions.

„ A transaction begins when the first DML statement is encountered, and ends
when one of the following occurs:

„ A COMMIT or ROLLBACK statement is issued


„ A DDL statement, such as CREATE, is issued
„ A DCL statement is issued
„ The user exits SQL*Plus
„ A machine fails or the system crashes
Data Consistency
„ When an insert, update, or delete operation is made to the database, the
Oracle Server takes a copy of the data before it is changed and writes it to a
rollback segment.

„ When a DML statement is committed, the change made to the database


becomes visible to anyone executing a SELECT statement. The space occupied
by the “old” data in the rollback segment file is freed for reuse.

„ If the transaction is rolled back, the changes are undone.


-- TIME=0 FIRST TRANSACTION STARTS
-- TIME=1 SECOND TRANSACTION STARTS
-- TIME=2
SQL> update emp set emp_id = 210 where emp_id=103;
1 row updated.
-- TME=3
SQL> select FIRST_NAME from emp where emp_id=210;
-- TIME=4 no rows selected
SQL> commit;
Commit complete. -- TIME=5
SQL> select FIRST_NAME from emp where emp_id=210;

FIRST_NAME
--------------------
Alexander
Locking

Oracle provide data concurrency and integrity between transactions using its
locking. Oracle uses two modes of locking in a multiuser
database:

„ EXCLUSIVE LOCK MODE


It prevents the associates resource from being shared and it is obtained to
modify data.

„ SHARED LOCK MODE


It allows the associated resource to be shared and it is obtained to read
data.

Oracle locking is fully automatic and requires no user action. Application


designers need only define transactions properly, and Oracle automatically
manages locking.
Transaction Isolation Levels
„ READ COMMITTED
This is the default isolation level. Each query executed by a transaction sees
only data that was committed before the query.

„ SERIALIZABLE
Serializable transactions see only those changes that were committed at the
time the transaction began, plus those changes made by the transaction itself.
To make this determination efficiently, Oracle uses control information stored in
the data block that indicates which rows in the block contain committed and
uncommetted changes. The amount of history that is retained is controlled by
the INITRANS parameter of CREATE TABLE statement. Under same
circumstances, Oracle can have insufficient history information to determine
whether a row has been updated by a “too recent” transaction. Oracle
generates an error when a serializable transaction tries to update or delete data
modified by a transaction that commits after the serializable transaction began.

„ READ ONLY
Read-only transactions see only those changes that were committed at the time
the transaction began and do not allow INSERT, DELETE and UPDATE
statements.
Table Creation Guidelines
„ When you create a table, Oracle automatically allocates a data segment in a
tablespace to hold the table’s future data.
„ A database is divided into logical storage units called TABLESPACES, which
group related logical structures together.
„ Physically a tablespace is composed by one or more DATAFILES.
„ Logically it is divided into SEGMENTS, EXTENTS and DATABLOCKS.

TABLESPACE
EXTENT 01
EXTENT 02

EXTENT 03

.... DATABLOCKS

SEGMENT 01 SEGMENT 02 SEGMENT 03


Table Creation Guidelines
You can control the allocation and use of space for a table’s data segment
according to storage definition at table’s creation level:

„ TABLESPACE clause There are many different tablespace according to


database user and object type (table or index).
„ EXTENT storage From Oracle 8i the tablespaces can be locally
managed. In other word, STORAGE clause in the
CREATE TABLE must not be defined.
„ DATABLOCK storage It can be managed through PCTFREE and PCTUSED
parameters. From Oracle 9i segments can be locally
managed, so PCTUSED parameters can be
disregarded.
„ INITRANS parameter Each datablock has a number of transaction entries
that are used for row locking purpose. Initially, this
number is specified by the INITRANS parameter, and
the default values (1 for table, 2 for index) is
generally sufficient. We suggest increasing INITRANS
values only after ORA-08177.
Table Creation - PCTFREE and PCTUSED
INSERT New rows can be added

PCTUSED
PCTFREE
to the row data area in
HEAD

the free portion of


datablock that isn’t
DATABLOCK
allocated to PCTFREE.

PCTFREE parameter sets


the minimum percentage After a datablock is filled to the limit
of a datablock to be determined by PCTFREE, Oracle considers
reserved as free space for the block unaviable for the insertion of new
possible updates to rows
rows until the percentage of that block falls
that already exists in that
block. below PCTUSED value. Oracle recommends
having:

PCTFREE + PCTUSED = 90%


Table Creation - example

There are some roles to follow about objects’ naming standard. Look at intranet
documentation (Development intranet: DevCentral\Oracle Guidelines).
create table AN_MA_ANAG_CLIENTI
(AC_CLIENTE_ID number(10,0),
AC_NOME varchar2(50),
AC_COGNOME varchar2(50),
AC_INDIRIZZO varchar2(50),
AC_COMUNE varchar2(50),
AC_CAP varchar2(5) constraint AN_AC_CAP_NN_2001 NOT NULL,
AC_PROVINCIA varchar2(4),
AC_TELEFONO varchar2(15),
constraint AN_AC_CLID_PK_1001 primary key (AC_CLIENTE_ID)
using index tablespace @@TB_IDX_LIT@@ PCTFREE 5
)
tablespace @@TB_DATI_LIT@@
PCTFREE 5
PCTUSED 85
/

Oracle associates to any PK or UQ an index. It NAME TABLEINDEX DIMENSION

is necessary defining storage parameters also LIT <30MB


for indexes (PCTFREE must not be defiened for MED [30MB, 50MB]
index). BIG >50MB

Potrebbero piacerti anche