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

Oracle SQL

SQL is a standard language for communicating with relational database management systems (RDBMS). It was originally based on IBM's SEQUEL but is now standardized and used widely. SQL allows users to create, modify, query, delete, and grant access to data in a database. It supports various data types including character, number, date/time, binary, and large object types. Pseudocolumns like ROWID and ROWNUM provide additional information for rows. Implicit and explicit conversions exist between different data types.

Uploaded by

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

Oracle SQL

SQL is a standard language for communicating with relational database management systems (RDBMS). It was originally based on IBM's SEQUEL but is now standardized and used widely. SQL allows users to create, modify, query, delete, and grant access to data in a database. It supports various data types including character, number, date/time, binary, and large object types. Pseudocolumns like ROWID and ROWNUM provide additional information for rows. Implicit and explicit conversions exist between different data types.

Uploaded by

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

Oracle SQL

SQL (Seequel) -History


› The language, Structured English Query Language (SEQUEL)
was developed by IBM Corporation, Inc., to use Codd's model.
SEQUEL later became SQL (still pronounced "sequel"). In 1979,
Relational Software, Inc. (now Oracle) introduced the first
commercially available implementation of SQL. Today, SQL is
accepted as the standard RDBMS language.
› Based on Dr. EF Codds paper A Relational Model of Data for
Large Shared Data Banks“ (1970)
Introduction to SQL
› Structured Query Language
– Standard command set used to communicate with the RDBMS.
– Creating, modifying, querying the database, deleting, granting
access to users
– High Level Language provides greater degree of abstractions
– Simple and easy to learn
– Performed at set level
Database Objects
› Database
› Table
› View
› Rule
› Stored Procedure
› Index
› Trigger
SQL Data Types
Character Data types
› Character (CHAR) :Max Size 2000: S
› Character Varying (VARCHAR2):4000
› NCHAR : UTF-8/UTF-16 : 2000/1000
› NVARCHAR2:UTF-8/UTF-16:4000/2000
Number: Number(p,s) p=40 , s=-84 to 127
Float: 22
Value BINARY_FLOAT BINARY_DOUBLE
Maximum positive finite 3.40282E+38F 1.79769313486231E+
value 308
Minimum positive finite 1.17549E-38F 2.22507485850720E-
value 308
SQL Data Types
› LONG : 2GB present only for Backward compatibility Use NCLOB,CLOB,BLOB for Large
Objects
DateTime:
Datetime Field Valid Values for Datetime Valid Values for INTERVAL
YEAR -4712 to 9999 (excluding year 0) Any positive or negative integer
MONTH 01 to 12 0 to 11
DAY 01 to 31 (limited by the values of MONTH and YEAR, according Any positive or negative integer
to the rules of the current NLS calendar parameter)
HOUR 00 to 23 0 to 23
MINUTE 00 to 59 0 to 59
SECOND 00 to 59.9(n), where 9(n) is the precision of time fractional 0 to 59.9(n), where 9(n) is the
seconds. The 9(n) portion is not applicable for DATE. precision of interval fractional
seconds
TIMEZONE_HOUR -12 to 14 (This range accommodates daylight saving time Not applicable
changes.) Not applicable for DATE or TIMESTAMP.
TIMEZONE_MINUTE 00 to 59. Not applicable for DATE or TIMESTAMP. Not applicable
(See note at end of table)
TIMEZONE_REGION Query the TZNAME column of the V$TIMEZONE_NAMES data Not applicable
dictionary view. Not applicable for DATE or TIMESTAMP. For a
complete listing of all time zone region names, refer to 
Oracle Database Globalization Support Guide.
SQL Data Types
› Date: stored as Julian Date, Starts From January 1, 4712 BC
› BFILE:access to binary file LOBs that are stored in file systems outside
Oracle Database, can be upto  264-1 bytes
› BLOB : stored as bitstream, can stored up to (4 gigabytes -1) * (the
value of the CHUNK parameter of LOB storage), If table spaces use
standard block then size would be  (4 gigabytes - 1) * (database
block size).
› CLOB:stores single-byte and multibyte character data (4 gigabytes -
1) * (the value of the CHUNK parameter of LOB storage) of character
data If table spaces use standard block then size would be  (4
gigabytes - 1) * (database block size).
› NCLOB: stores Unicode character data, size is similar to CLOB
PseduoColumn
› ROWID 
• The data block of the data file containing the row. The length of
this string depends on your operating system.
• The row in the data block.
• The database file containing the row. The first data file has the
number 1. The length of this string depends on your operating
system.
• The data object number, which is an identification number
assigned to every database segment.
Pseduocolumn
› ROWNUM:
› For each row returned by a query, the ROWNUM
pseudocolumn returns a number indicating the order in
which Oracle selects the row from a table or set of joined
rows. The first row selected has a ROWNUM of 1, the
second has 2, and so on.
› You can use ROWNUM to limit the number of rows
returned by a query
› Select * from emp where rownum <11
ANSI Data Type and Oracle Data Type
mapping
ANSI SQL Data Type Oracle Data Type
CHARACTER(n) CHAR(n)
CHAR(n)

CHARACTER VARYING(n) VARCHAR2(n)


CHAR VARYING(n)

NATIONAL CHARACTER(n) NCHAR(n)


NATIONAL CHAR(n)
NCHAR(n)

NATIONAL CHARACTER VARYING(n) NVARCHAR2(n)


NATIONAL CHAR VARYING(n)
NCHAR VARYING(n)

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

from Datetime/ TO_CHAR (date) -- -- -- -- -- -- -- --


Interval TO_NCHAR (datetime)

