You are on page 1of 53

H2O Overview

TEST & DEVELOP ENVIRONMENT PRODUCTION ENVIRONMENT

PRE-PRODUCTION ENVIRONMENT

ORABE WEBLOGIC OraGP OraMON Ora121 DATABASES OraBE CARTE PORT01 CARTE_DBA WEBLOGIC_DBA

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. 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. They have all the necessary privileges through CONNECT and RESOURCE roles. They also be able to manipulate test objects.

APPLICATIVE USERS

DEVELOP USERS

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 Function procedure package Table Sequence View GRANTS execute select, insert,update,delete select select SYNONYMS yes yes yes 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.

Integrity Constraints

PRIMARY KEY

PK identifies a row uniquely. PK can be composed by more than one column, but it is better short ones.
FIRST_ ... DEPT_ID DEPT_ID DEPT_N ... ... ...

CODE

LAST_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. By default every column can be NULL, otherwise a not null constraint can be defined on a column. CK allows forcing an integrity rule based on a logical expression, that cant be achieved through the other kind of constraints.

NOT NULL CHECK KEY

Dont 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) VARCHAR2 (size) NUMBER (p, s) Used to store fixed length character data of length size. Max size size is 2000 bytes. Used to store a variablevariable-length character string having maximum length size bytes. The maximum size is 4000 bytes 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. Used to store dates (and times). Valid dates range from 01/01/4712 01/01/4712 BC to 31/12/9999 AD. 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. Used to store raw binary data of length size bytes. Character data up to 4 gigabytes. Binary data up to 4 gigabytes. Binary data stored in an external file.

DATE TIMESTAMP (p)

RAW (size) CLOB BLOB BFILE

SQL Statements
SELECT INSERT DELETE UPDATE MERGE CREATE ALTER DROP TRUNCATE COMMIT ROLLBACK GRANT REVOKE
Data retrieval

Retrives data from the database.


Enters new rows, changes existing rows, and removes unwanted rows from tables in the database, respectively. Use the MERGE statement to select rows from one table for update or insertion into another table. Sets up, changes, and removes data structures from tables.

Data Manipulation Language (DML)

Data Definition Language (DDL)

Transaction Control

Manages the changes made by DML statements. Changes to the data can be grouped together into logical transactions.

Data Control Language (DCL)

Gives or removes access rights to both the Oracle database 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 ----------------------------------------EMP_ID FIRST_NAME LAST_NAME EMAIL PHONE_NUMBER HIRE_DATE JOB_ID SALARY COMMISSION_PCT MANAGER_ID DEPT_ID SQL> desc DEPT Name ----------------------------------------DEPT_ID DEPT_NAME MANAGER_ID LOCATION_ID Null? Type -------- ---------------------------NOT NULL NUMBER(6) VARCHAR2(20) NOT NULL VARCHAR2(25) NOT NULL VARCHAR2(25) VARCHAR2(20) NOT NULL DATE NOT NULL VARCHAR2(10) NUMBER(8,2) NUMBER(2,2) NUMBER(6) NUMBER(4) Null? -------NOT NULL NOT NULL Type ---------------------------NUMBER(4) VARCHAR2(30) NUMBER(6) 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

Selection Join

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. 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. 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 ---------10 20 50 60 80 90 110 190 DEPT_NAME MANAGER_ID LOCATION_ID ------------------------------ ---------- ----------Administration 200 1700 Marketing 201 1800 Shipping 124 1500 IT 103 1400 Sales 149 2500 Executive 100 1700 Accounting 205 1700 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; DEPT_ID LOCATION_ID ---------- ----------10 1700 20 1800 50 1500 60 1400 80 2500 90 1700 110 1700 190 1700 8 rows selected. SQL> SELECT dept_id as "Dept Id",location_id "Location#" 2 FROM dept; Dept Id Location# ---------- ----------10 1700 20 1800 50 1500 60 1400 80 2500 90 1700 110 1700 190 1700 8 rows selected. SQL> SELECT dept_id AS Dept, location_id location 2 from dept; DEPT LOCATION ---------- ----------10 1700 20 1800 50 1500 60 1400 80 2500 90 1700 110 1700 190 1700 8 rows selected.

