You are on page 1of 51

Oracle – SQL 10g

© Tech Mahindra Limited 2008 Tech Mahindra Limited confidential


Objectives
At the end of this session,you will be able to:

 Write SELECT queries using FROM, WHERE, ORDER BY


clauses

 Understand ORACLE Architecture

 Understand Stages in Processing SQL Statements

 Use operators in SQL

 Use functions with SELECT statement

 Use Regular Expressions

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 2


Agenda
 Select Command

 Oracle Architecture

 Stages in processing SQL statement

 SQL Operators and Functions

 Single Row Functions

 Aggregate Functions

 Regular Expressions

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 3


Schema used for Queries
1. EMP
2. DEPT
3. SALGRADE

To see the structure of these tables in SQL*PLUS:

SQL> DESC emp


SQL> DESC dept
SQL> DESC salgrade

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 4


Data Query Language (DQL)
 SELECT is used for retrieving data from database

 Syntax: SELECT <col1>,<col2>… or <*>


FROM <tablename>;

 Example: displaying the records in Department table

SELECT * FROM dept;

 DEPTNO DNAME LOC


 --------- --------------- --------------
 10 ACCOUNTING NEW YORK
 20 RESEARCH DALLAS
 30 SALES CHICAGO
 40 OPERATIONS BOSTON

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 5


SELECT Query
 ALIAS is renaming default column name

 Select <Column Name1> <Alias Name1>, <Column


Name2> <Alias Name2> From <Table Name>

 Example: List the Deptno & Dname from Department

SELECT deptno "Department Number", dname FROM Dept;

 Department Number DNAME

 ---------------------------------------------
 10 ACCOUNTING
 20 RESEARCH

 30 SALES

 40 OPERATIONS

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 6


WHERE Clause
 Specifies criteria

 Example: List all employees who belong to department


number 20

SQL> SELECT empno, ename, deptno FROM emp


WHERE deptno=20;

 EMPNO ENAME DEPTNO

 --------- ---------- ---------

 7369 SMITH 20

 7566 JONES 20

 7788 SCOTT 20

 7876 ADAMS 20

 7902 FORD 20

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 7


DISTINCT Clause
 Allows to remove duplicates from the result set

 Syntax: SELECT DISTINCT columns FROM tables

 Example: List the number of jobs in emp table, displaying


jobs only once, even if duplicate values exist

SELECT DISTINCT job FROM emp;


 JOB
 ---------------
 ANALYST

 CLERK

 MANAGER

 PRESIDENT

 SALESMAN
CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 8
ORDER BY clause
 Sorts records using specified criteria in ascending or
descending order

 Syntax:
 ORDER BY <col>|<expression> [ASC | DESC] [, expression
[ASC | DESC] ...]

 Examples:

 SELECT * FROM Emp


 ORDER BY ename ASC;

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 9


Oracle Architecture

© Tech Mahindra Limited 2008 Tech Mahindra Limited confidential


Oracle Server Architecture

Oracle Server

Oracle Database Oracle Instance

Physical Logical • SGA Memory Structure

• Data Files • Tablespaces • Background Processes

• Control Files • Segments


• Redo Log Files • Extents
• Blocks

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 11


Oracle Server Components

I N S T A N C E
Server
Shared Pool System Global Area
Library Cache

Database Buffer Redo log


Data Dictionary Cache Buffer cache
Cache

PMON SMON DBWR LGWR CKPT Others

Data files Archived Log files


Server Process
Control files
Database
Parameter file (init.ora)
PGA
Redo log files Password file

User
User Process

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 1


2
Oracle Instance
 A means to access an Oracle database

 Can open & use only one database at a time

 Consists of SGA memory structure & background processes


 Allocated in the virtual memory of the computer where the
oracle server resides

 System Global Area (SGA) stores database information


 Consists of several memory structures:
 Shared Pool
 Database Buffer Cache
 Redo Log Buffer

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 1


3
Shared Pool
 Stores the most recently executed SQL statements & used
data from the data dictionary

 The server process uses this area to compile the SQL


statement

 Has two components:

 Library Cache: Stores information about the most recently


used SQL statements

 The shared SQL area contains:


 The text of SQL statement
 The Parse Tree: Compiled version of a statement
 The Execution Plan

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 1


4
Shared Pool (Contd…)
 Data Dictionary Cache (Dictionary / Row Cache):
 A collection of the most recently used definitions in the
database

 Stores information about database files, tables, indexes,


columns, users, privileges etc.

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 1


5
Database Buffer Cache
 Stores the most recently used data

 The data is read from, and written to data files

 Size of each buffer in the buffer cache is equal to the size of