from RAW RAWTOHEX -- -- -- -- -- TO_BLOB -- --


RAWTONHEX
from ROWID ROWIDTOCHAR -- -- -- -- -- -- -- --

from LONG / LONG -- -- -- -- -- -- TO_LOB -- --


RAW
from CLOB, NCLOB, TO_CHAR -- -- -- -- -- TO_CLOB -- --
BLOB TO_NCHAR TO_NCLOB
from CLOB, NCLOB, TO_CHAR -- -- -- -- -- TO_CLOB -- --
BLOB TO_NCHAR TO_NCLOB
from BINARY_FLOAT TO_CHAR (char.) TO_NUMBER -- -- -- -- -- TO_BINARY_FL TO_BINARY_DO
TO_NCHAR (char.) OAT UBLE
from TO_CHAR (char.) TO_NUMBER -- -- -- -- -- TO_BINARY_FL TO_BINARY_DO
BINARY_DOUBLE TO_NCHAR (char.) OAT UBLE
Arithmatic OPerators
› +,-: Add , Subtract, Unary + and Unary -
› *,/: Multiply,Division
› Concatenation Operator (Strings & CLOB):
› ||
Set Operators
Operator Returns

UNION All distinct rows selected by either query

UNION ALL All rows selected by either query, including all duplicates

INTERSECT All distinct rows selected by both queries

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 :

4*3 will be evaluated first and the result will be added to 10


Conditions
› >, <,>=,<=,=,
› !=,^=,<>
› AND, OR , NOT
› IS NULL, IS NOT NULL
› IN, NOT IN
› LIKE, NOT LIKE (Pattern Matching)
› EXISTS
› IS OF TYPE
› ANY
› SOME
› ALL
› IS NOT NAN (Floating Point Condition)
› IS NOT INFINITE (Floating Point Condition)
› BETWEEN Expr1 and Expr2 == (a >= b and b <= c)
Truth Table For AND,OR and NOT
NOT Truth Table

-- 1 0 UNKNOWN
NOT 0 1 UNKNOWN

AND Truth Table

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

OR TRUE FALSE UNKNOWN


TRUE TRUE TRUE TRUE
FALSE TRUE FALSE UNKNOWN
UNKNOWN TRUE UNKNOWN UNKNOWN
Condition Precedence
Oracle evaluates conditions with higher precedence before evaluating those with lower precedence.

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

Type of Condition Purpose

SQL operators are evaluated before SQL conditions See Operator Precedence

=, !=, <, >, <=, >=, comparison

IS [NOT] NULL, LIKE, [NOT] BETWEEN, [NOT] IN, EXISTS, IS comparison


OF type
NOT exponentiation, logical negation

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

– SELECT employee_id, UPPER(last_name), department_id FROM


employees WHERE last_name =INITCAP(’higgins’);
› Number Functions
– Round – Rounded of value
– Trunc – truncate to decimal value
– Mod – remainder of m/n
› SELECT last_name, salary, MOD(salary, 5000) FROM employees WHERE
job_id = ’SA_REP’;

› 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;

› RIGHT OUTER JOIN


– This type of join returns all rows from the RIGHT-hand table specified in the
ON condition and only those rows from the other table where the joined
fields are equal (join condition is met).

› LEFT OUTER JOIN


– This type of join returns all rows from the LEFT-hand table specified in the
ON condition and only those rows from the other table where the joined
fields are equal (join condition is met).

› FULL OUTER JOIN


– This type of join returns all rows from the LEFT-hand table and RIGHT-hand
table with nulls in place where the join condition is not met.
› SELECT orders.order_id, orders.order_date,
suppliers.supplier_name FROM suppliers RIGHT OUTER
JOIN orders ON suppliers.supplier_id = orders.supplier_id;
› SELECT orders.order_id, orders.order_date,
suppliers.supplier_name FROM suppliers, orders WHERE
suppliers.supplier_id(+) = orders.supplier_id;
› SELECT suppliers.supplier_id, suppliers.supplier_name,
orders.order_date FROM suppliers LEFT OUTER JOIN
orders ON suppliers.supplier_id = orders.supplier_id;
› SELECT suppliers.supplier_id, suppliers.supplier_name,
orders.order_date FROM suppliers, orders WHERE
suppliers.supplier_id = orders.supplier_id(+);
› SELECT suppliers.supplier_id, suppliers.supplier_name,
orders.order_date FROM suppliers FULL OUTER JOIN
orders ON suppliers.supplier_id = orders.supplier_id;
› Self Join
– SELECT worker.last_name || ’ works for ’ || manager.last_name
FROM employees worker, employees manager WHERE
worker.manager_id = manager.employee_id ;
SubQuery
› A subquery is a SELECT statement that is embedded in a clause of
another SELECT statement.
› You can build powerful statements out of simple ones by using
subqueries.
› They can be very useful when you need to select rows from a table
with a condition that depends on the data in the table itself.
– SELECT last_name FROM employees WHERE salary > (SELECT salary FROM
employees WHERE last_name = ’Abel’);
› Enclose subqueries in parentheses.
› Place subqueries on the right side of the comparison condition.

– Single Row Subquery


› SELECT last_name, job_id, salary FROM employees WHERE job_id =(SELECT job_id
FROM employees WHERE employee_id = 141) AND salary > (SELECT salary FROM
employees WHERE employee_id = 143);
– Multiple-Row Subqueries (returns Multiple Values) (IN , ANY, ALL)
› SELECT last_name, salary, department_id FROM employees WHERE salary IN
(SELECT MIN(salary) FROM employees GROUP BY department_id);

You might also like