Column Alias When displaying the result of a query, SQL*Plus normally uses the name of the selected column as the column heading. You can change a column heading by using a column alias. By default, alias headings appear in uppercase. If the alias is case sensitive or if it contains spaces or special characters such as # or $, enclose it in 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, salary+300 2 from emp; LAST_NAME SALARY SALARY+300 ------------------------- ---------- ---------King 24000 24300 Kochhar 1700 2000 De Haan 17000 17300 Hunold 9000 9300 Ernst 6000 6300 Lorentz 4200 4500 Mourgos 5800 6100 Rajs 3500 3800 Davies 3100 3400 Matos 2600 2900 Vargas 2500 2800 Zlotkey 10500 10800 Abel 11000 11300 Taylor 8600 8900 Grant 7000 7300 Whalen 4400 4700 Hartstein 13000 13300 Fay 6000 6300 Higgins 12000 12300 Gietz 8300 8600 20 rows selected. SQL> SELECT last_name, salary, commission_pct, 2 salary*commission_pct comm_month 3 from emp; LAST_NAME SALARY COMMISSION_PCT COMM_MONTH -------------- ---------- -------------- -------------King 24000 Kochhar 1700 De Haan 17000 Hunold 9000 Ernst 6000 Lorentz 4200 Mourgos 5800 Rajs 3500 Davies 3100 Matos 2600 Vargas 2500 Zlotkey 10500 .2 2100 Abel 11000 .3 3300 Taylor 8600 .2 1720 Grant 7000 .15 1050 Whalen 4400 Hartstein 13000 Fay 6000 Higgins 12000 Gietz 8300 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 ------------------------- ---------- ------------King 24000 288100 Kochhar 1700 20500 De Haan 17000 204100 Hunold 9000 108100 Ernst 6000 72100 Lorentz 4200 50500 Mourgos 5800 69700 Rajs 3500 42100 Davies 3100 37300 Matos 2600 31300 Vargas 2500 30100 Zlotkey 10500 126100 Abel 11000 132100 Taylor 8600 103300 Grant 7000 84100 Whalen 4400 52900 Hartstein 13000 156100 Fay 6000 72100 Higgins 12000 144100 Gietz 8300 99700 20 rows selected. LAST_NAME SALARY (100+SALARY)*12 ------------------------- ---------- --------------King 24000 289200 Kochhar 1700 21600 De Haan 17000 205200 Hunold 9000 109200 Ernst 6000 73200 Lorentz 4200 51600 Mourgos 5800 70800 Rajs 3500 43200 Davies 3100 38400 Matos 2600 32400 Vargas 2500 31200 Zlotkey 10500 127200 Abel 11000 133200 Taylor 8600 104400 Grant 7000 85200 Whalen 4400 54000 Hartstein 13000 157200 Fay 6000 73200 Higgins 12000 145200 Gietz 8300 100800 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" 2 FROM emp; Names --------------------------------------------StevenKing NeenaKochhar LexDe Haan AlexanderHunold BruceErnst DianaLorentz KevinMourgos TrennaRajs CurtisDavies RandallMatos PeterVargas EleniZlotkey EllenAbel JonathonTaylor KimberelyGrant JenniferWhalen MichaelHartstein PAtFay ShelleyHiggins WilliamGietz 20 rows selected. SQL> SELECT last_name ||' is a '|| job_id 2 AS "Employee Details" FROM emp; Employee Details ----------------------------------------King is a AD_PRES Kochhar is a AD_VP De Haan is a AD_VP Hunold is a IT_PROG Ernst is a IT_PROG Lorentz is a IT_PROG Mourgos is a ST_MAN Rajs is a ST_CLERK Davies is a ST_CLERK Matos is a ST_CLERK Vargas is a ST_CLERK Zlotkey is a SA_MAN Abel is a SA_REP Taylor is a SA_REP Grant is a SA_REP Whalen is a AD_ASST Hartstein is a MK_MAN Fay is a MK_REP Higgins is a AC_MGR Gietz is a AC_ACCOUNT 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 90 60 60 60 50 50 50 50 50 80 80 80 10 20 20 110 110 20 rows selected.