an Oracle block

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 1


6
Redo Log Buffer
 Records changes made to a database using the instance

 The server process records changes in the redo log buffer

 It records the block that is changed, the location of the


change and the new value

 The buffer is reused after it is filled, once all the old redo
entries are recorded in the redo log files

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 1


7
Background Processes
Log Writer (LGWR):

 Performs sequential writes from the redo log buffer to the


redo log file
 When a transaction commits
 When the redo log buffer is one-third full
 When there is more than a megabyte of changes recorded in
the redo log buffer
 Before DBW0 writes modified blocks in the database buffer
cache to the data files

 Confirms COMMIT only after the redo is written to disk

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 1


8
Background Processes (Contd…)
Database Writer (DBW0):

 The server process records changes to rollback & data


blocks in the buffer cache

 The DBW0 writes the dirty buffers from the database buffer
cache to the data files

 Ensures that a sufficient number of free buffers are available


in the database buffer cache

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 1


9
Background Processes (Contd…)
 Server processes make changes only in the buffer cache,
and the DBW0 defers writing to the data files until:
 A number of dirty buffers reach the threshold value, or

 A process scans a specified number of blocks when scanning


for free buffers and cannot find any, or

 A timeout occurs (every three seconds), or

 A checkpoint occurs

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 2


0
Background Processes (Contd…)
System Monitor (SMON):

 Recovers the instance when a database is started

 Rolls forward changes in the redo logs

 Rolls back uncommitted transactions

 Combines adjacent areas of free space in the data files

 De-allocates temporary segments used to store data during


SQL statement processing

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 2


1
Background Processes (Contd…)
Process Monitor (PMON):

 Cleans up resources if one of the processes fail

 Includes:
 Rolling back user transactions

 Releasing all currently held table or row locks

 Freeing other resources currently reserved by the user

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 2


2
Oracle Database
 Logical Structure: Tablespaces

 An Oracle Database can be logically grouped into smaller logical


areas of space called tablespaces

 A tablespace can belong to only one database at a time

 Each tablespace consists of one or more OS files (called data files)

SYSTEM ACCOUNTING SALES


Tablespace Tablespace Tablespace

Data Data Data Data


File File File File

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 2


3
Segments
 Space allocated for a specific logical structure within a tablespace

 A tablespace may consist of one or more segments

 A segment cannot span tablespaces; However, a segment can span


multiple data files that belong to the same tablespace

 Each segment is made up of one or more extents

Segment Types Description


Data Stores the data associated with tables

Index Each index file has an index segment

Temporary Stores temporary data during sorting operations

Rollback Rolls back uncommitted transactions for users

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 2


4
Segments (Contd…)
 Extents:
 Space allocated to a segment by extents

 One or more extents make up a segment

 Extent is a set of contiguous Oracle blocks

 Must exist in one data file

 Data Blocks:
 At the finest level of granularity, the data is stored in data
blocks
 One data block corresponds to one or more OS blocks allocated
from the existing data file
 Data block size should be a multiple of the OS block size to
avoid unnecessary I/O

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 2


5
Segments (contd…)

Table
Segment

8KB 8KB 8KB 8KB 8KB 8KB 8KB 8KB 8KB

8KB 8KB 8KB 8KB 8KB 8KB 8KB 8KB 8KB

Data Block 8KB 8KB 8KB 8KB 8KB 8KB 8KB 8KB 8KB

Extent Extent Extent

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 2


6
Oracle Database
 A collection of data that is treated as a unit, which stores &
retrieves related information

 Physical structure is a set of OS files in the database

 Three file types:


 Control Files:
 Contain information required to maintain & verify database integrity
 A database needs at least one control file

 Data Files:
 At least one data file for each tablespace
 Can belong to only one tablespace
 Contain the data in database, including tables, indexes, rollback segments &
temp segments

 Online Redo Logs:


 Contain a record of changes made to the database to enable data recovery
 At least two redo log files for a database

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 2


7
Other Files
 Parameter File: Defines the characteristics of an oracle
instance

 Listener.ora File:
 Resides on the host node
 Client requests use the listener processes for connection to the
database

 Tnsnames.ora File: Resides on the client machine & stores


Oracle net services names

 Password File: Authenticates privileged database users

 Archived Redo Logs: Are backups of the online redo logs

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 2


8
Stages in Processing SQL Statements
A query has to go through:
1. Parse:
 An SQL statement is passed from user process to Oracle
 A parsed representation of the statement is loaded into a
shared SQL area, which:
 Searches for identical statements, else translates the statement,
