SQL and PL - SQL Referance
SQL and PL - SQL Referance
SQL and PL - SQL Referance
Topic
SQL Select
SQL Insert
Page 1
Sheet1
SQL NULLs
Page 2
Sheet1
Normalization
Page 3
Sheet1
SQL SubQueries
Page 4
Sheet1
SQL Difference Truncate / Drop
SQL Difference HAVING / WHERE
SQL REPLACE
SQL TOP
Page 5
Sheet1
SQL Count
Page 6
Sheet1
SQL DATEPART()
SQL Convert()
Page 7
Sheet1
SQL Insert Into Select
Page 8
Sheet1
SQL ROLLUP
SQL CUBE
SQL STUFF()
SQL Count_Big
SQL Binary_Checksum
Page 9
Sheet1
SQL Checksum_AGG
SQL Identity
SQL sp_columns
Page 10
Sheet1
SQL sp_who
SQL Session
SQL sp_executesql
Page 11
Sheet1
SQL Pivot
SQL Merge
SQL Has_perms_by_name
Page 12
Sheet1
Page 13
Sheet1
PL/SQL Procedures
Page 14
Sheet1
PL/SQL Functions
PL/SQL Collections
Page 15
Sheet1
PL/SQL Records
Page 16
Sheet1
PL/SQL Tables
PL/SQL Varrays
PL/SQL Nested Tables
PL/SQL Triggers
PL/SQL Cursors
Page 17
Sheet1
Page 18
Sheet1
Page 19
Sheet1
Functions Category
Unique Constraints
Page 20
Sheet1
Grant/Revoke Privileges
Roles
Change Password
Tablespaces
Users
Page 21
Sheet1
Schemas
Literals (Constants)
Page 22
Sheet1
Exception Handling
Page 23
Sheet1
Sequences (Autonumber)
Page 24
Sheet1
Transactions
Page 25
Sheet1
DELETE Statement
INTERSECT Operator
MINUS Operator
Page 26
Sheet1
JOIN TABLES
FROM Clause
ORDER BY Clause
HAVING Clause
SUM Function
MIN Function
MAX Function
OR Condition
AND and OR
LIKE Condition
REGEXP_LIKE Condition
IN Condition
NOT Condition
EXISTS Condition
CREATE TABLE
DROP TABLE
Page 27
Sheet1
VIEW
Data Types
DELETE
DISTINCT
Page 28
Sheet1
IS NOT NULL
UNION
UNION ALL
Page 29
Sheet1
Page 30
Sheet1
Page 31
Sheet1
Alter Tablespace
Page 32
Sheet1
Page 33
Sheet1
Close Cursor
Comments in SQL
Page 34
Sheet1
Commit
Create Tablespace
Create User
Page 35
Sheet1
Cursor Attributes
Cursor CURRENT OF
Page 36
Sheet1
Declare Cursor
Declare Variables
Defined Exception
Page 37
Sheet1
Enable Trigger
Error Messages
EXIT
Fetch Cursor
Find Users
Find Users Logged In
FOR Loop
Foreign Key
Page 38
Sheet1
GOTO
IF-THEN-ELSE
Lock Table
Open Cursor
Page 39
Sheet1
REPEAT UNTIL
Rollback
Sequences
Set Transaction
SQLCODE
Page 40
Sheet1
SQLERRM
System Exception
System Tables
WHEN OTHERS
Page 41
Sheet1
WHILE Loop
ABS
ACOS
ADD_MONTHS
ASCII
ASCIISTR
ASIN
Page 42
Sheet1
ATAN
ATAN2
BFILENAME
BIN_TO_NUM
BITAND
Page 43
Sheet1
CARDINALITY
CAST
CEIL
CHARTOROWID
CHR
COALESCE
COMPOSE
CONCAT
Concat with ||
CORR
Page 44
Sheet1
COS
COSH
COVAR_POP
COVAR_SAMP
Page 45
Sheet1
CUME_DIST
CURRENT_DATE
CURRENT_TIMESTAMP
DBTIMEZONE
DECODE
DECOMPOSE
Page 46
Sheet1
DENSE_RANK
DUMP
EMPTY_BLOB
EMPTY_CLOB
EXP
EXTRACT
Page 47
Sheet1
FLOOR
FROM_TZ
GREATEST
GROUP_ID
HEXTORAW
INITCAP
Page 48
Sheet1
INSTR
INSTR2
INSTR4
Page 49
Sheet1
INSTRB
INSTRC
LAG
LAST_DAY
Page 50
Sheet1
LEAD
LEAST
LENGTH
Page 51
Sheet1
LENGTH2
LENGTH4
LENGTHB
Page 52
Sheet1
LENGTHC
LISTAGG
LN
LNNVL
LOCALTIMESTAMP
Page 53
Sheet1
LOG
LOWER
LPAD
LTRIM
Page 54
Sheet1
MEDIAN
MOD
MONTHS_BETWEEN
NANVL
NCHR
NEW_TIME
NEXT_DAY
Page 55
Sheet1
NULLIF
NUMTODSINTERVAL
NUMTOYMINTERVAL
NVL
NVL2
Page 56
Sheet1
POWER
RANK
RAWTOHEX
Page 57
Sheet1
REMAINDER
ROUND (dates)
Page 58
Sheet1
ROUND (numbers)
RPAD
Page 59
Sheet1
RTRIM
SESSIONTIMEZONE
SIGN
Page 60
Sheet1
SIN
SINH
SOUNDEX
SQRT
STDDEV
Page 61
Sheet1
SUBSTR
SYSDATE
SYSTIMESTAMP
SYS_CONTEXT
TAN
TANH
Page 62
Sheet1
TO_CHAR
TO_CLOB
TO_DATE
TO_DSINTERVAL
TO_LOB
TO_MULTI_BYTE
TO_NCLOB
TO_NUMBER
Page 63
Sheet1
TO_SINGLE_BYTE
TO_TIMESTAMP
TO_TIMESTAMP_TZ
TO_YMINTERVAL
TRANSLATE
TRIM
Page 64
Sheet1
TRUNC (dates)
TRUNC (numbers)
Page 65
Sheet1
TZ_OFFSET
UID
UPPER
USER
USERENV
VARIANCE
VAR_POP
VAR_SAMP
Page 66
Sheet1
VSIZE
Advantages of PL/SQL
Parameters-Procedure, Function
PLSQL-Tutorial Home
Page 67
Sheet1
PL/SQL Home
PL/SQL Environment
PL/SQL Variables
PL/SQL Constants
PL/SQL Operators
PL/SQL Conditions
PL/SQL Strings
PL/SQL Arrays
Page 68
Sheet1
PL/SQL Packages
SQL Commands
SQL Subquery
Page 69
Sheet1
SQL Indexes
Oracle Functions
SQL Tuning or SQL Optimization
Sql Tuning Tips, Optimize SQL
SELECT LIMIT Statement
SELECT TOP Statement
UPDATE Statement
WHERE Clause
IS NULL Condition
BETWEEN Condition
SQL ALIASES
SQL AND
SQL SELECT LIMIT
SQL CREATE TABLE AS
SQL AVG
Page 70
Sheet1
Description
SQL select is Data Retrieval Language(DRL) Command and used to get data from
database table(s).We can use projection operator (*) with select to get all
columns data from table(s).
SQL Insert is Data Manipulation Language (DML) Command and used to inset row(s) to
database tables.
SQL joins are used to get the data from multiple tables which are in relation.
SQL joins are of following types:
Equi join
Non Equi join
Natural join
Inner join
Outer join
Self join & etc
Page 71
Sheet1
Explicit Join uses 'JOIN' Keyword
whereas
Implicit joins doesnot use 'JOIN' Keyword
Can handle using NVL, NVL2, COLEASE and never use not in, =!
all result tends to null
Page 72
Sheet1
Normalization is the process of efficiently organizing data in a database. There
are two goals of the normalization process:
eliminating redundant data (for example, storing the same data in more than one
table ) and
ensuring data dependencies make sense (only storing related data in a table).
Both of these are worthy goals as they reduce the amount of space a database
consumes and ensure that data is logically stored.
The Normal Forms
The database community has developed a series of guidelines for ensuring that
databases are normalized.
These are referred to as normal forms and are numbered from one (the lowest form
of normalization,
referred to as first normal form or 1NF) through five (fifth normal form or 5NF).
In practical applications, you'll often see 1NF , 2NF , and 3NF along with the
occasional 4NF.
Fifth normal form is very rarely seen and won't be discussed in this article.
First Normal Form (1NF):
First normal form (1NF) sets the very basic rules for an organized database:
Eliminate duplicative columns from the same table.
Create separate tables for each group of related data and identify each row
with a unique column or set of columns (the primary key).
Second Normal Form (2NF):
Second normal form (2NF) further addresses the concept of removing duplicative
data :
Meet all the requirements of the first normal form.
Remove subsets of data that apply to multiple rows of a table and place them
in separate tables.
Create relationships between these new tables and their predecessors through
the use of foreign keys.
Third Normal Form (3NF):
Third normal form (3NF) goes one large step further:
Page 73
Sheet1
A Subquery or Inner query or Nested query is a query within another SQL query and
embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a
condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.
There are a few rules that subqueries must follow:
1.
Subqueries must be enclosed within parentheses.
2.
A subquery can have only one column in the SELECT clause, unless multiple
columns are in the main query for the subquery to compare its selected columns.
3.
An ORDER BY cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY can be used to perform the same function as the ORDER B3.Y
in a subquery.
4.
Subqueries that return more than one row can only be used with multiple
value operators, such as the IN operator.
5.
The SELECT list cannot include any references to values that evaluate to a
BLOB, ARRAY, CLOB, or NCLOB.
6.
A subquery cannot be immediately enclosed in a set function.
7.
The BETWEEN operator cannot be used with a subquery; however, the BETWEEN
operator can be used within the subquery.
When you update a view oracle will update the underlying base table.
You can use DML operations on a view if the view does not include Group by, Start
with, Connect
by, Distinct clauses or any subqueries and set operations(Union, union all,
intersect
An inline view is basically a subquery, except it is always in the FROM clause of
a SQL statement. The reason it is called a view is because it essentially
functions as a view as far as the entire query is concerned.
Interview question
Interview question
Delete is DML command Require commit to be executed, and truncate is DDL which is
autcommit in nature.
We can delete data conditionally by using delete command, where conditional data
deletion is not possible with TRUNCATE.TRUNCATE command deletes all available data
Page 74
Sheet1
Truncate deletes the data but drop delete data as well as table structure.
Page 75
Sheet1
1) First difference between View and materialized view is that, In Views query
result is not stored in the disk or database but Materialized view allow to store
query result in disk or table.
2) Another difference between View vs materialized view is that, when we create
view using any table, rowid of view is same as original table but in case of
Materialized view rowid is different.
3) One more difference between View and materialized view in database is that, In
case of View we always get latest data but in case of Materialized view we need to
refresh the view for getting latest data.
4) Performance of View is less than Materialized view.
5) This is continuation of first difference between View and Materialized View, In
case of view its only the logical view of table no separate copy of table but in
case of Materialized view we get physically separate copy of table
6)
difference
between
vs Materialized
View is that, In case of
to Last
get the
number of
recordView
selected
by sql Query
The difference is that, Clustered index is unique for any given table and we can
have only one clustered index on a table. The leaf level of a clustered index is
the actual data and the data is resorted in case of clustered index.
Whereas in case of non-clustered index the leaf level is actually a pointer to the
data in rows so we can have as many non-clustered indexes as we can on the db.
Page 76
Sheet1
We
1.
2.
3.
4.
Unique can be null and should be unique, Primary key should be not null and
unique.
The GETDATE() function returns the current date and time from the SQL Server.
The DATEDIFF() function returns the time between two dates
The DATEADD() function adds or subtracts a specified time interval from a date.
The DATEPART() function is used to return a single part of a date/time, such as
year, month, day, hour, minute, etc.
Page 77
Sheet1
The INSERT INTO SELECT statement selects data from one table and inserts it into
an existing table. Any existing rows in the target table are unaffected.
We can insert multiple rows of explicit data in one SQL command in Oracle.
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means
that you cannot insert a new record, or update a record without adding a value to
this field.
It can be either table level or column level
Syntax (Column Level) :COLUMN [data type] [CONSTRAINT <constraint name> PRIMARY
KEY]
Syntax (Table Level): CONSTRAINT [constraint name] PRIMARY KEY [column (s)]
It can be composite also.
Page 78
Sheet1
The DEFAULT constraint is used to insert a default value into a column.
The default value will be added to all new records, if no other value is
specified.
The CHECK constraint is used to limit the value range that can be placed in a
column.
If you define a CHECK constraint on a single column it allows only certain values
for this column.
If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.
ROLLUP generates a result set that shows aggregates for a hierarchy of values in
the selected columns.
Page 79
Sheet1
CHECKSUM_AGG function is used to get checksum of values in a group.
It ignores null values in computation.
CHECKSUM_AGG can be used along with BINARY_CHECKSUM to detect changes in a table.
The order of the rows in the table does not affect the result of CHECKSUM_AGG.
In addition, CHECKSUM_AGG functions may be used with the DISTINCT keyword and the
GROUP BY clause.
A query is covered if all the columns it uses come from one or more indexes.
These columns include the columns you want the query to return as well as columns
in any JOIN, WHERE, HAVING, and ORDER BY clause.
A covered query typically is considered advantageous because data access through
indexes can be more efficient.
Creates an identity column in a table. This property is used with the CREATE TABLE
and ALTER TABLE Transact-SQL statements.
Returns column information for the specified objects that can be queried in the
current environment.
A local temporary table, #table_name, exists only for the duration of a user
session or the procedure that created the temporary table.
When the user logs off or when the procedure that created the table completes, the
local temporary table is lost. Multiple users can't share a local temporary table
because it is local to one user session.
You also can't grant or revoke permissions on the local temporary table.
A global temporary table, ##table_name, also exists for the duration of a user
session or the procedure that created the table.
When the last user session that references the table disconnects, the global
temporary
tableof
isprogram
lost. units you can create with PL/SQL and store in the
The main types
database are standalone procedures and functions, and packages.
Once stored in the database, these PL/SQL components, collectively known as stored
procedures, can be used as building blocks for several different applications.
Page 80
Sheet1
Provides information about current users, sessions, and processes in an instance
of the Microsoft SQL Server Database Engine.
The information can be filtered to return only those processes that are not idle,
that belong to a specific user, or that belong to a specific session.
Executes a Transact-SQL statement or batch that can be reused many times, or one
that has been built dynamically.
The Transact-SQL statement or batch can contain embedded parameters.
Page 81
Sheet1
CASE expressions let you use IF ... THEN ... ELSE logic in SQL statements without having to i
The PIVOT operator takes data in separate rows, aggregates it and converts it into
columns
Generates totals that appear as additional summary columns at the end of the
result set.
When used with BY, the COMPUTE clause generates control-breaks and subtotals in
the result set. You can specify COMPUTE BY and COMPUTE in the same query.
Page 82
Sheet1
Temporary Table:
1. Below is the sample example of Creating a Temporary Table, Inserting records
into it, retrieving the rows from it and then finally dropping the created
Temporary Table.
-- Create Temporary Table
CREATE TABLE #Customer
(Id INT, Name VARCHAR(50))
--Insert Two records
INSERT INTO #Customer
VALUES(1,'Basavaraj')
INSERT INTO #Customer
VALUES(2,'Kalpana')
--Reterive the records
SELECT * FROM #Customer
--DROP Temporary Table
DROP TABLE #Customer
GO
2. Temporary Table structure can be changed after its creation it implies we can
use DDL statements ALTER, CREATE, DROP.
3. Temporary Tables honor the explicit transactions defined by the user.
4. Temporary Tables are not allowed in User Defined Functions.
5. Temporary table supports adding Indexes explicitly after Temporary Table
creation and it can also have the implicit Indexes which are the result of Primary
and Unique Key constraint.
Table Variable:
1. Below is the sample example of Declaring a Table Variable, Inserting records
into it and retrieving the rows from it.
-- Create Table Variable
DECLARE @Customer TABLE
(
Id INT,
Name VARCHAR(50)
SELECT * FROM ALL_CONS_COLUMNS A JOIN ALL_CONSTRAINTS C ON A.CONSTRAINT_NAME =
C.CONSTRAINT_NAME WHERE C.TABLE_NAME = <your table> AND C.CONSTRAINT_TYPE = 'P'
The SQL Server in-memory columnstore index stores and manages data by using columnbased data storage and column-based query processing.
Columnstore indexes work well for data warehousing workloads that primarily
perform bulk loads and read-only queries.
Use the columnstore index to achieve up to 10x query performance gains over
Candidate Key A Candidate Key can be any column or a combination of columns that
can qualify as unique key in database. There can be multiple Candidate Keys in one
table. Each Candidate Key can qualify as Primary Key.
Primary Key A Primary Key is a column or a combination of columns that uniquely
Page 83
Sheet1
Difference between cross join and Full outer join
Cross Join :
No join conditions are specified.
Results in pairs of rows.
Results in Cartesian product of two tables.
Full Outer Join:
A combination of both left and right outer joins.
Results in every row from both of the tables , at least once.
Assigns NULL for unmatched fields.
Page 84
Sheet1
A function is a named PL/SQL Block which is similar to a procedure. The major
difference between a procedure and a function is,a function must always return a
value, but a procedure may or may not return a value.
Page 85
Sheet1
A PL/SQL record is a data structure that can hold data items of different kinds.
Records consist of different fields, similar to a row of a database table.
PL/SQL can handle the following types of records:
1.Table-based
2.Cursor-based records
3.User-defined records
A record based on a table's column structure, Each field corresponds to -- and has
the same name as -- a column in a table.
PL/SQL provides a user-defined record type that allows you to define different
record structures. Records consist of different fields. Suppose you want to keep
track of your books in a library.
Page 86
Sheet1
Syntax :
CUSOR Cursor_Name IS SELECT Statement;
Variable Cursor_Name%rowtype;
an
or, in
are
user is
Oracle creates a memory area, known as context area, for processing an SQL
statement, which contains all information needed for processing the statement, for
example, number of rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor.
Page 87
Sheet1
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor
is associated with this statement. For INSERT operations, the cursor holds the
data that needs to be inserted. For UPDATE and DELETE operations, the cursor
identifies the rows that would be affected.
In PL/SQL,
you can
refer
to the defined
most recent
implicit
cursor more
as the
SQL cursor,
Explicit
cursors
are
programmer
cursors
for gaining
control
over the
context area. An explicit cursor should be defined in the declaration section of
the PL/SQL Block. It is created on a SELECT Statement which returns more than one
row.
Working with an explicit cursor involves four steps:
Declaring the cursor for initializing in the memory
Opening the cursor for allocating memory
Fetching the cursor for retrieving data
Closing the cursor to release allocated memory
A ref cursor in Oracle PL/SQL is much like an ordinary PL/SQL cursor in that it
acts as a pointer to the result set of the cursor with which it is associated.
However, the difference is that a ref cursor can be assigned to different result
sets whereas a cursor is always associated with the same result set. Cursors and
ref cursors are not interchangeable.
The real purpose of ref cursors is to be able to share cursors and result sets
between the client and the Oracle server or between different subroutines. For
example you might open a cursor in an Oracle Forms client and then continue
working with the cursor on the server or you might open a cursor in a Java program
and then continue working with it in an Oracle PL/SQL stored procedure.
Ref cursors also come in two variants: strongly typed and weakly typed depending
on how likely you are (or want to) reuse a cursor variable. Weak ref cursor types
can be associated with any query whereas strong ref cursor types can only be
Page 88
Sheet1
You would use a CURSOR FOR LOOP when you want to fetch and process every record in
a cursor. The CURSOR FOR LOOP will terminate when all of the records in the cursor
have been fetched.
Syntax : FOR record_index in cursor_name
PL/SQL Parameterized cursor pass the parameters into a cursor and use them in to
query.
PL/SQL Parameterized cursor define only datatype of parameter and not need to
define it's length.
Default values is assigned to the Cursor parameters. and scope of the parameters
are locally.
Parameterized cursors are also saying static cursors that can passed parameter
value when cursor are opened.
Page 89
Sheet1
PL/SQL Where current of
... WHERE CURRENT OF cursor
WHERE CURRENT is used as a reference to the current row when using a cursor to
UPDATE or DELETE the current row.
The cursor must be based on SQL that selects 'FOR UPDATE'
Page 90
Sheet1
SQL GRANT Command
SQL GRANT is a command used to provide access or privileges on the database
objects to the users.
SQL REVOKE Command:
The REVOKE command removes user access rights or privileges to the database
objects.
A synonym is an alternative name (or alias) for an object (like an table or view)
in the database. Objects can have many synonyms. Use the CREATE SYNONYM SQL
command to create synonyms and the DROP SYNONYM command to remove them. To get a
list of synonyms, query the USER_SYNONYMS view.
Roles are a collection of privileges or access rights. When there are many users
in a database it becomes difficult to grant or revoke privileges to users.
Therefore, if you define roles, you can grant or revoke privileges to users,
thereby automatically granting or revoking privileges. You can either create Roles
or use the system roles pre-defined by oracle.
Used to change/Reset the user password
A database is divided into one or more logical storage units called tablespaces.
Tablespaces are divided into logical units of storage called segments, which are
further divided into extents.
Extents
areinformation
a collection
of contiguous
blocks.
We can get
about
users by using
below tables
1. user_users.
2. dba_users.
3. all_users.
Page 91
Sheet1
A schema is a collection of logical structures of data, or schema objects.
A schema is owned by a database user and has the same name as that user.
Each user owns a single schema. Schema objects can be created and manipulated with
SQL and include the following types of objects:
Clusters
Database links
Database triggers
Dimensions
External procedure libraries
Indexes and index types
Java classes, Java resources, and Java sources
Materialized views and materialized view logs
Object tables, object types, and object views
Operators
Sequences
Stored functions, procedures, and packages
Synonyms
Tables and index-organized tables
Views
A literal is an explicit numeric, character, string, or BOOLEAN value not
represented by an identifier.
Below are literal types:
1.Text Literals
2.Numeric Literals
3.Datetime Literals
4.Interval Literals
The numeric literal 147 and the BOOLEAN literal FALSE are examples
Page 92
Sheet1
PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block
known as exception Handling. Using Exception Handling we can test the code and
avoid it from exiting abruptly.
There are 3 types of Exceptions.
a) Named System Exceptions
b) Unnamed System Exceptions
c) User-defined Exceptions
a) System exceptions are automatically raised by Oracle, when a program violates
a RDBMS rule. There are some system exceptions which are raised frequently, so
they are pre-defined and given a name in Oracle which are known as Named System
Exceptions.
For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions.
B) Those system exception for which oracle does not provide a name is known as
unamed system exception. These exception do not occur frequently. These Exceptions
have a code and an associated message.
There are two ways to handle unnamed sysyem exceptions:
1. By using the WHEN OTHERS exception handler, or
2. By associating the exception code to a name and using it as a named exception.
We can assign a name to unnamed system exceptions using a Pragma called
EXCEPTION_INIT.
EXCEPTION_INIT will associate a predefined Oracle error number to a
programmer_defined exception name.
Steps to be followed to use unnamed system exceptions are
They are raised implicitly.
If they are not handled in WHEN Others they must be handled explicity.
To handle the exception explicity, they must be declared using Pragma
EXCEPTION_INIT as given above and handled referecing the user-defined exception
name in the exception section.
Page 93
Sheet1
Simple Loop, WHILE loop,
(LADDER)
For loop, If then End If; IF THEN ELSE END IF; IF ELSIF
Use the CREATE SEQUENCE statement to create a sequence, which is a database object
from which multiple users may generate unique integers. You can use sequences to
automatically generate primary key values.
Page 94
Sheet1
A transaction is a unit of work that is performed against a database.
Transactions are units or sequences of work accomplished in a logical order,
whether in a manual fashion by a user or automatically by some sort of a database
program.
A transaction is the propagation of one or more changes to the database.
For example, if you are creating a record or updating a record or deleting a
record from the table, then you are performing transaction on the table.
It is important to control transactions to ensure data integrity and to handle
database errors.
Transactions have the following four standard properties, usually referred to by
the acronym ACID:
Atomicity
Consistency
Isolation
Durability
There are following commands used to control transactions:
COMMIT: to save the changes.
ROLLBACK: to rollback the changes.
SAVEPOINT: creates points within groups of transactions in which to ROLLBACK
Comments can make your application easier for you to read and maintain.
For example, you can include a comment in a statement that describes the purpose
of the statement within your application.
With the exception of hints, comments within SQL statements do not affect the
statement execution. Please refer to "Hints " on using this particular form of
comment.
A comment can appear between any keywords, parameters, or punctuation marks in a
statement. You can include a comment in a statement in two ways:
1. Begin the comment with a slash and an asterisk (/*).
Proceed with the text of the comment. This text can span multiple lines. End the
comment with an asterisk and a slash (*/).
The opening and terminating characters need not be separated from the text by a
space or a line break.
We can get information about errors using SQLCODE AND SQLERRM functions in oracle
Page 95
Sheet1
Below are the oracle system tables:
ALL_ARGUMENTS Arguments in object accessible to the user
ALL_CATALOG All tables, views, synonyms, sequences accessible to the user
ALL_COL_COMMENTS Comments on columns of accessible tables and views
ALL_CONSTRAINTS Constraint definitions on accessible tables
ALL_CONS_COLUMNS Information about accessible columns in constraint definitions
ALL_DB_LINKS Database links accessible to the user
ALL_ERRORS Current errors on stored objects that user is allowed to create
ALL_INDEXES Descriptions of indexes on tables accessible to the user
ALL_IND_COLUMNS COLUMNs comprising INDEXes on accessible TABLES
ALL_LOBS Description of LOBs contained in tables accessible to the user
ALL_OBJECTS Objects accessible to the user
ALL_OBJECT_TABLES Description of all object tables accessible to the user
ALL_SEQUENCES Description of SEQUENCEs accessible to the user
ALL_SNAPSHOTS Snapshots the user can access
ALL_SOURCE Current source on stored objects that user is allowed to create
ALL_SYNONYMS All synonyms accessible to the user
ALL_TABLES Description of relational tables accessible to the user
ALL_TAB_COLUMNS Columns of user's tables, views and clusters
ALL_TAB_COL_STATISTICS Columns of user's tables, views and clusters
ALL_TAB_COMMENTS Comments on tables and views accessible to the user
ALL_TRIGGERS Triggers accessible to the current user
ALL_TRIGGER_COLS Column usage in user's triggers or in triggers on user's tables
ALL_TYPES Description of types accessible to the user
ALL_UPDATABLE_COLUMNS Description of all updatable columns
ALL_USERS Information about all users of the database
ALL_VIEWS Description of views accessible to the user
DATABASE_COMPATIBLE_LEVEL Database compatible parameter set via init.ora
DBA_DB_LINKS All database links in the database
DBA_ERRORS Current errors on all stored objects in the database
DBA_OBJECTS All objects in the database
DBA_ROLES All Roles which exist in the database
DBA_ROLE_PRIVS Roles granted to users and roles
DBA_SOURCE Source of all stored objects in the database
The DELETE statement is used to delete records in a table.
The Oracle INTERSECT operator is used to return the results of 2 or more SELECT
statements. However, it only returns the rows selected by all queries. If a record
exists in one query and not in the other, it will be omitted from the INTERSECT
results.
Each SELECT statement within the Oracle INTERSECT must have the same number of
fields in the result sets with similar data types.
The SQL MINUS operator is used to return all rows in the first SELECT statement
that are not returned in the second SELECT statement.
Each SELECT statement within the MINUS query must have the same number of fields
in the result sets with similar data types.
Page 96
Sheet1
Refer Joins (topic 4)
From clause used to specify the tables or views while selecting the data from
database.
Use to sort the Result set, Default it will sort in ascending order to sort Desc
use Desc keyword
Syntax
Byaggregate
Column_name
;
Used toOrder
filter
function.
Generally used with Group by clause.
The SQL SUM function is used to return the sum of an expression in a SELECT
statement.
The SQL MIN function is used to return the minimum value of an expression in a
SELECT statement.
The SQL MAX function is used to return the maximum value of an expression in a
SELECT statement.
The SQL OR Condition is used to test multiple conditions, where the records are
returned when any one of the conditions are met.
It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
The SQL AND condition and OR condition can be combined to test for multiple
conditions in a SELECT, INSERT, UPDATE, or DELETE statement.
When combining these conditions, it is important to use brackets so that the
database knows what order to evaluate each condition.
The SQL LIKE condition allows you to use wildcards to perform pattern matching.
The LIKE condition is used in the WHERE clause of a SELECT, INSERT, UPDATE, or
DELETE statement.
The Oracle REGEXP_LIKE condition allows you to perform regular expression matching
in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement
The SQL IN condition is used to help reduce the need for multiple OR conditions in
a
SELECT,
INSERT,
UPDATE,
orknown
DELETE
The
SQL NOT
Condition
(also
asstatement
the SQL NOT Operator) is used to negate a
condition in a SELECT, INSERT, UPDATE, or DELETE statement.
The SQL EXISTS condition is used in combination with a subquery and is considered
to be met, if the subquery returns at least one row.
It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
Page 97
Sheet1
These tables do not reside in the system catalogs and are not persistent.
Temporary tables exist only during the connection that declared them and cannot be
referenced outside of that connection.
When the connection closes, the rows of the table are deleted, and the in-memory
description of the temporary table is dropped.
Temporary tables are useful when:
The table structure is not known before using an application.
Other users do not need the same table structure.
Data in the temporary table is needed while using the application.
TheLOCAL
tableTEMPORARY
can be declared
and distinct
dropped without
holding and
the embedded
locks on SQL
the system
Oracle
TABLES are
within modules
programs within Oracle sessions.
An Oracle VIEW, in essence, is a virtual table that does not physically exist.
Rather, it is created by a query joining one or more tables.
Page 98
Sheet1
The SQL IS NOT NULL Condition is used to test for a NOT NULL value in SELECT,
INSERT, UPDATE, or DELETE statement.
The SQL UNION operator is used to combine the result sets of 2 or more SELECT
statements.
It removes duplicate rows between the various SELECT statements.
Each SELECT statement within the UNION must have the same number of fields in the
result sets with similar data types.
The Oracle UNION ALL operator is used to combine the result sets of 2 or more
SELECT statements.
It returns all rows from the query (even if the row exists in more than one of the
SELECT statements).
Each SELECT statement within the Oracle UNION ALL operator must have the same
number of fields in the result sets with similar data types.
A trigger is a pl/sql block structure which is fired when a DML statements like
Insert, Delete, Update is executed on a database table. A trigger is triggered
automatically when an associated DML statement is executed.
Syntax for Creating a Trigger
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;
CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with
the given name or overwrites an existing trigger with the same name.
{BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the
trigger get fired. i.e for example: before or after updating a table. INSTEAD OF
is used to create a trigger on a view. before and after cannot be used to create a
Page 99
Sheet1
An AFTER INSERT Trigger means that Oracle will fire this trigger after the INSERT
operation is executed.
Page 100
Sheet1
An AFTER UPDATE Trigger means that Oracle will fire this trigger after the UPDATE
operation is executed
Page 101
Sheet1
The ALTER TABLESPACE statement is used to modify a tablespace or one of its data
files or temp files.
A tablespace is used to allocate space in the Oracle database where schema objects
are stored.
Page 102
Sheet1
A BEFORE DELETE Trigger means that Oracle will fire this trigger before the DELETE
operation is executed.
Page 103
Sheet1
A BEFORE INSERT Trigger means that Oracle will fire this trigger before the INSERT
operation is executed.
A BEFORE UPDATE Trigger means that Oracle will fire this trigger before the UPDATE
operation is executed.
Close Cursor_name;
Comments are of two types:
1. Single line comment:
It is used to comment the entire line of a code segment.
2. Multi line comment:
It is used to comment multiple lines of code.
Page 104
Sheet1
To store the transaction permently we use commit statement; DDL are
autocommit (e.g CREATE, ALTER, DROP, TRUNCATE)
The CREATE SCHEMA statement does NOT actually create a schema in Oracle.
The CREATE SCHEMA statement is used only to create objects (ie: tables, views) in your schema in a single
SQL statement, instead of having to issue individual CREATE TABLE statements and CREATE VIEW
statements.
If an error occurs creating any of the objects in the CREATE SCHEMA statement, the Oracle database will roll
back all create statements (e: tables and view) in the CREATE SCHEMA statement.
The CREATE TABLESPACE statement is used to allocate space in the Oracle database where schema objects
are stored.
The CREATE TABLESPACE statement can be used to create the 3 kinds of tablespaces:
1. Permanent Tablespace
2. Temporary Tablespace
3. Undo Tablespace
Page 105
Sheet1
There are five cursor attributes: %isopen, %found, %notfound,
%rowcount and %bulk_rowcount.
%isopen
With %isopen it is possible to test whether a cursor was opened:
%found
%found returns true when the last fetch operation on the cursor
fetched a row. If %found is used on a cursor that is not open (%open
returns false), an ORA-01001: invalid cursor is raised. %notfound
returns null is returned:
%notfound
%notfound returns true when the last fetch operation on the cursor
did not fetch a row. If %notfound is used on a cursor that is not
open (%open returns false), an ORA-01001: invalid cursor is raised.
%notfound returns null is returned:
%rowcount
If you plan on updating or deleting records that have been referenced by a SELECT FOR UPDATE statement,
you can use the WHERE CURRENT OF statement.
Page 106
Sheet1
The SELECT FOR UPDATE statement allows you to lock the records in the cursor result set.
You are not required to make changes to the records in order to use this statement.
The record locks are released when the next commit or rollback statement is issued.
A cursor is a SELECT statement that is defined within the declaration section of your PLSQL code.
In Oracle/PLSQL, a variable allows a programmer to store data temporarily during the execution of code.
Sometimes, it is necessary for programmers to name and trap their own exceptions - ones that aren't defined
already by PL/SQL.
These are called Named Programmer-Defined Exceptions
Used to disable triggers specified on particular table.
Used to disable to foreign key in delete operations.
Used to disable trigger.
Used to remove constraint from a table.
The DROP TABLESPACE statement is used to remove a tablespace from the Oracle database.
A tablespace is used to allocate space in the Oracle database where schema objects are stored.
Used to erase trigger from database.
Used to remove database user.
Page 107
Sheet1
Used to enable a trigger
Refer SQLCODE and SQLERRM functions
Used to gracefully terminate the user session. Changes are saved permanently before closing the session.
Used to get the value(s) from the cursor. To fetch the value from cursor, cursor should be in open state.
We cannot delete parent table data if table are related with normal foreign key relationship.
If we create foreign key with cascade in child table, then if we delete the data from parent table, data from child
table related to deleted record in parent table also deleted.
We cannot delete parent table data if table are related with normal foreign key relationship.
If we create foreign key with SET NULL in child table, then if we delete the data from parent table, data from
child table related to deleted record in parent table are set to null.
Page 108
Sheet1
The GOTO statement causes the code to branch to the label after the GOTO statement.
Refer conditoinal statements
Page 109
Sheet1
In MySQL, the REPEAT statement is used when you do not know how many times you want the loop body to
execute.
SQLCODE: It returns the error number for the last encountered error.
Page 110
Sheet1
The SQLERRM function returns the error message associated with the
most recently raised error exception. This function should only be
used within the Exception Handling section of your code.
Named system exceptions are exceptions that have been given names by PL/SQL.
They are named in the STANDARD package in PL/SQL and do not need to be defined by the programmer.
Below are the system exceptions:
DUP_VAL_ON_INDEX
TIMEOUT_ON_RESOURCE
TRANSACTION_BACKED_OUT
INVALID_CURSOR
NOT_LOGGED_ON
LOGIN_DENIED.
NO_DATA_FOUND
TOO_MANY_ROWS.
ZERO_DIVIDE
INVALID_NUMBER
STORAGE_ERROR
PROGRAM_ERROR
VALUE_ERROR
CURSOR_ALREADY_OPEN.
Refer Oracle system tables (topic 114)
The WHEN OTHERS clause is used to trap all remaining exceptions that have not been handled by your Named
System Exceptions and Named Programmer-Defined Exceptions.
Page 111
Sheet1
Refer looping statements
Page 112
Sheet1
The Oracle/PLSQL ATAN function returns the arc tangent of a number.
Page 113
Sheet1
The Oracle/PLSQL CARDINALITY function returns the number of elements
in a nested table.
The Oracle/PLSQL CAST function converts one datatype to another.
COALESCE will return the first non-NULL item in its parameter list
The Oracle/PLSQL COMPOSE function returns a Unicode string.
Page 114
Sheet1
The Oracle/PLSQL COVAR_SAMP function returns the sample covariance of a set of number pairs.
Page 115
Sheet1
The Oracle/PLSQL CUME_DIST function returns the cumulative
distribution of a value in a group of values. The CUME_DIST function
will return a value that is >0 and <=1.
The CUME_DIST function can be used two ways - as an Aggregate
function or as an Analytic function.
CUME_DIST Function Syntax #1 - Used as an Aggregate Function
As an Aggregate function, the CUME_DIST function returns the
relative position of a row within a group of rows.
The Oracle/PLSQL DECOMPOSE function accepts a string and returns a Unicode string.
Page 116
Sheet1
As an Analytic function, the DENSE_RANK function returns the rank of
each row of a query with respective to the other rows.
The syntax for the DENSE_RANK function when used as an Analytic
function is:
Page 117
Sheet1
The Oracle/PLSQL FLOOR function returns the largest integer value
that is equal to or less than a number.
The Oracle/PLSQL INITCAP function sets the first character in each word to uppercase and the rest to
lowercase.
Page 118
Sheet1
The Oracle/PLSQL INSTR4 function returns the location of a substring in a string, using UCS4 code points
Page 119
Sheet1
The Oracle/PLSQL INSTRB function returns the location of a substring in a string, using bytes instead of
characters.
The Oracle/PLSQL INSTRC function returns the location of a substring in a string, using Unicode complete
characters.
The Oracle/PLSQL LAST_DAY function returns the last day of the month
based on a date value.
Page 120
Sheet1
The Oracle/PLSQL LEAD function is an analytic function that
query more than one row in a table at a time without having
the table to itself. It returns values from the next row in
table. To return a value from a previous row, try using the
function.
lets you
to join
the
LAG
Page 121
Sheet1
Page 122
Sheet1
Page 123
Sheet1
Page 124
Sheet1
The Oracle/PLSQL MEDIAN function returns the median of an
expression.
The Oracle/PLSQL NCHR function returns the character based on the number_code in the national character
set.
Page 125
Sheet1
Page 126
Sheet1
The Oracle/PLSQL RAWTOHEX function converts a raw value into a hexadecimal value.
One of our viewers says that this function comes in handy to move a varchar value to a blob field.
Page 127
Sheet1
Page 128
Sheet1
Page 129
Sheet1
The Oracle/PLSQL SESSIONTIMEZONE function returns the current session's time zone as a time zone offset
(in the following format: '[+|-]TZH:TZM') or a time zone region name.
Page 130
Sheet1
The
SINH function
returnsfunction
the hyperbolicreturns
sine of n.
TheOracle/PLSQL
Oracle/PLSQL
SOUNDEX
a phonetic representation
The Oracle/PLSQL STDDEV function returns the standard deviation of a set of numbers.
The STDDEV function can be used two ways - as an Aggregate function or as an Analytic function.
Page 131
Sheet1
The Oracle/PLSQL SUBSTR functions allows you to extract a substring from a string.
The Oracle/PLSQL SYSTIMESTAMP function returns the current system date and time (including fractional
seconds and time zone) on your local database.
The Oracle/PLSQL SYS_CONTEXT function can be used to retrieve information about the Oracle environment.
Page 132
Sheet1
The Oracle/PLSQL TO_DSINTERVAL function converts a string to an INTERVAL DAY TO SECOND type.
Page 133
Sheet1
The Oracle/PLSQL TO_SINGLE_BYTE function returns a character value with all of the multibyte characters
converted to single-byte characters.
To use this function, your database character set contains both single-byte and multibyte characters.
The Oracle/PLSQL TO_TIMESTAMP function converts a string to a timestamp.
The Oracle/PLSQL TO_TIMESTAMP_TZ function converts a string to a timestamp with time zone.
The Oracle/PLSQL TO_YMINTERVAL function converts a string to an INTERVAL YEAR TO MONTH type.
Page 134
Sheet1
Page 135
Sheet1
The Oracle/PLSQL TZ_OFFSET function returns the time zone offset of a value.
The Oracle/PLSQL UID function returns the id number for a user's session (the user who is currently logged in).
Page 136
Sheet1
The Oracle/PLSQL VSIZE function returns the number of bytes in the internal representation of an expression.
Sheet1
PL/SQL variables must be declared in the declaration section or in a
package as a global variable.
When you declare a variable, PL/SQL allocates memory for the
variable's value and the storage location is identified by the
A constant holds a value that once declared, does not change in the program.
A constant declaration specifies its name, data type, and value, and allocates storage for it.
The declaration can also impose the NOT NULL constraint.
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulation.
PL/SQL language is rich in built-in operators and provides the following types of operators:
Arithmetic operators
Relational operators
Comparison operators
Logical operators
String operators
Below are conditional statements available in PL/SQL
IF - THEN statement
IF-THEN-ELSE statement
IF-THEN-ELSIF statement
Case statement
Searched CASE statement
nested IF-THEN-ELSE
The string in PL/SQL is actually a sequence of characters with an optional size specification.
The characters could be numeric, letters, blank, special characters or a combination of all. PL/SQL offers three
kinds of strings:
1.Fixed-length strings:
In such strings, programmers specify the length while declaring the string.
The string is right-padded with spaces to the length so specified.
2.Variable-length strings:
In such strings, a maximum length up to 32,767, for the string is specified and no padding takes place.
3.Character large objects (CLOBs):
An array is a part of collection type data and it stands for variable-size arrays
Page 138
Sheet1
PL/SQL packages are schema objects that groups logically related PL/SQL types, variables and subprograms.
A package will have two mandatory parts:
1. Package specification:
The specification is the interface to the package. It just DECLARES the types, variables, constants, exceptions,
cursors, and subprograms that can be referenced from outside the package.
In other words, it contains all information about the content of the package, but excludes the code for the
subprograms.
2. Package body or definition:
The package body has the codes for various methods declared in the package specification and other private
declarations, which are hidden from code outside the package.
DBMS_OUTPUT.PUT_LINE
Below are the sql commands:
DML: INSERT, UPDATE, DELETE, MERGE
DDL: CREATE, ALTER, DROP, TRUNCATE
TCL: COMMIT, ROLLBACK, SAVEPOINT
DCL: GRANT, REVOKE
DRL: SELECT
Page 139
Sheet1
An index is a performance-tuning method of allowing faster retrieval
of records. An index creates an entry for each value that appears in
the indexed columns. By default, Oracle creates B-tree indexes.
Page 140
Sheet1
Syntax
SELECT column_list FROM table-name
[WHERE Clause]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause];
INSERT INTO TABLE_NAME
[ (col1, col2, col3,...colN)]
VALUES (value1, value2, value3,...valueN);
INSERT INTO TABLE_NAME
VALUES (value1, value2, value3,...valueN);
INSERT INTO table_name
[(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM table_name [WHERE condition];
Syntax :SELECT col1, col2, col3...
FROM table_name1, table_name2
WHERE table_name1.col2 = table_name2.col1;
Page 141
Sheet1
Explicit Join Syntax :
SELECT TableA.ColumnA1,
TableB.ColumnB2
FROM TableA
INNER JOIN TableB
ON TableA.ColumnA1 = TableB.ColumnB1
Implicit Join Syntax:
SELECT TableA.ColumnA1,
TableB.ColumnB2
FROM TableA,
TableB
WHERE TableA.ColumnA1 = TableB.ColumnB1
Syntax :SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
Page 142
Sheet1
Page 143
Sheet1
Subquery with Select :
SELECT column_name [, column_name ]
FROM
table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Subquery with Insert :
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
Subquery with Update :
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Subquery with Delete :
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Subquery for column :
SELECT column_namw, (select statement) alias FROM table_Name;
Subquery in FROM clause (Inline View):
Syntax : SELECT column_name1, column_name2, alias2.column_name1 FROM Table_name1,
(SELECT Column_name1, column_name2 FROM table_name3) alias2
NA
select max(age)
from (
-- this part of the query is an inline view:
select age from table
)
NA
NA
DELETE FROM table_name [where conditions];
TRUNCATE TABLE table_name;
Page 144
Sheet1
TRUNCATE TABLE table_name;
DROP TABLE table_name;
NA
CONVERT(data_type(length),expression,style)
CAST ( { expr | ( subquery ) | MULTISET ( subquery ) } AS type_name
)
NA
NA
NA
NA
Page 145
Sheet1
NA
NA
Page 146
Sheet1
1. Using subquery
DELETE FROM table_name A
WHERE a.rowid >ANY (SELECT B.rowid FROM
B.col2 );
DATEPART(datepart,date)
CONVERT(data_type(length),expression,style)
Page 147
Sheet1
INSERT INTO table2
SELECT * FROM table1;
INSERT
INTO
INTO
INTO
SELECT
ALL
mytable (column1, column2, column3) VALUES ('val1.1', 'val1.2', 'val1.3')
mytable (column1, column2, column3) VALUES ('val2.1', 'val2.2', 'val2.3')
mytable (column1, column2, column3) VALUES ('val3.1', 'val3.2', 'val3.3')
* FROM dual;
NA
NA
Page 148
Sheet1
Syntax:CONSRAINT [constraint name] DEFAULT Value
Page 149
Sheet1
CHECKSUM ( * | expression [ ,...n ] )
NA
Page 150
Sheet1
sp_who [ [ @loginame = ] 'login' | session ID | 'ACTIVE' ]
CONNECT user@database
DISCONNECT
NA
Page 151
Sheet1
Syntax : CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
SELECT *
FROM
(SELECT product_code, quantity
FROM
pivot_test)
PIVOT (SUM(quantity) AS sum_quantity FOR (product_code) IN ('A' AS a, 'B' AS b,
'C' AS c));
MERGE INTO employees e
USING hr_records h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address)
VALUES (h.emp_id, h.address);
[ COMPUTE
{ { AVG | COUNT | MAX | MIN | STDEV | STDEVP | VAR | VARP | SUM }
( expression ) } [ ,...n ]
[ BY expression [ ,...n ] ]
]
Arguments
AVG | COUNT | MAX | MIN | STDEV | STDEVP | VAR | VARP | SUM
Specifies the aggregation to be performed. These row aggregate functions are
used with the COMPUTE clause.
HAS_PERMS_BY_NAME ( securable , securable_class , permission
[ , sub-securable ] [ , sub-securable_class ] )
Page 152
Sheet1
NA
NA
NA
Page 153
Sheet1
NA
NA
NA
Syntax :
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
Page 154
Sheet1
Syntax:CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
Index By table :
Syntax : TYPE type_name IS TABLE OF element_type [NOT NULL] INDEX BY
subscript_type;
table_name type_name;
Nested Table:
Syntax : TYPE type_name IS TABLE OF element_type [NOT NULL];
table_name type_name;
Varray:
TYPE Type_Name IS VARRAY(SIZE) OF DATATYPE(10)
Page 155
Sheet1
Syntax : TYPE record_type_name IS RECORD
(first_col_name column_datatype,
second_col_name column_datatype, ...);
TYPE
type_name IS RECORD
( field_name1 datatype1 [NOT NULL] [:= DEFAULT EXPRESSION],
field_name2
datatype2
[NOT NULL] [:= DEFAULT EXPRESSION],
...
field_nameN datatypeN [NOT NULL] [:= DEFAULT EXPRESSION);
record-name type_name;
Page 156
Sheet1
DECLARE
CURSOR customer_cur is
SELECT id, name, address
FROM customers;
customer_rec customer_cur%rowtype;
BEGIN
OPEN customer_cur;
LOOP
FETCH customer_cur into customer_rec;
EXIT WHEN customer_cur%notfound;
DBMS_OUTPUT.put_line(customer_rec.id || ' ' || customer_rec.name);
END LOOP;
END;
Syntax :
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Page 157
Sheet1
NA
E.g : DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
TYPE ref_type_name IS REF CURSOR
[RETURN {cursor_name%ROWTYPE
|ref_cursor_name%ROWTYPE
|record_name%TYPE
|record_type_name
|table_name%ROWTYPE} ];
The RETURN clause is optional, when included it causes the cursor variable to be
strongly typed.
Page 158
Sheet1
LOOP
{...statements...}
END LOOP;
DECLARE
cursor c(no number) is select * from emp_information
where emp_no = no;
tmp emp_information%rowtype;
BEGIN
OPEN c(4);
FOR tmp IN c(4) LOOP
dbms_output.put_line('EMP_No:
'||tmp.emp_no);
dbms_output.put_line('EMP_Name: '||tmp.emp_name);
dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);
dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);
END Loop;
CLOSE c;
END;
/
Page 159
Sheet1
e.g.
DECLARE
CURSOR trip_cursor IS
SELECT
bt_id_pk,
bt_duration
FROM
business_trips
WHERE
bt_id_pk = 23
FOR UPDATE OF bt_id_pk, bt_duration;
BEGIN
FOR trip_record IN trip_cursor LOOP
UPDATE business_trips
SET bt_duration = 5
WHERE CURRENT OF trip_cursor;
END LOOP;
COMMIT;
END;
NA
Page 160
Sheet1
The Syntax for the GRANT command is:
GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];
The Syntax for the REVOKE command is:
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name} ;
CREATE SYNONYM emp FOR scott.employees;
CREATE PUBLIC SYNONYM dual FOR sys.dual;
CREATE PUBLIC SYNONYM emp FOR scott.employees;
DROP SYNONYM emp;
The Syntax to create a role is:
CREATE ROLE role_name
[IDENTIFIED BY password];
DROP ROLE role_name;
alter user user_name identified by new_password replace old_password
NA
Page 161
Sheet1
NA
NA
Page 162
Sheet1
NA
Page 163
Sheet1
Simple loop without condition:
LOOP
{...statements...}
END LOOP;
Simple loop with condition:
LOOP
{...statements...}
EXIT [ WHEN boolean_condition ];
END LOOP;
While loop:
WHILE condition
LOOP
{...statements...}
END LOOP;
For loop:
FOR loop_counter IN [REVERSE] lowest_number..highest_number
LOOP
{...statements...}
END LOOP;
IF statement:
IF condition THEN
{...statements to execute when condition is TRUE...}
END IF;
IF else statement:
IF condition THEN
{...statements to execute when condition is TRUE...}
Syntax : CREATE SEQUENCE <sequence_name>
MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;
Page 164
Sheet1
NA
NA
Page 165
Sheet1
NA
Page 166
Sheet1
NA
NA
NA
NA
SELECT SUM(expression)
FROM tables
WHERE conditions;
SELECT MIN(expression)
FROM tables
WHERE conditions;
SELECT MAX(expression)
FROM tables
WHERE conditions;
WHERE condition1
OR condition2
...
OR condition_n;
WHERE condition1
AND condition2
...
OR condition_n;
expression LIKE pattern [ ESCAPE 'escape_character' ]
NOT condition
Page 167
Sheet1
DECLARE GLOBAL TEMPORARY TABLE table-Name
{ column-definition [ , column-definition ] * }
[ ON COMMIT {DELETE | PRESERVE} ROWS ]
NOT LOGGED [ON ROLLBACK DELETE ROWS]
Page 168
Sheet1
expression IS NOT NULL
Page 169
Sheet1
CREATE [ OR REPLACE ] TRIGGER trigger_name
AFTER INSERT
ON table_name
[ FOR EACH ROW ]
DECLARE
-- variable declarations
BEGIN
-- trigger code
EXCEPTION
WHEN ...
-- exception handling
END;
Page 170
Sheet1
CREATE [ OR REPLACE ] TRIGGER trigger_name
AFTER UPDATE
ON table_name
[ FOR EACH ROW ]
DECLARE
-- variable declarations
BEGIN
-- trigger code
EXCEPTION
WHEN ...
-- exception handling
END;
Page 171
Sheet1
ALTER TABLESPACE tablespace_name
{ DEFAULT
[ { COMPRESS | NOCOMPRESS } ] storage_clause
| MINIMUM EXTENT integer [ K | M | G | T | P | E ]
| RESIZE integer [ K | M | G | T | P | E ]
| COALESCE
| RENAME TO new_tablespace_name
| { BEGIN | END } BACKUP
| { ADD { DATAFILE | TEMPFILE }
[ file_specification
[, file_specification ]
]
| DROP {DATAFILE | TEMPFILE } { 'filename' | file_number }
| RENAME DATAFILE 'filename' [, 'filename' ] TO 'filename' [, 'filename' ]
| { DATAFILE | TEMPFILE } { ONLINE | OFFLINE }
}
| { logging_clause | [ NO ] FORCE LOGGING }
| TABLESPACE GROUP { tablespace_group_name | '' }
| { ONLINE
| OFFLINE [ NORMAL | TEMPORARY | IMMEDIATE ]
}
| READ { ONLY | WRITE }
| { PERMANENT | TEMPORARY }
| AUTOEXTEND
{ OFF
| ON [ NEXT integer [ K | M | G | T | P | E ] ]
[ MAXSIZE { UNLIMITED | integer [ K | M | G | T | P | E ] } ]
}
| FLASHBACK { ON | OFF }
| RETENTION { GUARANTEE | NOGUARANTEE }
} ;
Page 172
Sheet1
CREATE [ OR REPLACE ] TRIGGER trigger_name
BEFORE DELETE
ON table_name
[ FOR EACH ROW ]
DECLARE
-- variable declarations
BEGIN
-- trigger code
EXCEPTION
WHEN ...
-- exception handling
END;
Page 173
Sheet1
CREATE [ OR REPLACE ] TRIGGER trigger_name
BEFORE INSERT
ON table_name
[ FOR EACH ROW ]
DECLARE
-- variable declarations
BEGIN
-- trigger code
EXCEPTION
WHEN ...
-- exception handling
END;
NA
Single line comment:
--code goes here
Multi line comment:
/* code goes here */
Page 174
Sheet1
commit;
CREATE SCHEMA AUTHORIZATION schema_name
[create_table_statement]
[create_view_statement]
[grant_statement];
CREATE
[ SMALLFILE | BIGFILE ]
TABLESPACE tablespace_name
{ DATAFILE { [ 'filename' | 'ASM_filename' ]
[ SIZE integer [ K | M | G | T | P | E ] ]
[ REUSE ]
[ AUTOEXTEND
{ OFF
| ON [ NEXT integer [ K | M | G | T | P | E ] ]
[ MAXSIZE { UNLIMITED | integer [ K | M | G | T | P | E ] } ]
}
]
| [ 'filename | ASM_filename'
| ('filename | ASM_filename'
[, 'filename | ASM_filename' ] )
]
[ SIZE integer [ K | M | G | T | P | E ] ]
[ REUSE ]
}
{ MINIMUM EXTENT integer [ K | M | G | T | P | E ]
| BLOCKSIZE integer [ K ]
| { LOGGING | NOLOGGING }
| FORCE LOGGING
| DEFAULT [ { COMPRESS | NOCOMPRESS } ]
storage_clause
| { ONLINE | OFFLINE }
| EXTENT MANAGEMENT
{ LOCAL
[ AUTOALLOCATE
| UNIFORM
[ SIZE integer [ K | M | G | T | P | E ] ]
]
| DICTIONARY
}
| SEGMENT SPACE MANAGEMENT { AUTO | MANUAL }
Connect as SYSTEM.
CREATE USER username IDENTIFIED BY password;
GRANT CONNECT TO username;
GRANT EXECUTE on schema.procedure TO username;
Page 175
Sheet1
UPDATE table_name
SET set_clause
WHERE CURRENT OF cursor_name;
OR
DELETE FROM table_name
WHERE CURRENT OF cursor_name;
Page 176
Sheet1
CURSOR cursor_name
IS
select_statement
FOR UPDATE [OF column_list] [NOWAIT];
Cursor Cursor_Name IS SELECT Statement;
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
Page 177
Sheet1
ALTER TRIGGER trigger_name ENABLE;
NA
EXIT;
Page 178
Sheet1
GOTO label_name;
label_name must be unique within the scope of the code.
There must be at least one statement to execute after the Label Declaration.
NA
LOCK TABLE tables IN lock_mode MODE [ WAIT [, integer] | NOWAIT ];
OPEN cursor_name;
Page 179
Sheet1
[ label_name: ] REPEAT
{...statements...}
UNTIL condition
END REPEAT [ label_name ];
ROLLBACK;
Syntax : CREATE SEQUENCE <sequence_name>
MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;
ALTER DATABASE DEFAULT TABLESPACE tbs_perm_01;
You can run the following query to see that the default permanent tablespace has,
in fact, been changed:
SELECT PROPERTY_VALUE
FROM DATABASE_PROPERTIES
WHERE PROPERTY_NAME = 'DEFAULT_PERMANENT_TABLESPACE';
SET TRANSACTION [ READ ONLY | READ WRITE ]
[ ISOLATION LEVEL [ SERIALIZE | READ COMMITED ]
[ USE ROLLBACK SEGMENT 'segment_name' ]
[ NAME 'transaction_name' ];
SQLCODE
Page 180
Sheet1
SQLERRM
NA
NA
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
EXCEPTION
WHEN exception_name1 THEN
[statements]
WHEN exception_name2 THEN
[statements]
WHEN exception_name_n THEN
[statements]
WHEN OTHERS THEN
[statements]
Page 181
Sheet1
NA
Syntax : ABS( number )
ADD_MONTHS( date1, n )
ASCII( single_character )
ASCIISTR( string )
ASIN( number )
Page 182
Sheet1
ATAN( NUMBER )
ATAN2( n, m )
Page 183
Sheet1
CARDINALITY( nested table column )
CEIL( number )
CHARTOROWID( value1 )
CHR( number_code )
NA
COMPOSE( string )
I like ' || t.type_desc_column || ' cake with ' || t.icing_desc_column || ' and a
'
|| t.fruit_desc_column
CORR(
n ,m ) [ over (analytic_clause) ]
Page 184
Sheet1
COS( number )
NA
Page 185
Sheet1
CUME_DIST( expression1, ... expression_n ) WITHIN GROUP ( ORDER BY expression1,
... expression_n )
CURRENT_DATE( )
CURRENT_TIMESTAMP
DBTIMEZONE
DECOMPOSE( string )
Page 186
Sheet1
EMPTY_BLOB ()
EMPTY_CLOB ()
exp( number )
EXTRACT (
{ YEAR | MONTH | DAY | HOUR | MINUTE | SECOND }
| { TIMEZONE_HOUR | TIMEZONE_MINUTE }
| { TIMEZONE_REGION | TIMEZONE_ABBR }
FROM { date_value | interval_value } )
Page 187
Sheet1
FLOOR( number )
HEXTORAW( char )
INITCAP( string1 )
Page 188
Sheet1
INSTR( string, substring [, start_position [, nth_appearance ] ] )
string is the string to search. string can be CHAR, VARCHAR2, NCHAR, NVARCHAR2,
CLOB, or NCLOB.
substring is the substring to search for in string. substring can be CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
start_position is the position in string where the search will start. This
argument is optional. If omitted, it defaults to 1. The first position in the
string is 1. If the start_position is negative, the INSTR function counts back
start_position number of characters from the end of string and then searches
towards the beginning of string.
nth_appearance is the nth appearance of substring. This is optional. If omitted,
it defaults to 1.
Page 189
Sheet1
INSTRB( string, substring [, start_position [,
nth_appearance ] ] )
nth_appearance ] ] )
Page 190
Sheet1
LEAD ( expression [, offset [, default] ] )
over ( [ query_partition_clause ] order_by_clause )
expression is an expression that can contain other built-in functions, but can not
contain any analytic functions.
offset is optional. It is the physical offset from the current row in the table.
If this parameter is omitted, the default is 1.
LEAST( expr1, expr2, ... expr_n )
LENGTH( string1 )
Page 191
Sheet1
LENGTH2( string1 )
LENGTH4( string1 )
LENGTHB( string1 )
Page 192
Sheet1
LENGTHC( string1 )
LN( number )
LNNVL( condition )
LOCALTIMESTAMP
Page 193
Sheet1
LOG( m, n )
LOWER( string1 )
Page 194
Sheet1
MEDIAN( expression ) [ OVER ( query partition clause ) ]
MOD( m, n )
NCHR( number_code )
Page 195
Sheet1
NULLIF( expr1, expr2 )
Page 196
Sheet1
POWER( m, n )
If m is negative, then n must be an integer.
The syntax for the RANK function when used as an Analytic function is:
rank() OVER ( [ query_partition_clause] ORDER BY clause )
RAWTOHEX( raw )
Page 197
Sheet1
REMAINDER( m, n )
Page 198
Sheet1
ROUND( number, [ decimal_places ] )
RPAD('tech', 7)
Page 199
Sheet1
RTRIM( string1, [ trim_string ] )
SESSIONTIMEZONE
SIGN( number )
If number < 0, then sign returns -1.
If number = 0, then sign returns 0.
Page 200
Sheet1
SIN( n )
SINH( n )
SOUNDEX( string1 )
SQRT( n )
Page 201
Sheet1
SUBSTR( string, start_position, [ length ] )
TAN( n )
TANH( n )
Page 202
Sheet1
TO_CHAR( value, [ format_mask ], [ nls_language ] )
TO_CLOB( expression )
TO_LOB( long_column )
TO_MULTI_BYTE( char )
TO_NCLOB( expression )
TO_NUMBER( string1, [ format_mask ], [ nls_language ] )
Page 203
Sheet1
TO_SINGLE_BYTE( char )
TO_TIMESTAMP( string1, [ format_mask ] [ 'nlsparam' ] )
TO_TIMESTAMP_TZ( string1 , [ format_mask ] [ 'nlsparam' ] )
TO_YMINTERVAL( character )
Page 204
Sheet1
TRUNC ( date, [ format ] )
Page 205
Sheet1
TZ_OFFSET( timezone )
UID
UPPER( string1 )
USER
USERENV( parameter )
VARIANCE( expression )
VAR_POP( expression )
VAR_SAMP( expression )
Page 206
Sheet1
VSIZE( expression )
NA
NA
NA
NA
Page 207
Sheet1
NA
Page 208
Sheet1
CREATE PACKAGE cust_sal AS
PROCEDURE find_sal(c_id customers.id%type);
END cust_sal;
/
CREATE OR REPLACE PACKAGE BODY cust_sal AS
PROCEDURE find_sal(c_id customers.id%TYPE) IS
c_sal customers.salary%TYPE;
BEGIN
SELECT salary INTO c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line('Salary: '|| c_sal);
END find_sal;
END cust_sal;
/
NA
alter table
table_name
rename to
new_table_name;
Page 209
Sheet1
CREATE [UNIQUE] INDEX index_name
ON table_name (column1, column2, ... column_n)
[ COMPUTE STATISTICS ];
Page 210
Sheet1
Example(s)
SELECT ENO,ENAME,SAL FROM EMP;
SELECT ENO, ENAME,SAL, DEPTNO FROM EMP WHERE SAL>1800 ;
Equi Joins:
SELECT order_id, product_name, unit_price, supplier_name, total_units
FROM product, order_items
WHERE order_items.product_id = product.product_id;
Outer Join:
SELECT p.product_id, p.product_name, o.order_id, o.total_units
FROM order_items o, product p
WHERE o.product_id (+) = p.product_id;
Self Join
SELECT E.ename, M.Ename FROM Emp E, Emp M
WHERE M.empno = E.mgr;
Non Equi Join:
SELECT E.Ename, E.Sal S.grade
FROM emp E, salgrade
WHERE E.sal between s.losal AND S.hisal;
Page 211
Sheet1
SELECT e.empno,e.ename,e.sal,d.dname,d.location from emp e inner join dept d on
e.deptno=d.deptno;
SELECT e.empno,e.ename,e.sal,d.dname,d.location from emp e,dept d where
e.deptno=d.deptno;
Page 212
Sheet1
Page 213
Sheet1
SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;
UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
NA
Select * from (select rownum rn,sal from(select * from emp order by sal desc))
where rn=&m;
select max(sal) FROM emp
WHERe sal NOT IN (SELECT MAx(sal) FROM emp);
Delete from emp;
truncate table emp;
Page 214
Sheet1
TRUNCATE TABLE emp;
DROP TABLE emp;
NA
select CONVERT(VARCHAR(10),BusinessEntityID) FROM HumanResources.Employee
select CAST(BusinessEntityID AS VARCHAR(10)) FROM HumanResources.Employee
NA
NA
NA
NA
dual;
Page 215
Sheet1
NA
Page 216
Sheet1
Example :
DELETE FROM xx_dupl_test
WHERE rowid not in
(SELECT MIN(rowid) FROM xx_dupl_test group BY SNO, name);
NA
SELECT GETDATE() AS CurrentDateTime
SELECT DATEDIFF(day,'2008-06-05','2008-08-05') AS DiffDate
SELECT OrderId,DATEADD(day,45,OrderDate) AS OrderPayDate
FROM Orders
SELECT DATEPART(yyyy,OrderDate) AS OrderYear,
DATEPART(mm,OrderDate) AS OrderMonth,
DATEPART(dd,OrderDate) AS OrderDay
FROM Orders
WHERE OrderId=1
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
Page 217
Sheet1
INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers
WHERE Country='Germany';
INSERT
INTO
INTO
INTO
SELECT
ALL
suppliers (supplier_id, supplier_name) VALUES (1000, 'IBM')
suppliers (supplier_id, supplier_name) VALUES (2000, 'Microsoft')
suppliers (supplier_id, supplier_name) VALUES (3000, 'Google')
* FROM dual;
INSERT ALL
INTO suppliers (supplier_id, supplier_name) VALUES (1000, 'IBM')
INTO suppliers (supplier_id, supplier_name) VALUES (2000, 'Microsoft')
INTO customers (customer_id, customer_name, city) VALUES (999999, 'Anderson
Construction', 'New York')
SELECT * FROM dual;
Page 218
Sheet1
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
)
SELECT CASE WHEN (GROUPING(Item) = 1) THEN 'ALL'
ELSE ISNULL(Item, 'UNKNOWN')
END AS Item,
CASE WHEN (GROUPING(Color) = 1) THEN 'ALL'
ELSE ISNULL(Color, 'UNKNOWN')
END AS Color,
SUM(Quantity) AS QtySum
FROM Inventory
GROUP BY Item, Color WITH ROLLUP
SELECT Item, Color, SUM(Quantity) AS QtySum
FROM Inventory
GROUP BY Item, Color WITH CUBE
SELECT
FROM
WHERE
ProductID
TableBC
EXISTS
(
SELECT
ProductID
FROM
Products
WHERE
Products.ProductID = TableBC.ProductID
AND
BINARY_CHECKSUM(*) <> TableBC.bchecksum)
Page 219
Sheet1
SELECT
CHECKSUM_AGG(CONVERT(INT,UnitsInStock)) FROM
USE AdventureWorks2012;
GO
EXEC sp_columns @table_name = N'Department',
@table_owner = N'HumanResources';
CREATE OR REPLACE
PROCEDURE ADD_EVALUATION
( evaluation_id IN NUMBER
, employee_id IN NUMBER
, evaluation_date IN DATE
, job_id IN VARCHAR2
, manager_id IN NUMBER
, department_id IN NUMBER
) AS
BEGIN
NULL;
END ADD_EVALUATION;
Page 220
Products
Sheet1
USE master;
GO
EXEC sp_who;
GO
NA
EXECUTE sp_executesql
N'SELECT * FROM AdventureWorks2012.HumanResources.Employee
WHERE BusinessEntityID = @level',
N'@level tinyint',
@level = 109;
Page 221
Sheet1
SELECT cust_last_name,
CASE credit_limit WHEN 100 THEN 'Low'
WHEN 5000 THEN 'High'
ELSE 'Medium' END
FROM customers
SELECT *
FROM
(SELECT product_code, quantity
FROM
pivot_test)
PIVOT (SUM(quantity) AS sum_quantity FOR (product_code) IN ('A' AS a, 'B' AS b,
'C' AS c));
MERGE INTO employees e
USING (SELECT * FROM hr_records WHERE start_date > ADD_MONTHS(SYSDATE, -1)) h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address)
VALUES (h.emp_id, h.address);
SELECT CustomerID, OrderDate, SubTotal, TotalDue
FROM Sales.SalesOrderHeader
WHERE SalesPersonID = 35
ORDER BY OrderDate
COMPUTE SUM(SubTotal), SUM(TotalDue);
Page 222
Sheet1
NA
NA
NA
Page 223
Sheet1
NA
NA
NA
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
Page 224
Sheet1
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;
RETURN total;
END;
/
DECLARE
TYPE numbers_nt IS TABLE OF NUMBER;
l_numbers numbers_nt;
BEGIN
l_numbers := numbers_nt (1, 2, 3);
END;
Page 225
Sheet1
e.g DECLARE
TYPE employee_type IS RECORD
(employee_id number(5),
employee_first_name varchar2(25),
employee_last_name employee.last_name%type,
employee_dept employee.dept%type);
employee_salary employee.salary%type;
employee_rec employee_type;
DECLARE
customer_rec customers%rowtype;
BEGIN
SELECT * into customer_rec
FROM customers
WHERE id = 5;
dbms_output.put_line('Customer
dbms_output.put_line('Customer
dbms_output.put_line('Customer
dbms_output.put_line('Customer
END;
/
DECLARE
TYPE books IS RECORD
(title varchar(50),
author varchar(50),
subject varchar(100),
book_id
number);
book1 books;
book2 books;
Page 226
Sheet1
DECLARE
CURSOR customer_cur is
SELECT id, name, address
FROM customers;
customer_rec customer_cur%rowtype;
BEGIN
OPEN customer_cur;
LOOP
FETCH customer_cur into customer_rec;
EXIT WHEN customer_cur%notfound;
DBMS_OUTPUT.put_line(customer_rec.id || ' ' || customer_rec.name);
END LOOP;
END;
Page 227
Sheet1
E.g : DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
CREATE OR REPLACE
PROCEDURE get_emp_rs (p_deptno
IN emp.deptno%TYPE,
p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR
SELECT ename,
empno,
deptno
FROM
emp
WHERE deptno = p_deptno
ORDER BY ename;
END GetEmpRS;
/
Page 228
Sheet1
E.g CREATE OR REPLACE Function TotalIncome
( name_in IN varchar2 )
RETURN varchar2
IS
total_val number(6);
cursor c1 is
SELECT monthly_income
FROM employees
WHERE name = name_in;
BEGIN
total_val := 0;
FOR employee_rec in c1
LOOP
total_val := total_val + employee_rec.monthly_income;
END LOOP;
RETURN total_val;
END;
DECLARE
cursor c(no number) is select * from emp_information
where emp_no = no;
tmp emp_information%rowtype;
BEGIN
OPEN c(4);
FOR tmp IN c(4) LOOP
dbms_output.put_line('EMP_No:
'||tmp.emp_no);
dbms_output.put_line('EMP_Name: '||tmp.emp_name);
dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);
dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);
END Loop;
CLOSE c;
END;
/
Page 229
Sheet1
e.g.
DECLARE
CURSOR trip_cursor IS
SELECT
bt_id_pk,
bt_duration
FROM
business_trips
WHERE
bt_id_pk = 23
FOR UPDATE OF bt_id_pk, bt_duration;
BEGIN
FOR trip_record IN trip_cursor LOOP
UPDATE business_trips
SET bt_duration = 5
WHERE CURRENT OF trip_cursor;
END LOOP;
COMMIT;
END;
NA
Page 230
Sheet1
GRANT CREATE TABLE TO testing;
REVOKE CREATE TABLE FROM testing;
Page 231
Sheet1
NA
NA
Page 232
Sheet1
NA
Page 233
Sheet1
NA
Page 234
Sheet1
NA
NA
Page 235
Sheet1
NA
Page 236
Sheet1
NA
NA
NA
NA
SELECT SUM(salary) AS "Total Salary"
FROM employees
WHERE salary > 25000;
SELECT MIN(salary) AS "Lowest salary"
FROM employees;
SELECT department, MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department;
SELECT supplier_id
FROM suppliers
WHERE supplier_name = 'IBM'
OR city = 'New York'
OR offices > 5;
SELECT *
FROM suppliers
WHERE (city = 'New York' AND name = 'IBM')
OR (ranking >= 10);
SELECT supplier_name
FROM suppliers
WHERE supplier_name LIKE '%bob%';
SELECT last_name
FROM contacts
WHERE REGEXP_LIKE (last_name, 'Anders(o|e|a)n');
SELECT *
FROM suppliers
WHERE supplier_name IN ('IBM', 'Hewlett Packard', 'Microsoft');
SELECT *
FROM suppliers
WHERE supplier_name NOT IN ( 'IBM', 'Hewlett Packard', 'Microsoft' );
SELECT *
FROM suppliers
WHERE EXISTS (SELECT *
FROM orders
WHERE suppliers.supplier_id = orders.supplier_id);
create TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), Address varchar(255), City varchar(255) DEFAULT 'Sandnes'
)
DROP TABLE EMP;
Page 237
Sheet1
declare global temporary table t2(c21 int) not logged;
Page 238
Sheet1
SELECT *
FROM customers
WHERE customer_name IS NOT NULL;
SELECT supplier_id
FROM suppliers
UNION
SELECT supplier_id
FROM orders;
SELECT supplier_id
FROM suppliers
UNION ALL
SELECT supplier_id
FROM orders;
Page 239
Sheet1
CREATE OR REPLACE TRIGGER orders_after_insert
AFTER INSERT
ON orders
FOR EACH ROW
DECLARE
v_username varchar2(10);
BEGIN
-- Find username of person performing the INSERT into the table
SELECT user INTO v_username
FROM dual;
-- Insert record into audit table
INSERT INTO orders_audit
( order_id,
quantity,
cost_per_item,
total_cost,
username )
VALUES
( :new.order_id,
:new.quantity,
:new.cost_per_item,
:new.total_cost,
v_username );
END;
Page 240
Sheet1
CREATE OR REPLACE TRIGGER orders_after_update
AFTER UPDATE
ON orders
FOR EACH ROW
DECLARE
v_username varchar2(10);
BEGIN
-- Find username of person performing UPDATE into table
SELECT user INTO v_username
FROM dual;
-- Insert record into audit table
INSERT INTO orders_audit
( order_id,
quantity_before,
quantity_after,
username )
VALUES
( :new.order_id,
:old.quantity,
:new.quantity,
v_username );
END;
Page 241
Sheet1
ALTER TABLESPACE tablespace_name
{ DEFAULT
[ { COMPRESS | NOCOMPRESS } ] storage_clause
| MINIMUM EXTENT integer [ K | M | G | T | P | E ]
| RESIZE integer [ K | M | G | T | P | E ]
| COALESCE
| RENAME TO new_tablespace_name
| { BEGIN | END } BACKUP
| { ADD { DATAFILE | TEMPFILE }
[ file_specification
[, file_specification ]
]
| DROP {DATAFILE | TEMPFILE } { 'filename' | file_number }
| RENAME DATAFILE 'filename' [, 'filename' ] TO 'filename' [, 'filename' ]
| { DATAFILE | TEMPFILE } { ONLINE | OFFLINE }
}
| { logging_clause | [ NO ] FORCE LOGGING }
| TABLESPACE GROUP { tablespace_group_name | '' }
| { ONLINE
| OFFLINE [ NORMAL | TEMPORARY | IMMEDIATE ]
}
| READ { ONLY | WRITE }
| { PERMANENT | TEMPORARY }
| AUTOEXTEND
{ OFF
| ON [ NEXT integer [ K | M | G | T | P | E ] ]
[ MAXSIZE { UNLIMITED | integer [ K | M | G | T | P | E ] } ]
}
| FLASHBACK { ON | OFF }
| RETENTION { GUARANTEE | NOGUARANTEE }
} ;
Page 242
Sheet1
CREATE OR REPLACE TRIGGER orders_before_delete
BEFORE DELETE
ON orders
FOR EACH ROW
DECLARE
v_username varchar2(10);
BEGIN
-- Find username of person performing the DELETE on the table
SELECT user INTO v_username
FROM dual;
-- Insert record into audit table
INSERT INTO orders_audit
( order_id,
quantity,
cost_per_item,
total_cost,
delete_date,
deleted_by )
VALUES
( :old.order_id,
:old.quantity,
:old.cost_per_item,
:old.total_cost,
sysdate,
v_username );
END;
Page 243
Sheet1
CREATE OR REPLACE TRIGGER orders_before_insert
BEFORE INSERT
ON orders
FOR EACH ROW
DECLARE
v_username varchar2(10);
BEGIN
-- Find username of person performing INSERT into table
SELECT user INTO v_username
FROM dual;
-- Update create_date field to current system date
:new.create_date := sysdate;
-- Update created_by field to the username of the person performing the INSERT
:new.created_by := v_username;
END;
Page 244
Sheet1
commit;
CREATE SCHEMA AUTHORIZATION smithj
CREATE TABLE products
( product_id number(10) not null,
product_name varchar2(50) not null,
category varchar2(50),
CONSTRAINT products_pk PRIMARY KEY (product_id)
);
CREATE TABLESPACE tbs_perm_01
DATAFILE 'tbs_perm_01.dat'
SIZE 20M
ONLINE;
CREATE TEMPORARY TABLESPACE tbs_temp_01
TEMPFILE 'tbs_temp_01.dbf'
SIZE 5M
AUTOEXTEND ON;
CREATE UNDO TABLESPACE tbs_undo_01
DATAFILE 'tbs_undo_01.f'
SIZE 5M
AUTOEXTEND ON
RETENTION GUARANTEE;
Connect as system;
create user scott identified by tiger;
grant connect,resource,dba to scott;
Page 245
Sheet1
Page 246
Sheet1
CURSOR c1
IS
SELECT course_number, instructor
FROM courses_tbl
FOR UPDATE OF instructor;
CURSOR C IS SELECT * FROM EMP;
LDescription varchar2(40);
LDescription := 'techonthenet.com Example';
CREATE OR REPLACE PROCEDURE add_new_order
(order_id_in IN NUMBER, sales_in IN NUMBER)
IS
no_sales EXCEPTION;
BEGIN
IF sales_in = 0 THEN
RAISE no_sales;
ELSE
INSERT INTO orders (order_id, total_sales )
VALUES ( order_id_in, sales_in );
END IF;
EXCEPTION
WHEN no_sales THEN
raise_application_error (-20001,'You must have sales in order to submit the
order.');
WHEN OTHERS THEN
raise_application_error (-20002,'An error has occurred inserting an
order.');
END;
NA
NA
NA
NA
DROP TABLESPACE tbs_perm_01
INCLUDING CONTENTS
CASCADE CONSTRAINTS;
NA
DROP USER SCOTT CASCADE;
Page 247
Sheet1
NA
NA
EXIT;
CURSOR C IS SELECT * FROM EMP;
OPEN C;
FETCH C.empno into emp_number;
NA
NA
NA
for I in 1..10 loop
dbms_output.put_line('value of I is :||I);
end loop;
NA
NA
NA
Page 248
Sheet1
CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;
CURSOR c1
IS
SELECT MAX(course_number)
FROM courses_tbl
WHERE course_name = name_in;
BEGIN
open c1;
fetch c1 into cnumber;
IF c1%notfound then
GOTO default_number;
ELSE
GOTO increment_number;
END IF;
<<default_number>>
cnumber := 0;
<<increment_number>>
cnumber := cnumber + 1;
close c1;
RETURN cnumber;
END;
LOCK TABLE suppliers IN SHARE MODE NOWAIT;
Cursor c is select * from emp;
OPEN C;
FETCH C.empno into emp_number;
Page 249
Sheet1
DELIMITER //
CREATE FUNCTION CalcIncome ( starting_value INT )
RETURNS INT
BEGIN
DECLARE income INT;
SET income = 0;
label1: REPEAT
SET income = income + starting_value;
UNTIL income >= 4000
END REPEAT label1;
RETURN income;
END; //
DELIMITER ;
ROLLBACK;
CREATE SEQUENCE customers_seq
START WITH
1000
INCREMENT BY
1
NOCACHE
NOCYCLE;
NA
Page 250
Sheet1
SQLERRM
NA
NA
CREATE OR REPLACE PROCEDURE add_new_order
(order_id_in IN NUMBER, sales_in IN NUMBER)
IS
no_sales EXCEPTION;
BEGIN
IF sales_in = 0 THEN
RAISE no_sales;
ELSE
INSERT INTO orders (order_id, total_sales )
VALUES ( order_id_in, sales_in );
END IF;
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
raise_application_error (-20001,'You have tried to insert a duplicate
order_id.');
WHEN no_sales THEN
raise_application_error (-20001,'You must have sales in order to submit the
order.');
WHEN OTHERS THEN
raise_application_error (-20002,'An error has occurred inserting an
order.');
END;
Page 251
Sheet1
NA
E.g ABS(-23)
Result: 23
ABS(-23.6)
Result: 23.6
ABS(-23.65)
Result: 23.65
ACOS(0.2)
Result: 1.36943840600457
ACOS(0.35)
Result: 1.21322522314939
ACOS(-0.15)
Result: 1.72136459957158
ADD_MONTHS('01-Aug-03', 3)
Result: '01-Nov-03'
ASCII('t')
Result: 116
ASCII('T')
Result: 84
ASCII('T2')
Result: 84
ASCIISTR('A B C ')
Result: 'A B C \00C4 \00CA'
ASCIISTR('A B C ')
Result: 'A B C \00D5 \00D8'
ASCIISTR('A B C ')
Result: 'A B C \00C4 \00CA \00CD \00D5 \00D8'
ASIN(0.2)
Result: 0.201357920790331
ASIN(0.35)
Result: 0.35757110364551
ASIN(-0.15)
Result: -0.150568272776686
Page 252
Sheet1
ATAN(0.2)
Result: 0.197395559849881
ATAN(0.35)
Result: 0.336674819386727
ATAN(-0.15)
Result: -0.148889947609497
ATAN2(0.2, 0.3)
Result: 0.588002603547568
ATAN2(0.35, -0.15)
Result: 1.97568811307998
ATAN2(-0.3, -0.4)
Result: -2.49809154479651
SELECT BFILENAME('exampleDir', 'totn_logo.png')
FROM dual;
BIN_TO_NUM(1)
Result: 1
BIN_TO_NUM(1,0)
Result: 2
BIN_TO_NUM(1,1)
Result: 3
BIN_TO_NUM(1,1,1,0)
Result: 14
BIN_TO_NUM(1,1,1,1)
Result: 15
BITAND(5,3)
Result: 1
BITAND(15,7)
Result: 7
BITAND(5,2)
Result: 0
BITAND(5,0)
Result: 0
BITAND(6,2)
Result: 2
Page 253
Sheet1
select supplier_id, CARDINALITY(location)
from suppliers;
COMPOSE('o' || unistr('\0308') )
Result:
COMPOSE('a' || unistr('\0302') )
Result:
COMPOSE('e' || unistr('\0301') )
Result:
CONCAT('Tech on', ' the Net')
Result: 'Tech on the Net'
CONCAT('a', 'b')
Result: 'ab'
I like ' || t.type_desc_column || ' cake with ' || t.icing_desc_column || ' and a
'
|| t.fruit_desc_column
select CORR(quantity, commission)
from sales;
Page 254
Sheet1
COS(0.2)
Result: 0.980066577841242
COS(0.35)
Result: 0.939372712847379
COS(-3.15)
Result: -0.999964658471342
COS(200)
Result: 0.487187675007006
Page 255
Sheet1
Example (as an Aggregate Function)
select CUME_DIST(1000, 500) WITHIN GROUP (ORDER BY salary, bonus)
from employees;
As Analytical Function
CUME_DIST() OVER ( [ query_partition_clause] ORDER BY clause )
E.g select employee_name, salary,
CUME_DIST() OVER (PARTITION BY department ORDER BY salary)
from employees
where department = 'Marketing';
mysql> SELECT CURRENT_DATE();
-> '2014-01-28'
mysql> SELECT CURRENT_DATE() + 0;
-> 20140128
mysql> SELECT CURRENT_DATE() + 1;
-> 20140129
select CURRENT_TIMESTAMP
from dual;
select DBTIMEZONE
from dual;
SELECT supplier_name,
DECODE(supplier_id, 10000, 'IBM',
10001, 'Microsoft',
10002, 'Hewlett Packard',
'Gateway') result
FROM suppliers;
DECOMPOSE('Trs bien')
Result: 'Tre`s bien'
DECOMPOSE('')
Result: 'e'
DECOMPOSE('ol')
Result: 'ole'
Page 256
Sheet1
DUMP('Tech')
Result: 'Typ=96 Len=4: 84,101,99,104'
DUMP('Tech', 10)
Result: 'Typ=96 Len=4: 84,101,99,104'
DUMP('Tech', 16)
Result: 'Typ=96 Len=4: 54,65,63,68'
DUMP('Tech', 1016)
Result: 'Typ=96 Len=4 CharacterSet=US7ASCII: 54,65,63,68'
DUMP('Tech', 1017)
Result: 'Typ=96 Len=4 CharacterSet=US7ASCII: T,e,c,h'
UPDATE products
SET product_photo = EMPTY_BLOB();
UPDATE customers
SET customer_photo = EMPTY_CLOB();
EXP(3)
Result: 20.0855369231877
EXP(3.1)
Result: 22.1979512814416
EXP(-3)
Result: 0.0497870683678639
EXTRACT(YEAR FROM DATE '2003-08-22')
Result: 2003
EXTRACT(MONTH FROM DATE '2003-08-22')
Result: 8
EXTRACT(DAY FROM DATE '2003-08-22')
Result: 22
Page 257
Sheet1
FLOOR(5.9)
Result: 5
FLOOR(34.29)
Result: 34
FLOOR(-5.9)
Result: -6
HEXTORAW('45D')
Result: '045D' (as a raw value)
HEXTORAW('7E')
Result: '7E'
Page 258
Sheet1
E. G
INSTR('Tech on the net', 'e')
Result: 2
(the first occurrence of 'e')
INSTR('Tech on the net', 'e', 1, 1)
Result: 2
(the first occurrence of 'e')
INSTR('Tech on the net', 'e', 1, 2)
Result: 11 (the second occurrence of 'e')
INSTR('Tech on the net', 'e', 1, 3)
Result: 14 (the third occurrence of 'e')
INSTR('Tech on the net', 'e', -3, 2)
Result: 2
INSTR2('TechOnTheNet.com', 'e')
Result: 2
(the first occurrence of 'e')
INSTR2('TechOnTheNet.com', 'e', 1, 1)
Result: 2
(the first occurrence of 'e')
INSTR2('TechOnTheNet.com', 'e', 1, 2)
Result: 9
(the second occurrence of 'e')
INSTR2('TechOnTheNet.com', 'e', 1, 3)
Result: 11 (the third occurrence of 'e')
INSTR2('TechOnTheNet.com', 'e', -3, 2)
Result: 9
INSTR4('TechOnTheNet.com', 'e')
Result: 2
(the first occurrence of 'e')
INSTR4('TechOnTheNet.com', 'e', 1, 1)
Result: 2
(the first occurrence of 'e')
INSTR4('TechOnTheNet.com', 'e', 1, 2)
Result: 9
(the second occurrence of 'e')
INSTR4('TechOnTheNet.com', 'e', 1, 3)
Result: 11 (the third occurrence of 'e')
INSTR4('TechOnTheNet.com', 'e', -3, 2)
Result: 9
Page 259
Sheet1
INSTRB('TechOnTheNet.com', 'e')
Result: 2
(the first occurrence of 'e' - single-byte character set)
INSTRB('TechOnTheNet.com', 'e', 1, 1)
Result: 2; (the first occurrence of 'e' - single-byte character set)
INSTRB('TechOnTheNet.com', 'e', 1, 2)
Result: 9; (the second occurrence of 'e' - single-byte character set)
INSTRB('TechOnTheNet.com', 'e', 1, 3)
Result: 11; (the third occurrence of 'e' - single-byte character set)
INSTRB('TechOnTheNet.com', 'e', -3, 2)
Result: 9
(single-byte character set)
INSTRC('TechOnTheNet.com', 'e')
Result: 2
(the first occurrence of 'e')
INSTRC('TechOnTheNet.com', 'e', 1, 1)
Result: 2
(the first occurrence of 'e')
INSTRC('TechOnTheNet.com', 'e', 1, 2)
Result: 9
(the second occurrence of 'e')
INSTRC('TechOnTheNet.com', 'e', 1, 3)
Result: 11 (the third occurrence of 'e')
INSTRC('TechOnTheNet.com', 'e', -3, 2)
Result: 9
LAST_DAY(TO_DATE('2003/03/15', 'yyyy/mm/dd'))
Result: Mar 31, 2003
LAST_DAY(TO_DATE('2003/02/03', 'yyyy/mm/dd'))
Result: Feb 28, 2003
LAST_DAY(TO_DATE('2004/02/03', 'yyyy/mm/dd'))
Result: Feb 29, 2004
Page 260
Sheet1
select product_id, order_date,
LEAD (order_date,1) over (ORDER BY order_date) AS next_order_date
from orders;
LEAST(2, 5, 12, 3)
Result: 2
LEAST('2', '5', '12', '3')
Result: '12'
LEAST('apples', 'oranges', 'bananas')
Result: 'apples'
LEAST('apples', 'applis', 'applas')
Result: 'applas'
LEAST('apples', 'applis', 'applas', null)
Result: NULL
LENGTH(NULL)
Result: NULL
LENGTH('')
Result: NULL
LENGTH(' ')
Result: 1
LENGTH('Tech on the Net')
Result: 15
LENGTH('Tech on the Net ')
Result: 16
Page 261
Sheet1
LENGTH2(NULL)
Result: NULL
LENGTH2('')
Result: NULL
LENGTH2(' ')
Result: 1
LENGTH2('TechOnTheNet.com')
Result: 16
LENGTH2('TechOnTheNet.com ')
Result: 17
LENGTHB(' ')
Result: 1
LENGTHB('TechOnTheNet.com')
Result: 16
(single-byte character set)
LENGTHB('TechOnTheNet.com ')
Result: 17
(single-byte character set)
Page 262
Sheet1
If string1 is NULL, then the LENGTHC function will return NULL.
LENGTHC(NULL)
Result: NULL
LENGTHC('')
Result: NULL
LENGTHC(' ')
Result: 1
LENGTHC('TechOnTheNet.com')
Result: 16
LENGTHC('TechOnTheNet.com ')
Result: 17
Page 263
Sheet1
LOG(10, 20)
Result: 1.30102999566398
LOG(2, 15)
Result: 3.90689059560852
LOG(100, 1)
Result: 0
LOWER('Tech on the Net');
Result: 'tech on the net'
LOWER('GEORGE BURNS 123
');
Result: 'george burns 123
'
LPAD('tech', 7);
Result: '
tech'
LPAD('tech', 2);
Result: 'te'
LPAD('tech', 8, '0');
Result: '0000tech'
LPAD('tech on the net', 15, 'z');
Result: 'tech on the net'
LPAD('tech on the net', 16, 'z');
Result: 'ztech on the net'
LTRIM('
tech')
Result: 'tech'
LTRIM('
tech', ' ')
Result: 'tech'
LTRIM('000123', '0')
Result: '123'
LTRIM('123123Tech', '123')
Result: 'Tech'
LTRIM('123123Tech123', '123')
Result: 'Tech123'
LTRIM('xyxzyyyTech', 'xyz')
Result: 'Tech'
LTRIM('6372Tech', '0123456789')
Result: 'Tech'
Page 264
Sheet1
The MEDIAN function is NEW to Oracle 10! In older versions of Oracle, try using
the PERCENTILE_CONT function to calculate the median value.
select MEDIAN(salary)
from employees
where department = 'Marketing';
MOD(15, 4)
Result: 3
MOD(15, 0)
Result: 15
MOD(11.6, 2)
Result: 1.6
MOD(11.6, 2.1)
Result: 1.1
MOD(-15, 4)
Result: -3
MOD(-15, 0)
Result: -15
Page 265
Sheet1
NULLIF(12, 12)
Result: NULL
NULLIF(12, 13)
Result: 12
NULLIF('apples', 'apples')
Result: NULL
NULLIF('apples', 'oranges')
Result: 'apples'
NULLIF(NULL, 12)
Result: ORA-00932 error
NUMTODSINTERVAL(150, 'DAY')
Result: '+000000150'
NUMTODSINTERVAL(1500, 'HOUR')
Result: '+000000062'
NUMTODSINTERVAL(15000, 'MINUTE')
Result: '+000000010'
NUMTODSINTERVAL(150000, 'SECOND')
Result: '+000000001'
NUMTOYMINTERVAL(100000000, 'MONTH')
Result: '+0083'
NUMTOYMINTERVAL(100000, 'YEAR')
Result: '+0001'
SELECT NVL(supplier_city, 'n/a')
FROM suppliers;
select NVL2(supplier_city, 'Completed', 'n/a')
from suppliers;
Page 266
Sheet1
POWER(3, 2)
Result: 9
POWER(5, 3)
Result: 125
POWER(-5, 3)
Result: -125
POWER(6.2, 3)
Result: 238.328
POWER(6.2, 3.5)
Result: 593.431934277892
Page 267
Sheet1
REMAINDER(15, 6)
Result: 3
REMAINDER(15, 5)
Result: 0
REMAINDER(15, 4)
Result: -1
REMAINDER(11.6, 2)
Result: -0.4
REMAINDER(11.6, 2.1)
Result: -1
REMAINDER(-15, 4)
Result: 1
ROUND(TO_DATE ('22-AUG-03'),'YEAR')
Result: '01-JAN-04'
ROUND(TO_DATE ('22-AUG-03'),'Q')
Result: '01-OCT-03'
ROUND(TO_DATE ('22-AUG-03'),'MONTH')
Result: '01-SEP-03'
ROUND(TO_DATE ('22-AUG-03'),'DDD')
Result: '22-AUG-03'
ROUND(TO_DATE ('22-AUG-03'),'DAY')
Result: '24-AUG-03'
Page 268
Sheet1
ROUND(125.315)
Result: 125
ROUND(125.315, 0)
Result: 125
ROUND(125.315, 1)
Result: 125.3
ROUND(125.315, 2)
Result: 125.32
ROUND(125.315, 3)
Result: 125.315
ROUND(-125.315, 2)
Result: -125.32
Result: 'tech
'
RPAD('tech', 2)
Result: 'te'
RPAD('tech', 8, '0')
Result: 'tech0000'
RPAD('tech on the net', 15, 'z')
Result: 'tech on the net'
RPAD('tech on the net', 16, 'z')
Result: 'tech on the netz'
Page 269
Sheet1
RTRIM('tech
')
Result: 'tech'
RTRIM('tech
', ' ')
Result: 'tech'
RTRIM('123000', '0')
Result: '123'
RTRIM('Tech123123', '123')
Result: 'Tech'
RTRIM('123Tech123', '123')
Result: '123Tech'
RTRIM('Techxyxzyyy', 'xyz')
Result: 'Tech'
RTRIM('Tech6372', '0123456789')
Result: 'Tech'
SELECT SESSIONTIMEZONE
FROM dual;
Page 270
Sheet1
SIN(3)
Result: 0.141120008059867
SIN(5.2)
Result: -0.883454655720153
SIN(-5.2)
Result: 0.883454655720153
SINH(3)
Result: 10.0178749274099
SINH(5.2)
Result: 90.6333626553652
SINH(-5.2)
Result: -90.6333626553652
SOUNDEX('tech on the net')
Result: 'T253'
SOUNDEX('TECH ON THE NET')
Result: 'T253'
SOUNDEX('apples')
Result: 'A142'
SOUNDEX('apples are great')
Result: 'A142'
SOUNDEX('applus')
Result: 'A142'
SQRT(9)
Result: 3
SQRT(37)
Result: 6.08276253029822
SQRT(5.617)
Result: 2.37002109695251
select STDDEV(bonus)
from employees;
Page 271
Sheet1
SUBSTR('This is a test', 6, 2)
Result: 'is'
SUBSTR('This is a test', 6)
Result: 'is a test'
SUBSTR('TechOnTheNet', 1, 4)
Result: 'Tech'
SUBSTR('TechOnTheNet', -3, 3)
Result: 'Net'
SUBSTR('TechOnTheNet', -6, 3)
Result: 'The'
SUBSTR('TechOnTheNet', -8, 2)
Result: 'On'
Page 272
Sheet1
TO_CHAR(1210.73, '9999.9')
Result: ' 1210.7'
TO_CHAR(-1210.73, '9999.9')
Result: '-1210.7'
TO_CHAR(1210.73, '9,999.99')
Result: ' 1,210.73'
TO_CHAR(1210.73, '$9,999.00')
Result: ' $1,210.73'
TO_CHAR(21, '000099')
Result: ' 000021'
select TO_CLOB(nclob_column)
from suppliers;
TO_DATE('2003/07/09', 'yyyy/mm/dd')
Result: date value of July 9, 2003
TO_DATE('070903', 'MMDDYY')
Result: date value of July 9, 2003
TO_DATE('20020315', 'yyyymmdd')
Result: date value of Mar 15, 2002
TO_DSINTERVAL('150 08:30:00')
Result: '+000000150'
TO_DSINTERVAL('80 12:30:00')
Result: '+000000080'
TO_DSINTERVAL('95 18:30:00')
Result: '+000000095'
insert into companies (lob_column)
select TO_LOB(long_column)
from suppliers;
select TO_MULTI_BYTE('Tech on the net')
from dual;
select TO_NCLOB(lob_column)
from suppliers;
TO_NUMBER('1210.73', '9999.99')
Result: 1210.73
TO_NUMBER('546', '999')
Result: 546
TO_NUMBER('23', '99')
Result: 23
Page 273
Sheet1
select TO_SINGLE_BYTE('Tech on the net')
from dual;
TO_TIMESTAMP('2003/12/13 10:13:18', 'YYYY/MM/DD HH:MI:SS')
TO_TIMESTAMP_TZ('2003/12/13 10:13:18 -8:00', 'YYYY/MM/DD HH:MI:SS TZH:TZM')
TO_YMINTERVAL('03-11')
Result: 3 years 11 months
(as an INTERVAL YEAR TO MONTH type)
TO_YMINTERVAL('01-05')
Result: 1 year 5 months
TO_YMINTERVAL('00-01')
Result: 0 years 1 month
TRIM('
tech
Result: 'tech'
')
'
tech
')
Page 274
Sheet1
TRUNC(TO_DATE('22-AUG-03'), 'YEAR')
Result: '01-JAN-03'
TRUNC(TO_DATE('22-AUG-03'), 'Q')
Result: '01-JUL-03'
TRUNC(TO_DATE('22-AUG-03'), 'MONTH')
Result: '01-AUG-03'
TRUNC(TO_DATE('22-AUG-03'), 'DDD')
Result: '22-AUG-03'
TRUNC(TO_DATE('22-AUG-03'), 'DAY')
Result: '17-AUG-03'
TRUNC(125.815)
Result: 125
TRUNC(125.815, 0)
Result: 125
TRUNC(125.815, 1)
Result: 125.8
TRUNC(125.815, 2)
Result: 125.81
TRUNC(125.815, 3)
Result: 125.815
TRUNC(-125.815, 2)
Result: -125.81
TRUNC(125.815, -1)
Result: 120
TRUNC(125.815, -2)
Result: 100
TRUNC(125.815, -3)
Result: 0
Page 275
Sheet1
TZ_OFFSET('US/Michigan')
Result: '-05:00'
TZ_OFFSET('-08:00')
Result: '-08:00'
TZ_OFFSET(sessiontimezone)
Result: '-07:00' (depending on your configuration)
TZ_OFFSET(dbtimezone)
Result: '-07:00' (depending on your configuration)
SELECT UID
INTO parm_uid
FROM dual;
UPPER('Tech on the Net')
Result: 'TECH ON THE NET'
UPPER('george burns 123
')
Result: 'GEORGE BURNS 123
'
select USER
into parm_user_ID
from dual;
USERENV('ENTRYID')
Result: FALSE
USERENV('LANGUAGE')
Result: 'AMERICAN_AMERICA.WE8DEC'
select VARIANCE(char_length)
from all_tab_columns;
select VAR_POP(data_length)
from all_tab_columns;
select VAR_SAMP(char_length)
from all_tab_columns;
Page 276
Sheet1
VSIZE('Tech on the net')
Result: 15
VSIZE('Tech on the net ')
Result: 16
VSIZE(null)
Result: <null>
VSIZE('')
Result: <null>
VSIZE(' ')
Result: 1
NA
NA
NA
Page 277
Sheet1
NA
Page 278
Sheet1
CREATE PACKAGE cust_sal AS
PROCEDURE find_sal(c_id customers.id%type);
END cust_sal;
/
CREATE OR REPLACE PACKAGE BODY cust_sal AS
PROCEDURE find_sal(c_id customers.id%TYPE) IS
c_sal customers.salary%TYPE;
BEGIN
SELECT salary INTO c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line('Salary: '|| c_sal);
END find_sal;
END cust_sal;
/
NA
Page 279
Sheet1
Page 280