SQL> SELECT DISTINCT dept_id FROM emp; DEPT_ID ---------10 20 50 60 80 90 110 8 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.
SQL> SELECT last_name, job_id, dept_id FROM emp 2 WHERE dept_id = 90 ; LAST_NAME ------------------------King Kochhar De Haan JOB_ID DEPT_ID ---------- ---------AD_PRES 90 AD_VP 90 AD_VP 90

Operators = > >= < <= <> Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to

SQL> SELECT last_name, manager_id FROM emp WHERE last_name='Ernst'; LAST_NAME MANAGER_ID ------------------------- ---------Ernst 103 SQL> SELECT last_name, manager_id FROM emp WHERE last_name='ernst'; no rows selected
SQL> SELECT last_name, manager_id FROM emp 2 WHERE LOWER (last_name) = ernst'; LAST_NAME MANAGER_ID ------------------------- ---------Ernst 103

Character strings and dates in the WHERE clause must be enclosed in single quotation marks ( ). All character and date searches are case sensitive.

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 ---------101 102 103 104 107 124 149 201 LAST_NAME SALARY MANAGER_ID ------------------------- ---------- ---------Kochhar 1700 100 De Haan 17000 100 Hunold 9000 102 Ernst 6000 103 Lorentz 4200 103 Mourgos 5800 100 Zlotkey 10500 100 Hartstein 13000 100

8 rows selected. SQL> SELECT first_name, manager_id from emp where manager_id IS NULL; FIRST_NAME MANAGER_ID -------------------- ---------Steven

A null value means that the value is unavailable, unassigned, unknown, or inapplicable. You cannot test with (=) because a null value cannot be equal or unequal to any value.

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 (%) the underscore (_)

represents any sequence of zero or more characters. 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 ------------------------Hartstein Fay JOB_ID ---------MK_MAN 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 ---------141 142 143 144 LAST_NAME ------------------------Rajs Davies Matos Vargas JOB_ID SALARY ---------- ---------ST_CLERK 3500 ST_CLERK 3100 ST_CLERK 2600 ST_CLERK 2500

SQL> SELECT first_name, job_id FROM emp 2 WHERE job_id NOT IN 3 ('ST_CLERK','SA_REP','IT_PROG'); FIRST_NAME -------------------Steven Neena Lex Kevin Eleni Jennifer Michael PAt Shelley William 10 rows selected. JOB_ID ---------AD_PRES AD_VP AD_VP ST_MAN SA_MAN AD_ASST MK_MAN MK_REP AC_MGR AC_ACCOUNT

SQL> SELECT emp_id, last_name, job_id, salary FROM emp 2 WHERE salary >= 12000 OR job_id = 'ST_CLERK'; EMP_ID ---------100 102 141 142 143 144 201 205 LAST_NAME ------------------------King De Haan Rajs Davies Matos Vargas Hartstein Higgins JOB_ID SALARY ---------- ---------AD_PRES 24000 AD_VP 17000 ST_CLERK 3500 ST_CLERK 3100 ST_CLERK 2600 ST_CLERK 2500 MK_MAN 13000 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> 2 3 4 5 SELECT last_name,manager_id, job_id FROM emp WHERE manager_id = 100 OR manager_id = 124 AND job_id = 'ST_CLERK';

LAST_NAME MANAGER_ID JOB_ID ------------------------- ---------- -------Kochhar 100 AD_VP De Haan 100 AD_VP Mourgos 100 ST_MAN Rajs 124 ST_CLERK Davies 124 ST_CLERK Matos 124 ST_CLERK Vargas 124 ST_CLERK Zlotkey 100 SA_MAN Hartstein 100 MK_MAN 9 rows selected.

