Oracle SQL
Oracle SQL
NUMERIC[(p,s)] NUMBER(p,s)
DECIMAL[(p,s)] (Note 1)
INTEGER NUMBER(38)
INT
SMALLINT
FLOAT (Note 2) FLOAT(126)
DOUBLE PRECISION (Note 3) FLOAT(126)
REAL (Note 4) FLOAT(63)
Implicit Data Type Conversion
DATETIME
VARCHAR NVARCHA / BINARY_F BINARY_D
Data Type CHAR 2 NCHAR R2 DATE INTERVAL NUMBER LOAT OUBLE LONG RAW ROWID CLOB BLOB NCLOB
CHAR -- X X X X X X X X X X X X X X
VARCHAR2 X -- X X X X X X X X X X X -- X
NCHAR X X -- X X X X X X X X X X -- X
NVARCHAR2 X X X -- X X X X X X X X X -- X
DATE X X X X -- -- -- -- -- -- -- -- -- -- --
DATETIME/ X X X X -- -- -- -- -- X -- -- -- -- --
INTERVAL
NUMBER X X X X -- -- -- X X -- -- -- -- -- --
BINARY_FLOAT X X X X -- -- X -- X -- -- -- -- -- --
BINARY_DOUBLE X X X X -- -- X X -- -- -- -- -- -- --
LONG X X X X -- XFoot 1 -- -- -- -- X -- X -- X
RAW X X X X -- -- -- -- -- X -- -- -- X --
ROWID X X X X -- -- -- -- -- -- -- -- -- -- --
CLOB X X X X -- -- -- -- -- X -- -- -- -- X
BLOB -- -- -- -- -- -- -- -- -- -- X -- -- -- --
NCLOB X X X X -- -- -- -- -- X -- -- X -- --
Explicit Data Type Conversion
to
to LONG,L to
CHAR,VARCHAR2,NCH ONG to CLOB, to BINARY_DOUBL
ourceData Type AR,NVARCHAR2 to NUMBER to Datetime/Interval to RAW to ROWID RAW NCLOB,BLOB BINARY_FLOAT E
from CHAR, TO_CHAR (char.) TO_NUMBER TO_DATE HEXTORAW CHARTO -- TO_CLOB TO_BINARY_FL TO_BINARY_DO
VARCHAR2, NCHAR, TO_NCHAR (char.) TO_TIMESTAMP =ROWID TO_NCLOB OAT UBLE
NVARCHAR2 TO_TIMESTAMP_TZ
TO_YMINTERVAL
TO_DSINTERVAL
from NUMBER TO_CHAR (number) -- TO_DATE -- -- -- -- TO_BINARY_FL TO_BINARY_DO
TO_NCHAR (number) NUMTOYM- INTERVAL OAT UBLE
NUMTODS- INTERVAL
UNION ALL All rows selected by either query, including all duplicates
MINUS All distinct rows selected by the first query but not the
second
Operator Precedence
Oracle evaluates operators with equal precedence from left to right within an expression.
lists the levels of precedence among SQL operators from high to low.
Operators listed on the same line have the same precedence.
Operator Operation
+, - (as unary Identity, negation, location in hierarchy
operators), PRIOR, CONNECT_BY_ROOT, CO
LLATE
*, / Multiplication, division
+, - (as binary operators), || Addition, subtraction, concatenation
SQL conditions are evaluated after SQL See "Condition Precedence"
operators
Example
10+4*3 :
-- 1 0 UNKNOWN
NOT 0 1 UNKNOWN
AND 1 0 UNKNOWN
1 1 0 UNKNOWN
0 0 0 0
UNKNOWN UNKNOWN 0 UNKNOWN
Truth Table For AND,OR and NOT
OR Truth Table
Oracle evaluates conditions with equal precedence from left to right within an expression, with the
following exceptions:
•Left to right evaluation is not guaranteed for multiple conditions connected using AND
•Left to right evaluation is not guaranteed for multiple conditions connected using OR
AND conjunction
OR disjunction
Types of SQL Commands
› Query
› Update, insert and delete
› Creating, modifying and deleting database objects
› Controlling access to the database
› Data integrity and consistancy
Types
› Data Definition Command (Create, Alter,
Drop,Truncate,Comment)
› Data Manipulation Language (Update, Insert,Delete,
Merge,Call,Explain Plan)
› Data Query Language (Select)
› Data Control Language (Grant, Revoke)
› Transaction Control Statements (Commit, Rollback and
Savepoint)
Basic select statement
› A SELECT statement retrieves information from the database.
Using a SELECT statement, you can do the following:
– Projection: You can use the projection capability in SQL to
choose the columns in a table that you want returned by your
query. You can choose as few or as many columns of the table
as you require.
– Selection: You can use the selection capability in SQL to choose
the rows in a table that you want returned by a query. You can
use various criteria to restrict the rows that you see.
– Joining: You can use the join capability in SQL to bring together
data that is stored in different tables by creating a link between
them. You learn more about joins in a later lesson.
– In its simplest form, a SELECT statement must include the
following:
› A SELECT clause, which specifies the columns to be displayed
› A FROM clause, which specifies the table containing the columns
listed in the SELECT clause
› Using the following simple rules and guidelines, you can
construct valid statements that are both easy to read and
easy to edit:
– SQL statements are not case sensitive, unless indicated.
– SQL statements can be entered on one or many lines.
– Keywords cannot be split across lines or abbreviated.
– Clauses are usually placed on separate lines for readability and ease
of editing.
– Indents should be used to make code more readable.
– Keywords typically are entered in uppercase; all other words, such as
table names and columns, are entered in lowercase
› Select * from tablename
› Select employeeid, employeename from employee
› Select salary, salary+200 from employee (Arithmetic)
› Select employeeid as id from employee (Alias)
› Select name||employeeid from employee (Concat)
› Select name || ‘salary is’ || salary as “employee salary”
from employee [String Literals]
› Select distinct salary from employee
Restricting and sorting data
› Limiting the Rows Selected
– Use where clause in the select statement with condition
– Select * from employee where salary = 10000;
– Charater string and date should be enclose in ‘’
– The default date display is DD-MON-RR
– Select * from employees where salary Between 5000 AND 7500
– Select * from employees where ID IN(100,101,102)
– Select * from employees where name LIKE ‘s%’
– AND OR NOT – Logical operator in the condition
› Order By
– Select id,salary from employee order by salary
› Used to sort the rows.
› Should be the last statement
› Select id, salary*12 annsal from employee order by annsal
› Order of execution
– FROM clause
– WHERE clause
– SELECT clause
– ORDER BY clause
Single Row Functions
› Functions are a very powerful feature of SQL and can be used to do the
following:
– Perform calculations on data
– Modify individual data items
– Manipulate output for groups of rows
– Format dates and numbers for display
– Convert column data types
– SQL functions sometimes take arguments and always return a value.
› These functions operate on single rows only and return one result per
row.
› The different types of single-row functions.
– Character - Accept character input and can return both character and
number values
– Number - Accept numeric input and return numeric values
– Date - Operate on values of the DATE data type (All date functions return a
value of DATE data type except the MONTHS_BETWEEN function, which
returns a number.)
– Conversion - Convert a value from one data type to another
› Character Function
– LOWER – Display as Lowercase
– UPPER – Display Upper case
– INITCAP – Display Initial letter as Caps
– CONCAT - Joins values together (You are limited to using two
parameters with CONCAT.)
– SUBSTR - Extracts a string of determined length
– LENGTH – Shows the length of a string as a numeric value
– INSTR - Finds numeric position of a named character
– LPAD | RPAD - Pads the character value right-justified / Left -
Justified
– TRIM - Trims heading or trailing characters
› Date Functions
– The default date display format is DD-MON-RR
– SYSDATE is a date function that returns the current database server
date and time.
– Select SYSDATE from employee
› SELECT employee_id, hire_date, MONTHS_BETWEEN
(SYSDATE, hire_date) TENURE, ADD_MONTHS (hire_date,
6) REVIEW, NEXT_DAY (hire_date, ’FRIDAY’),
LAST_DAY(hire_date) FROM employees WHERE
MONTHS_BETWEEN (SYSDATE, hire_date) < 36;
› Conversion Functions
› Implicit
› SELECT employee_id, TO_CHAR(hire_date, ’MM/YY’)
Month_Hired FROM employees WHERE last_name =
’Higgins’;
› SELECT last_name, TO_CHAR(hire_date, ’DD-Mon-YYYY’)
FROM employees WHERE hire_date < TO_DATE(’01-Jan-
90’, ’DD-Mon-RR’);
› NVL – To convert a null value to an actual value
› NVL2 - The NVL2 function examines the first expression. If the
first expression is not null, then the NVL2 function returns the
second expression. If the first expression is null, then the third
expression is returned.
› NULLIF - The NULLIF function compares two expressions. If
they are equal, the function returns null
› Coalese - function returns the first non-null expression in the
list
› CASE expressions let you use IF-THEN-ELSE logic in SQL
statements without having to invoke procedures.
– SELECT last_name, job_id, salary, CASE job_id WHEN ’IT_PROG’ THEN
1.10*salary WHEN ’ST_CLERK’ THEN 1.15*salary WHEN ’SA_REP’ THEN
1.20*salary ELSE salary END "REVISED_SALARY“ FROM employees;
› The DECODE function decodes an expression in a way similar
to the IF-THEN-ELSE logic used in various languages.
– SELECT last_name, job_id, salary, DECODE(job_id, ’IT_PROG’,
1.10*salary, ’ST_CLERK’, 1.15*salary, ’SA_REP’, 1.20*salary, salary)
REVISED_SALARY FROM employees;
Aggregate Functions
› Group Functions
– Unlike single-row functions, group functions operate on
sets of rows to give one result per group.
– AVG - Average value of n, ignoring null values
– COUNT - Number of rows, where expr evaluates to
something other than null
– MAX - Maximum value of expr
– MIN – Minimum Value of Expr
– STDDEV - Standard deviation of n
– SUM - Sum values of n
– VARIANCE - Variance of n
› SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary) FROM employees
› SELECT MIN(last_name), MAX(last_name) FROM employees;
› SELECT COUNT(*) FROM employees WHERE department_id = 50;
› SELECT COUNT(commission_pct) FROM employees WHERE department_id =
80;
› SELECT COUNT(DISTINCT department_id) FROM employees;
› SELECT department_id, AVG(salary) FROM employees GROUP BY
department_id ;
› SELECT department_id, MAX(salary) FROM employees GROUP BY
department_id HAVING MAX(salary)>10000 ;
Displaying Data From Multiple Tables
› SELECT last_name, department_name dept_name FROM employees,
departments; (Cartesian Product)
› Equijoin - Equijoins are also called simple joins
› Non-equijoin
› Outer join
› Self join
› When data from more than one table in the database is required, a join
condition is used.
› Rows in one table can be joined to rows in another table according to
common values existing in corresponding columns, that is, usually
primary and foreign key columns.
› When writing a SELECT statement that joins tables, precede the
column name with the table name for clarity and to enhance database
access.
› If the same column name appears in more than one table, the column
name must be prefixed with the table name.
› Equi Join
– SELECT employees.employee_id, employees.last_name,
employees.department_id, departments.department_id,
departments.location_id FROM employees, departments WHERE
employees.department_id = departments.department_id AND
last_name = ’Matos’;
– SELECT e.employee_id, e.last_name, e.department_id, d.department_id,
d.location_id FROM employees e , departments d WHERE
e.department_id = d.department_id;
– SELECT e.last_name, d.department_name, l.city FROM employees e,
departments d, locations l WHERE e.department_id = d.department_id
AND d.location_id = l.location_id;
› NON EQUI JOINS
– SELECT e.last_name, e.salary, j.grade_level FROM employees e, job_grades j
WHERE e.salary BETWEEN j.lowest_sal AND j.highest_sal;