verifying it to be a valid statement
 Checks syntax, object names from data dictionary & privileges
 Locks objects used during parse
 Creates & stores the execution plan
 For distributed statements, routs all or parts of the statement to
remote nodes that contain referenced data

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 2


9
Stages (Contd…)
2. Bind:
 Oracle needs values for the variables listed in any statement
 Binding obtains values for the variables

3. Execute: Processes the statements


 For INSERT, no rows are locked as no data is being changed
 For UPDATE & DELETE, all rows that the statement affects are locked
from use by other users
 Released after the next COMMIT, ROLLBACK or SAVEPOINT for the
transaction
 This ensures data integrity

4. Fetch: Returns rows to the user process


 Rows are selected & ordered (if requested by the query)
 Each successive fetch retrieves another row of the result, until the last
row has been fetched

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 3


0
SQL Operators
 Arithmetic
 +,-,*,/

 Relational
 = , < , > , <= , >=
 < >, != , ^=

 Boolean
 AND, OR, NOT

 Set Operators
 UNION, UNION ALL, INTERSECT, MINUS

 Others
 IN, BETWEEN
 LIKE , IS NULL

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 3


1
Relational Operator
Example: List the employee name whose employee number is
7900

SELECT ename FROM Emp


WHERE empno = 7900;

ENAME
----------
JAMES

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 3


2
Relational Operators
Example: List the employees whose hire date is before 28-SEP-81

SELECT empno, ename, hiredate, deptno


FROM emp WHERE hiredate < = '28-SEP-81';

EMPNO ENAME HIREDATE DEPTNO

---------------------------------------------------

7369 SMITH 17-DEC-80 20

7499 ALLEN 20-FEB-81 30

7521 WARD 22-FEB-81 30

7566 JONES 02-APR-81 20

7654 MARTIN 28-SEP-81 30

7698 BLAKE 01-MAY-81 30

7782 CLARK 09-JUN-81 10

7844 TURNER 08-SEP-81 30


CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 3
3
Logical Operators
 Example: List the employees who get salary in the range of
1500 and 3000

 SELECT empno, ename, sal


 FROM emp WHERE sal >= 1500 AND sal <= 3000;

 Example: List the employee number & names of department


10 & 20

 SELECT empno, ename, sal


 FROM emp WHERE deptno=10 OR deptno=20;

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 3


4
Other Operators
SELECT empno, ename, deptno
FROM emp WHERE sal BETWEEN 1500 AND 2500;

SELECT empno, ename, sal


FROM emp WHERE deptno IN(10,20);

SELECT empno, ename


FROM emp WHERE ename LIKE 'S%';
SELECT empno, ename,comm
FROM emp WHERE comm IS NULL;

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 3


5
Recap
 SELECT * from emp;

 SELECT ename, empno FROM emp;

 SELECT ename, deptno FROM emp WHERE deptno = 10;

 SELECT ename, sal,job FROM emp


WHERE job = 'MANAGER';

 SELECT DISTINCT job FROM emp;

 SELECT empno, ename FROM emp WHERE comm IS NULL;

 *NULL is absence of information

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 3


6
ORDER BY Clause
 SELECT empno,ename,sal FROM emp
ORDER BY ename;

 SELECT ename FROM emp


ORDER BY ename DESC;

 SELECT job,ename FROM emp


ORDER BY job,ename;

 SELECT job,ename FROM emp


ORDER BY job, ename DESC;

 SELECT ename,job FROM emp


ORDER BY 1 DESC;

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 3


7
Single Row Functions
 Manipulate data items

 Accept arguments and return one value

 Act on each row returned

 Return one result per row

 May modify the data type

 Can be nested

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 3


8
Single Row Functions (Contd…)
 Numeric

 Character

 Date

 Conversion

 Aggregate Functions

 Regular Expressions

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 3


9
Single Row Functions: Numeric
 NVL: Converts NULL values to required values

SELECT sal + NVL(comm,0) FROM emp;

 ROUND (m,n): Rounds values to the specified decimal

SELECT ROUND(52.5) FROM dual; o/p: 53

 TRUNC (m,n): Truncates values to the specified decimal

SELECT TRUNC(56.223,1) FROM dual; o/p : 56.2

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 4


0
Single Row Functions: Character
 CONCAT (col1, col2)

 SELECT CONCAT (ename,job) FROM emp;

 UPPER, LOWER, INITCAP

 SELECT UPPER(ename), LOWER(ename),


INITCAP(ename) FROM emp;

 TRIM

 SELECT TRIM(ename) FROM emp;

 LTRIM, RTRIM

 SELECT LTRIM(ename), RTRIM(ename) FROM emp;

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 4