SQL> SELECT last_name,manager_id, job_id FROM emp 2 WHERE (manager_id = 100 OR manager_id = 124) 3 AND job_id = 'ST_CLERK'; LAST_NAME MANAGER_ID JOB_ID ------------------------- ---------- ---------Rajs 124 ST_CLERK Davies 124 ST_CLERK Matos 124 ST_CLERK Vargas 124 ST_CLERK

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 2 ORDER BY dept_id, salary DESC ; LAST_NAME DEPT_ID SALARY ------------------------- ---------- ---------Whalen 10 4400 Hartstein 20 13000 Fay 20 6000 Mourgos 50 5800 Rajs 50 3500 Davies 50 3100 Matos 50 2600 Vargas 50 2500 Hunold 60 9000 Ernst 60 6000 Lorentz 60 4200 Abel 80 11000 Zlotkey 80 10500 Taylor 80 8600 King 90 24000 De Haan 90 17000 Kochhar 90 1700 Higgins 110 12000 Gietz 110 8300 Grant 7000 20 rows selected. SQL> SELECT emp_id, last_name,salary*12 annsal FROM emp 2 ORDER BY annsal; EMP_ID ---------101 144 143 142 141 107 200 124 104 202 178 206 176 103 149 174 205 201 102 100 LAST_NAME ANNSAL ------------------------- ---------Kochhar 20400 Vargas 30000 Matos 31200 Davies 37200 Rajs 42000 Lorentz 50400 Whalen 52800 Mourgos 69600 Ernst 72000 Fay 72000 Grant 84000 Gietz 99600 Taylor 103200 Hunold 108000 Zlotkey 126000 Abel 132000 Higgins 144000 Hartstein 156000 De Haan 204000 King 288000

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 Single-row functions Date Number

Conversion

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, job_id, 2 12*salary*(1+NVL(commission_pct,0)) sal_tot FROM emp; LAST_NAME ------------------------King Kochhar De Haan Hunold Ernst Lorentz Mourgos Rajs Davies Matos Vargas Zlotkey Abel Taylor Grant Whalen Hartstein Fay Higgins Gietz 20 rows selected. JOB_ID SAL_TOT ---------- ---------AD_PRES 288000 AD_VP 20400 AD_VP 204000 IT_PROG 108000 IT_PROG 72000 IT_PROG 50400 ST_MAN 69600 ST_CLERK 42000 ST_CLERK 37200 ST_CLERK 31200 ST_CLERK 30000 SA_MAN 151200 SA_REP 171600 SA_REP 123840 SA_REP 96600 AD_ASST 52800 MK_MAN 156000 MK_REP 72000 AC_MGR 144000 AC_ACCOUNT 99600 JOB_ID SAL_TOT ---------- ---------AD_PRES AD_VP AD_VP IT_PROG IT_PROG IT_PROG ST_MAN ST_CLERK ST_CLERK ST_CLERK ST_CLERK SA_MAN 151200 SA_REP 171600 SA_REP 123840 SA_REP 96600 AD_ASST MK_MAN MK_REP AC_MGR AC_ACCOUNT

SQL> SELECT last_name NAME,job_id, 2 12*salary*(1+commission_pct) sal_tot FROM emp; NAME ------------------------King Kochhar De Haan Hunold Ernst Lorentz Mourgos Rajs Davies Matos Vargas Zlotkey Abel Taylor Grant Whalen Hartstein Fay Higgins Gietz 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 ------------------------Hunold Ernst Lorentz HIREDATE -------------------January 03RD, 1990 May 21ST, 1991 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 ------------------------King Kochhar De Haan Hunold Ernst Lorentz .... 20 rows selected. HIREDATE ------------------------------------------17 of June 1987 0:0:0 21 of September 1989 0:0:0 13 of January 1993 0:0:0 3 of January 1990 0:0:0 21 of May 1991 0:0:0 7 of February 1999 0:0:0

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 COUNT(*), 2 FROM emp; COUNT(*) ---------20

SQL> SELECT AVG(commission_pct), 2 AVG(NVL(commission_pct,0)) 3 FROM emp; AVG(COMMISSION_PCT) AVG(NVL(COMMISSION_PCT,0)) ------------------- -------------------------.2125 .0425

SQL> SELECT TO_CHAR(MIN(hire_date),'DD-MON-YYYY') OLDER, 2 TO_CHAR(MAX(hire_date),'DD-MON-YYYY') YOUNGER 3 FROM emp; OLDER YOUNGER ----------- ----------17-JUN-1987 29-JAN-2000

SQL> 2 3 4

SELECT COUNT(*), COUNT(dept_id), COUNT(DISTINCT(dept_id)) FROM emp;

COUNT(*) COUNT(DEPT_ID) COUNT(DISTINCT(DEPT_ID)) ---------- -------------- -----------------------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, count(*) FROM emp 2 GROUP BY dept_id; DEPT_ID COUNT(*) ---------- ----------10 1 20 2 50 5 60 3 80 3 90 3 110 2 1 8 rows selected.

SQL> SELECT dept_id, AVG(salary) FROM emp 2 HAVING AVG(salary)>7000 3 GROUP BY dept_id; DEPT_ID AVG(SALARY) ---------- ----------20 9500 80 10033.3333 90 14233.3333 110 10150

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 Cartesian join Self join

Outer join Full outer 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 ------------------------Abel Taylor Fay JOB_ID DEPT_ID DEPT_NAME ---------- ---------- -----------------------------SA_REP 80 Sales SA_REP 80 Sales 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 ------------------------King Kochhar De Haan Hunold Ernst Lorentz Mourgos Rajs Davies Matos Vargas Zlotkey Abel Taylor Grant Whalen Hartstein Fay Higgins .... 160 rows selected. DEPT_NAME -----------------------------Administration Administration Administration Administration Administration Administration Administration Administration Administration Administration Administration Administration Administration Administration Administration Administration Administration Administration Administration

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 employees 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 2 from emp e, dept d 3 where 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 19 rows selected. SQL> select e.dept_id,d.dept_id 2 from emp e, dept d 3 where e.dept_id(+) = d.dept_id; DEPT_ID DEPT_ID ---------- ---------10 10 20 20 20 20 50 50 50 50 50 50 50 50 50 50 60 60 60 60 60 60 80 80 80 80 80 80 90 90 90 90 90 90 110 110 110 110 190 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 20 20 110 110 10 20 20 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 Hartsteins 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 ------------------------Hunold Ernst Lorentz JOB_ID ---------IT_PROG IT_PROG 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 ------------------------Whalen Mourgos Grant Hunold Abel Higgins Hartstein King 8 rows selected. JOB_ID SALARY ---------- ---------AD_ASST 4400 ST_MAN 5800 SA_REP 7000 IT_PROG 9000 SA_REP 11000 AC_MGR 12000 MK_MAN 13000 AD_PRES 24000

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; 1 row updated. SQL> UPDATE emp 2 SET job_id = (SELECT job_id FROM emp WHERE emp_id = 205), 3 salary = (SELECT salary FROM emp WHERE emp_id = 205) 4 WHERE emp_id = 124; 1 row updated.

SQL> DELETE FROM emp_history 2 WHERE emp_id = 206; 1 rows deleted. SQL> truncate table emp_history; Table truncated. 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> 2 3 4 5 insert all into sal_history values (empid,hiredate,sal) into mgr_history values (empid,mgrid,hiredate) select emp_id empid,hire_date hiredate, salary sal, manager_id mgrid 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.
FIRST TRANSACTION STARTS -- TIME=1 SECOND TRANSACTION STARTS

-- TIME=0

-- 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; no rows selected -- TIME=5 SQL> select FIRST_NAME from emp where emp_id=210; FIRST_NAME -------------------Alexander

-- TIME=4 SQL> commit; Commit complete.

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 tables 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 tables data segment according to storage definition at tables creation level:

TABLESPACE clause EXTENT storage

There are many different tablespace according to database user and object type (table or index). From Oracle 8i the tablespaces can be locally managed. In other word, STORAGE clause in the CREATE TABLE must not be defined. It can be managed through PCTFREE and PCTUSED parameters. From Oracle 9i segments can be locally managed, so PCTUSED parameters can be disregarded. 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.

DATABLOCK storage

INITRANS parameter

Table Creation - PCTFREE and PCTUSED


PCTUSED PCTFREE INSERT

DATABLOCK

New rows can be added to the row data area in the free portion of datablock that isnt allocated to PCTFREE.

PCTFREE parameter sets the minimum percentage of a datablock to be reserved as free space for possible updates to rows that already exists in that block.

HEAD

After a datablock is filled to the limit determined by PCTFREE, Oracle considers the block unaviable for the insertion of new rows until the percentage of that block falls 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 is necessary defining storage parameters also for indexes (PCTFREE must not be defiened for index).

NAME LIT MED BIG

TABLEINDEX DIMENSION <30MB [30MB, 50MB] >50MB

You might also like