1
Single Row Functions: Character (Contd…)
 LENGTH (STRING)

SELECT LENGTH (ename) FROM emp;

 INSTR(STRING, ‘search strng’, start position)

SELECT INSTR(ename, 'S',1) FROM emp;

 SUBSTR(STRING, ‘start pos’, ‘no. of chs’);

SELECT SUBSTR(ename,1,3) FROM emp;

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 4


2
Single Row Functions: Date
 The SYSDATE function returns the current date & time as a
DATETIME value

 TO_CHAR: Converts date into a required character format

SELECT TO_CHAR(hiredate, 'DD-MON-YY') FROM EMP;

 ADD_MONTHS: Adds months to a date

SELECT ADD_MONTHS(hiredate,11) FROM emp;

 MONTHS_BETWEEN: Finds the number of months between


two dates

SELECT MONTHS_BETWEEN(sysdate,hiredate) FROM emp;

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 4


3
Conversion Functions
 TO_CHAR(X): Converts the value of X to a character or
a date to a character

SELECT TO_CHAR(1981) FROM dual;

 TO_NUMBER(X): Converts a nonnumeric value X to a number

SELECT TO_NUMBER('1221') FROM dual;

 TO_DATE(X,[Y]): Converts a non-date value X to a date using


the format specified by Y

SELECT TO_DATE('12-FEB-2007') FROM dual;

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 4


4
Aggregate Functions
 SUM: Returns the sum of the column values provided
 SELECT SUM(sal) "Total Sal" FROM emp WHERE deptno = 20;

 AVG(n): Returns average value of n


 SELECT AVG(Sal) "Average" FROM Emp ;

 COUNT: Returns the number of rows for the specified column


 count(*) – Slow SELECT count(*) "Tot_row" FROM Emp;
 count(empno) – Fast SELECT count(ename) "Tot_row" FROM Emp;

 MIN: Returns the minimum value of an expression


 SELECT MIN(Sal) "Minimum" FROM emp;

 MAX: Returns the maximum value of an expression


 SELECT MAX(Sal) "Maximum" FROM emp;

 Aggregate functions ignore NULL values by default

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 4


5
Regular Expressions
 A powerful tool to search & manipulate character data

 Can be implemented with SQL functions and a WHERE


clause operator

 Specified using two types of characters:


 Meta characters
 Literals

 Uses:
 Data Validation
 Identifies duplicate word occurrences
 Locates patterns like HTML tags, numbers, dates etc.

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 4


6
Some More Functions
 REGEXP_LIKE:
 REGEXP_LIKE(source_string, pattern [,match_parameter])
 E.g. SELECT ename FROM emp
WHERE REGEXP_LIKE(ename,'[sS][cC][oO][tT]')
 ENAME
 ----------
 SCOTT

 REGEXP_INSTR:
 REGEXP_INSTR(source, regexp, position, occurrence,
return_option, modes)

 Difference between INSTR & REGEXP_INSTR: REGEXP_INSTR lets us specify a


pattern instead of a specific search string
 E.g. SELECT regexp_substr('Oracle Database 10g is first grid aware
database', '[0-9]+') version FROM
dual;
 VE
 ----
 10

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 4


7
Some More Functions (Contd…)
 REGEXP_SUBSTR:
 REGEXP_SUBSTR(source, regexp, position, occurrence, modes)

 Options of match modes:

‘i ' : specifies case-insensitive matching

'c' : specifies case-sensitive matching

'n' : allows the period (.), which is the match-any-character


character, to match the newline character

'm‘ : treats the source string as multiple lines

 E.g. SELECT regexp_substr('Oracle Database 10g is first


grid aware database','[0-9]+') version FROM
dual;

 VE
 ---
 10

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 4


8
Some More Functions (Contd…)
 REGEXP_REPLACE:
 REGEXP_REPLACE (source, regexp, replacement, position,
occurrence, modes)
 Specifically used to remove extra spaces with the REPLACE
function, earlier we needed to list exactly how many spaces to be
replaced
 Also used for back referencing

 An Example,
SELECT regexp_replace('Oracle10g','([[:alpha:]]+)
([[:digit:]]
+.)', '\1\2') FROM dual;


REGEXP_REP

----------------

Oracle 10g

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 4


9
Summary
In this session, we learned:

 To write SELECT queries using FROM, WHERE, GROUP BY,


HAVING ORDER BY clauses

 The ORACLE Architecture

 The Stages in Processing SQL Statements

 To use operators in SQL

 To use functions with SELECT statement

 To use Regular Expressions

CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited 5


0
Thank You

© Tech Mahindra Limited 2008 Tech Mahindra Limited confidential

You might also like