Oracle Notes
Oracle Notes
Data: Raw facts and figures that can be recorded (facts and statistics collected together for
reference or analysis)
Database Object: A database object is any defined object in a database that is used to store or
reference data
(Tables, views, sequences, indexes, and synonyms)
Database Table: a table is a set of data elements (values) using a model of vertical columns
and horizontal rows, the cell being the unit where a row and column intersect. A table has a
specified number of columns, but can have any number of rows.
(The primary and simplest form of data storage in a relational database)
Database User: An account through which you can log in to an Oracle database
Disadvantages:
Creating them can be a long, costly venture
Databases that are made from scratch can require huge amounts of money
Databases oftentimes require hardware and software for their startup, and these things
can also rack up big costs
Databases will be hooked up to various application programs. So, if the database is
compromised, all of those applications will subsequently suffer.
Relational Database: Dr. E.F.Codd proposed the relational model for database systems in 1970.
It is the basis for the relational database management system.
The relational model consists of:
Collection of objects or relations,
Set of operators to act on the relations
Data integrity for accuracy and consistency.
Rule 1: Information Rule: The data stored in a database, may it be user data or metadata,
must be a value of some table cell. Everything in a database must be stored in a table format.
Rule 2: Guaranteed Access Rule: Every single data element (value) is guaranteed to be
accessible logically with a combination of table-name, primary-key (row value), and attribute-
name (column value). No other means, such as pointers, can be used to access data.
Rule 3: Systematic Treatment of NULL Values: The NULL values in a database must be
given a systematic and uniform treatment. This is a very important rule because a NULL can be
interpreted as one the following data is missing, data is not known, or data is not applicable.
Rule 4: Active Online Catalog: The structure description of the entire database must be
stored in an online catalog, known as data dictionary, which can be accessed by authorized
users. Users can use the same query language to access the catalog which they use to access
the database itself.
Rule 5: Comprehensive Data Sub-Language Rule: A database can only be accessed using a
language having linear syntax that supports data definition, data manipulation, and transaction
management operations. This language can be used directly or by means of some application. If
the database allows access to data without any help of this language, then it is considered as a
violation.
Rule 6: View Updating Rule: All the views of a database, which can theoretically be updated,
must also be updatable by the system.
Rule 7: High-Level Insert, Update, and Delete Rule: A database must support high-level
insertion, updation, and deletion. This must not be limited to a single row, that is, it must also
support union, intersection and minus operations to yield sets of data records.
Rule 8: Physical Data Independence: The data stored in a database must be independent of
the applications that access the database. Any change in the physical structure of a database
must not have any impact on how the data is being accessed by external applications.
Rule 9: Logical Data Independence: The logical data in a database must be independent of
its users view (application). Any change in logical data must not affect the applications using it.
For example, if two tables are merged or one is split into two different tables, there should be no
impact or change on the user application. This is one of the most difficult rule to apply.
Rule 10: Integrity Independence: A database must be independent of the application that
uses it. All its integrity constraints can be independently modified without the need of any
change in the application. This rule makes a database independent of the front-end application
and its interface.
Rule 11: Distribution Independence: The end-user must not be able to see that the data is
distributed over various locations. Users should always get the impression that the data is
located at one site only. This rule has been regarded as the foundation of distributed database
systems.
Rule 12: Non-Subversion Rule: If a system has an interface that provides access to low-level
records, then the interface must not be able to subvert the system and bypass security and
integrity constraints.
Oracle Database is a robust object relational database that provides efficient and effective
solutions for database users such as delivering high performance, protecting users from
unauthorized access, and enabling fast failure recovery.
A database schema is a collection of metadata that describes the relationship between the data
in a database. A schema can be simply described as the "layout" of a database or the blueprint
that outlines how data is organized into tables.
Schema objects are database objects that contain data or that govern or perform operations on
data. By definition, each schema object belongs to a specific schema. The following are
commonly used schema objects:
Tables: Basic units of data storage in an Oracle database. Here, data is stored in rows and
columns. You define a table with a table name and a set of columns.
Indexes: Performance-tuning methods for allowing faster retrieval of records.
Views: Representations of SQL statements that are stored in memory so that they can be
reused.
SQL
SQL is nonprocedural language that provides database access. SQL language compiler
automatically generates a procedure to navigate the database and performs the desired task.
SQL is a limited language that allows you to directly interact with the database. You can
manipulate objects and data with SQL, but SQL doesn't include all the things that normal
programming languages have, such as loops and IFTHEN statements. That is what PL/SQL is
for. Oracle SQL provides an easy, elegant, performant architecture for accessing, defining, and
maintaining data.
Oracle SQL includes many extensions to the ANSI/ISO standard SQL language, and Oracle tools
and applications provide additional statements. The Oracle tools SQL*Plus and Oracle Enterprise
Manager let you run any ANSI/ISO standard SQL statement against an Oracle database, as well
as additional statements or functions that are available for those tools.
Although some Oracle tools and applications simplify or mask SQL use, all database operations
are performed using SQL. Any other data access method circumvents the security built into
Oracle Database and potentially compromises data security and integrity.
SQL Statement
All operations performed on the information in Oracle Database are run using SQL statements. A
statement consists of identifiers, parameters, variables, names, datatypes, and SQL reserved
words. SQL reserved words have special meaning in SQL and cannot be used for any other
purpose. For example, SELECT and UPDATE are reserved words and cannot be used as table
names. A SQL statement is a computer program or instruction. The statement must be the
equivalent of a complete SQL sentence
PL/SQL
PL/SQL is a normal programming language that includes all the features of most other
programming languages. But it has one thing that other programming languages dont have,
namely the easy ability to integrate with SQL.
Structured Query Language (SQL) is:
The ANSI standard language for operating relational databases
Efficient, easy to learn, and use
Functionally complete (With SQL, you can define, retrieve, and manipulate data in tables.)
Character Datatypes
Character datatypes store character (alphanumeric) data, which are words and free-form text.
They are less restrictive than other datatypes and consequently have fewer properties. For
example, character columns can store all alphanumeric values, but NUMBER columns can store
only numeric values. Character data is stored in strings with byte values corresponding to one of
the character sets, such as 7-bit ASCII or EBCDIC, specified when the database was created.
Oracle Database supports both single-byte and multi-byte character sets.
These datatypes are used for character data: CHAR & VARCHAR2 Datatype
CHAR Datatype
The CHAR datatype specifies a fixed-length character string. Oracle ensures that all values stored
in a CHAR column have the length specified by size. If you insert a value that is shorter than the
column length, then Oracle blank-pads the value to column length. If you try to insert a value
that is too long for the column, then Oracle returns an error. The default length for a CHAR
column is 1 byte and the maximum allowed is 2000 bytes. A 1-byte string can be inserted into a
CHAR(10) column, but the string is blank-padded to 10 bytes before it is stored.
When you create a table with a CHAR column, by default you supply the column length in bytes.
The BYTE qualifier is the same as the default. If you use the CHAR qualifier, for example CHAR(10
CHAR), then you supply the column length in characters. A character is technically a code point
of the database character set. Its size can range from 1 byte to 4 bytes, depending on the
database character set.
Fixed-length character data of length size bytes. Maximum size is 2000 bytes or characters.
Default and minimum size is 1 byte. BYTE and CHAR have the same semantics as for VARCHAR2.
VARCHAR2 Datatype
The VARCHAR2 datatype specifies a variable-length character string. When you create a
VARCHAR2 column, you supply the maximum number of bytes or characters of data that it can
hold. Oracle subsequently stores each value in the column exactly as you specify it, provided the
value does not exceed the column's maximum length of the column. If you try to insert a value
that exceeds the specified length, then Oracle returns an error.
You must specify a maximum length for a VARCHAR2 column. This maximum must be at least 1
byte, although the actual string stored is permitted to be a zero-length string (''). You can use the
CHAR qualifier, for example VARCHAR2(10 CHAR), to give the maximum length in characters
instead of bytes. A character is technically a code point of the database character set. CHAR and
BYTE qualifiers override the setting of the NLS_LENGTH_SEMANTICS parameter, which has a
default of bytes.
Variable-length character string having maximum length size bytes or characters. Maximum size
is 4000 bytes or characters, and minimum is 1 byte or 1 character. You must specify size for
VARCHAR2.
BYTE indicates that the column will have byte length semantics;
CHAR indicates that the column will have character semantics.
NUMBER Datatype
The numeric datatypes store positive and negative fixed and floating-point numbers, zero.
The NUMBER datatype stores fixed and floating-point numbers. Numbers of virtually any
magnitude can be stored and are guaranteed portable among different systems operating Oracle
Database, up to 38 digits of precision.
column_name NUMBER
column_name NUMBER (precision, scale)
If a precision is not specified, the column stores values as given. If no scale is specified, the scale
is zero.
When you specify numeric fields, it is a good idea to specify the precision and scale. This
provides extra integrity checking on input.
DATE Datatype
The DATE datatype stores point-in-time values (dates and times) in a table. The DATE datatype
stores the year (including the century), the month, the day, the hours, the minutes, and the
seconds (after midnight). Oracle Database uses its own internal format to store dates. Date data
is stored in fixed-length fields of seven bytes each, corresponding to century, year, month, day,
hour, minute, and second.
For input and output of dates, the standard Oracle date format is DD-MON-YY: '13-NOV-92'
You can change this default date format for an instance with the parameter NLS_DATE_FORMAT.
You can also change it during a user session with the ALTER SESSION statement. To enter dates
that are not in standard Oracle date format, use the TO_DATE function with a format mask:
Oracle Database stores time in 24-hour formatHH:MI:SS. By default, the time in a date field
is 00:00:00 A.M. (midnight) if no time portion is entered. In a time-only entry, the date portion
defaults to the first day of the current month. To enter the time portion of a date, use
the TO_DATE function with a format mask indicating the time portion, as in:
Keys
Key-> Each row has one or more attributes, known as key, which can identify the row in the table
uniquely. A single column or combination of multiple columns that helps uniquely identify a row
in a table.
Composite key >key, that is a combination of more than one columns (maximum up to 32
columns)
Natural Key -> key which has natural data in nature
Surrogate Key -> key which has artificial/generated data in nature
Candidate key -> key that is eligible to become a primary key
Primary key -> key which is unique, not null and helps uniquely identify a row in a table. One
table can have only one primary key. A composite key elected as primary key is known as
composite primary key
Alternate key -> Candidate keys other than primary key
Literal Values
The terms literal and constant value are synonymous and refer to a fixed data value. For
example, 'JACK', 'BLUE ISLAND', and '101' are all character literals; 5001 is a numeric literal.
Character literals are enclosed in single quotation marks so that Oracle can distinguish them
from schema object names.
Many SQL statements and functions require you to specify character and numeric literal values.
You can also specify literals as part of expressions and conditions.
Text/Character/String Literals
Use the text literal notation to specify values whenever 'string' or appears in the syntax of
expressions, conditions, SQL functions, and SQL statements in other parts of this reference. This
reference uses the terms text literal, character literal, and string interchangeably. Text, character,
and string literals are always surrounded by single quotation marks. If the syntax uses the
term char, you can specify either a text literal or another expression that resolves to character.
Text literals have properties of both the CHAR and VARCHAR2 datatypes: Within expressions and
conditions, Oracle treats text literals as though they have the datatype CHAR by comparing them
using blank-padded comparison semantics. A text literal can have a maximum length of 4000
bytes.
'Hello'
'ORACLE.dbs'
'Jackie''s raincoat'
'09-MAR-98'
Numeric Literals
Here are some valid NUMBER literals:
25
+6.34
0.5
-1
Datetime Literals
Oracle Database supports four datetime datatypes: DATE, TIMESTAMP, TIMESTAMP WITH TIME
ZONE, and TIMESTAMP WITH LOCAL TIME ZONE.
Date Literals
You can specify a DATE value as a string literal. To specify a DATE value as a literal, you must use
the Gregorian calendar. You can specify an ANSI literal, as shown:
DATE '1998-12-25'
'29-DEC-13' -> accepted as date literal
'09/06/2013' -> not accepted as date, hence it is character literal
CREATE
CREATE TABLE statement allows you to create and define a table
Syntax: CREATE TABLE <tablename> (col1 datatype null/not null, col2 datatype null/not null, ... );
Each column must have a datatype. The column should either be defined as "null" or "not null"
and if this value is left blank, the database assumes "null" as the default - also we can specify
database constraints while defining table
You can also create a table from an existing table by copying the existing table's columns.
It is important to note that when creating a table in this way, the new table will be populated
with the records from the existing table (based on the SELECT Statement)
Question: How can I create a table from another table without copying any values from the old
table?
Answer: To do this, the basic syntax is: CREATE TABLE <new_table> AS (SELECT * FROM
old_table WHERE 1=2); - here a false condition is used
ALTER
ALTER TABLE statement allows you to add, modify, drop, or rename a column from an existing
table
TRUNCATE
TRUNCATE statement is used to remove all rows from a table.
Removing rows with the TRUNCATE TABLE statement can be faster than removing all rows with
the DELETE statement, especially if the table has numerous triggers, indexes, and other
dependencies. To truncate a table, the table must be in your schema or you must have DROP
ANY TABLE system privilege.
DROP
DROP TABLE statement allows you to remove a table from the database.
Syntax: DROP TABLE <table_name>;
RENAME
RENAME statement allows you to rename an existing table in the database.
(to rename a table) Syntax: RENAME <old_name> to <new_name>;
(to rename a column) Syntax: RENAME COLUMN <old_column> to <new_column>
COMMENT
COMMENT statement allows to add to the data dictionary a comment about a table or table
column, view, or materialized view.
Syntax: COMMENT on <table> is Sample comments;
To drop comment from the database, set it to the empty string ' '.
INSERT
1 - INSERT statement allows you to insert a single record or multiple records into a table
INSERT INTO <table> (col1, col2, ... coln) VALUES (val1, val2, ... valn);
2- INSERT statement allows you to insert data using sub-SELECT
INSERT INTO <tab1>(col11, col12) SELECT col21, col22 FROM <tab2> WHERE <expr>
3 - INSERT ALL
INTO suppliers (supplier_id, supplier_name) VALUES (1000, 'IBM')
INTO suppliers (supplier_id, supplier_name) VALUES (2000, 'Microsoft')
INTO products (product_id, product_name) VALUES (1001, 'Chair')
INTO dept (deptno, dname, location) VALUES (10, 'sales','chicago') SELECT * FROM dual;
UPDATE
1 - UPDATE statement allows you to update a single record or multiple records in a table.
UPDATE <tablename> SET <column> = <expression> WHERE <condition>
2 - UPDATE on table based on values in another table is done using sub-queries and EXISTS
clause.
DELETE
DELETE statement allows you to delete a single record or multiple records from a table.
1 - DELETE FROM <table> WHERE <condition> - deletes records from table that satisfy condition
2 - DELETE FROM <table_name> - deletes all records from table
3 - DELETE can be performed on one table based on values in another table using EXISTS/IN/
NOT IN/ NOT EXISTS operator(s)
MERGE
COMMIT
The COMMIT statement makes permanent any changes made to the database during the current
transaction. A commit also makes the changes visible to other users. The COMMIT statement
releases all row and table locks, and erases any savepoints you marked since the last commit or
rollback
ROLLBACK
ROLLBACK statement is the inverse of the COMMIT statement. It undoes some or all database
changes made during the current transaction.
All savepoints marked after the savepoint to which you roll back are erased. The savepoint to
which you roll back is not erased. For example, if you mark savepoints A, B, C, and D in that
order, then roll back to savepoint B, only savepoints C and D are erased.
SAVEPOINT
SAVEPOINT statement names and marks the current point in the processing of a transaction.
With the ROLLBACK TO statement, savepoints undo parts of a transaction instead of the whole
transaction.
A simple rollback or commit erases all savepoints. When you roll back to a savepoint, any
savepoints marked after that savepoint are erased. The savepoint to which you roll back remains.
You can reuse savepoint names within a transaction. The savepoint moves from its old position to
the current point in the transaction. An implicit savepoint is marked before executing an INSERT,
UPDATE, or DELETE statement. If the statement fails, a rollback to the implicit savepoint is done.
Normally, just the failed SQL statement is rolled back, not the whole transaction
GRANT
You can grant users various privileges to tables. These privileges can be any combination of
SELECT, insert, update & delete. Below is an explanation of what each privilege means
REVOKE
Once you have granted privileges, you may need to revoke some or all of these privileges. To do
this, you can execute a revoke command. You can revoke any combination of SELECT, insert,
update and delete.
Note: You cannot take back column level privileges. Suppose you just want to take back insert
privilege on ename column then you have to first take back the whole insert privilege and then
grant privilege on empno column.
Example:
Database: ITA
Database schema1: scott (pwd: tiger) -> EMP, DEPT
Database schema2: itamerica (pwd: edison) -> BANK, PRD
Database schema3: training (school) -> SALGRADE, STUDENT, DEPT
1) As database user scott I want to access data from & insert data into table BANK from
itamerica schema
-Because scott is not owner of table BANK - it cannot be accessed
-user itamerica has to grant SELECT, insert permissions on BANK table to scott which
enables access to scott user
2) As user itamerica I want to access data from table DEPT from both scott & training schemas
connect as scott/tiger
sql> grant SELECT on dept to itamerica;
connect as training/school
sql> grant SELECT on dept to itamerica;
when you connect as itamerica/edison, you can access table dept from both scott and training
schemas
sql> SELECT * from scott.dept -- gives data from scott schema dept table
sql> SELECT * from training.dept -- gives data from training schema dept table
GRANT -> TO GRANT (insert, update, delete, SELECT) permission on own table to other
schemas/users in same database
REVOKE -> to take permission(s) off from another user in same database on own tables (when
permissions were already assigned)
Column names
Whether null values are allowed (NULL or NOT NULL) for each column
Execute the following command to view the description of the EMP table:
Database Constraints
NULL
NULL is a marker that represents missing, unknown, or inapplicable data. Null is untyped in SQL,
meaning that it is not designated as a NUMBER, CHAR, or any other specific data type. Do not
use NULL to represent a value of zero, because they are not equivalent.
SQL Constraints
SQL constraints are used to specify rules for the data in a table. If there is any violation between
the constraint and the data action, the action is aborted by the constraint.
Constraints can be specified when the table is created (inside the CREATE TABLE statement) or
after the table is created (inside the ALTER TABLE statement).
The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL
values:
The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is
created:
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following
SQL syntax:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
);
To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the
following SQL:
ALTER TABLE Persons ADD UNIQUE (P_Id);
Or
The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is
created
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on
multiple columns
Above there is only ONE PRIMARY KEY (pk_PersonID). However, the VALUE of the primary key is
made up of TWO COLUMNS (P_Id + LastName)
To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created
or
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons"
table.
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the table it points to.
The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is
created:
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already
created, use the following:
The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is
created. The CHECK constraint specifies that the column "P_Id" must only include integers
greater than 0.
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns,
use the following:
To create a CHECK constraint on the "P_Id" column when the table is already created, use the
following SQL:
ALTER TABLE Persons ADD CHECK (P_Id>0);
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns,
use the following SQL:
ALTER TABLE Persons ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Dallas')
The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is
created:
To create a DEFAULT constraint on the "City" column when the table is already created, use the
following SQL:
Table: EMP
SELECT statement
COLUMN ALIAS -> display user defined column header in the output
SELECT DEPTNO, DNAME, LOC, 'HELLO', 1000, 'NEW CLASS', '09-JAN-2017' FROM DEPT;
SELECT DEPTNO, LOC, 'HELLO' GREETING, 1000 BONUS, 'NEW CLASS' CLASS_TYPE, '09-JAN-2017'
JOINDATE FROM DEPT;
SELECT EMPNO, ENAME, SAL, 1000 ITAMERICA, '1000' ITAMERICA1 FROM EMP;
SELECT 'HELLO' GREETING, ENAME FROM EMP;
SELECT 'HELLO', ENAME FROM EMP;
SELECT EMPNO, ENAME, 'MODIFIED_SAL' "1000" FROM EMP;
SELECT ENAME SAL, SAL ENAME FROM EMP;
DUAL Table:
Dual is a dummy table that you can use to view literal values, results from functions and
calculations. This table is owned by SYS user and can be accessed by all users in the database. It
contains one column, DUMMY, and one row with value X. Dual table is used to return a value only
once.
Restricting data
Logical Operators
AND
OR
NOT
OR - TRUTH TABLE
------------------
TRUE OR TRUE =
TRUE OR FALSE =
FALSE OR FALSE =
TRUE OR NULL =
FALSE OR NULL =
Between Operator
================
Like Operator
=============
To match pattern
% (PERCENTILE) -> Represents zero or more characters
_ (UNDERSCORE)-> Represents one (any) character;
To sort data please specify ORDER BY column_name| column_alias | column order in SELECT list
FUNCTIONS
1. UPPER
Converts all letters in the specified string to uppercase. If there are characters in the string that
are not letters, they are unaffected by this function.
Usage: UPPER( string1 )
string1 is the string to convert to uppercase.
eg: UPPER('Oracle Char functions'); would return 'ORACLE CHAR FUNCTIONS';
UPPER('hello oracle'); would return 'HELLO ORACLE'
2. LOWER
Converts all letters in the specified string to lowercase. If there are characters in the string that
are not letters, they are unaffected by this function.
Usage: LOWER( string1 )
string1 is the string to convert to lowercase.
eg: LOWER('IT America'); would return 'it america';
LOWER('RHYTHM OF LIFE '); would return 'rhythm of life '
SELECT EMPNO, ENAME, LOWER(ENAME) LNAME FROM EMP;
DROP TABLE DEPT1;
DROP TABLE DEPT101;
CREATE TABLE DEPT101 AS SELECT * FROM DEPT;
SELECT * FROM DEPT101;
INSERT INTO DEPT101 VALUES(50,'FINANCE','Dallas');
SELECT * FROM DEPT101;
SELECT * FROM DEPT101 WHERE LOC = 'DALLAS';
SELECT * FROM DEPT101 WHERE UPPER(LOC) = 'DALLAS';
SELECT * FROM DEPT101 WHERE LOWER(LOC) = 'dallas';
3. INITCAP
Sets the first character in each word to uppercase and the rest to lowercase.
Usage: INITCAP( string1 )
string1 is the string argument whose first character in each word will be converted to uppercase
and all remaining characters converted to lowercase.
eg: INITCAP('rhythm of life'); would return 'Rhythm Of Life';
INITCAP('IT AMERICA'); would return 'It America'
4. ASCII
5. CHR
7. LENGTHB
Returns the number of bytes in char (use for double-byte char sets)
8. LTRIM
string1 is the string to trim the characters from the left-hand side.
trim_string is the string that will be removed from the left-hand side of string1. If this parameter
is omitted, the ltrim function will remove all leading spaces from string1.
eg: ltrim(' abcd'); would return 'abcd'; ltrim(' abcd', ' '); would return abcd'
ltrim('000123', '0'); would return '123'
ltrim('123123abcd', '123'); would return 'abcd'
ltrim('123123abcd123', '123'); would return 'abcd123'
ltrim('xyxzyyyabcd', 'xyz'); would return 'abcd'
ltrim('6372Tech', '0123456789'); would return 'Tech'
The ltrim function may appear to remove patterns, but this is not the case as demonstrated in
the following example.
The ltrim function can also be used to remove all leading numbers as demonstrated in the next
example.
ltrim( '6372Tech', '0123456789'); would return 'Tech'
In this example, every number combination from 0 to 9 has been listed in the trim_string
parameter. By doing this, it does not matter the order that the numbers appear in string1, all
leading numbers will be removed by the ltrim function.
9. RTRIM
10. TRIM
removes all specified characters either from the beginning or the ending of a string.
Usage: RTRIM( [ leading | trailing | both [ trim_character ] ] string1 )
leading - remove trim_string from the front of string1.
trailing - remove trim_string from the end of string1.
both - remove trim_string from the front and end of string1.
If none of these are chosen (ie: leading, trailing, both), the trim function will remove trim_string
from both the front and end of string1.
trim_character is the character that will be removed from string1. If this parameter is omitted,
the trim function will remove all leading and trailing spaces from string1.
string1 is the string to trim.
eg:
TRIM (' test ') would return 'test'
TRIM (' ' from ' test ') would return 'test'
TRIM (leading '0' from '000123') would return '123'
TRIM (trailing '1' from 'Test1') would return 'Test'
TRIM (both '1' from '123Test111') would return '23Test'
11. CONCAT
12. REPLACE
13. TRANSLATE
replaces a sequence of characters in a string with another set of characters. However, it replaces
a single character at a time. For example, it will replace the 1st character in the string_to_replace
with the 1st character in the replacement_string. Then it will replace the 2nd character in the
string_to_replace with the 2nd character in the replacement_string, and so on.
14. INSTR
SELECT instr('Our new office is near to train station','o',1) as pos from dual;
SELECT instr('Our new office is near to train station','new',1) as pos from dual;
SELECT instr('Our new office is near to train station','r',2) as pos from dual;
SELECT instr('Our new office is near to train station','r',4) as pos from dual;
SELECT instr('Our new office is near to train station','f',1,2) as pos from dual;
SELECT instr('Our new office is near to train station','i',-1) as pos from dual;
SELECT instr('Our new office is near to train station','i',-2,4) as pos from dual;
SELECT instr('Our new office is near to train station','z',1) as pos from dual;
SELECT instr('Our new office is near to train station','new',-1,2) as pos from dual;
15. SUBSTR
SELECT ENAME,
SUBSTR(ENAME,1,LENGTH(ENAME)/2) FNAME
,SUBSTR(ENAME,(LENGTH(ENAME)/2)+1) LNAME
FROM EMP;
SELECT ENAME,
CONCAT(
UPPER(SUBSTR(ENAME,1,LENGTH(ENAME)/2))
,LOWER(SUBSTR(ENAME,(LENGTH(ENAME)/2)+1))
) NEWNAME
FROM EMP;
16. LPAD
Pads the left-side of a string with a specific set of characters (when string1 is not null).
Usage: LPAD( string1, padded_length, [ pad_string ] )
string1 is the string to pad characters to (the left-hand side).
padded_length is the number of characters to return. If the padded_length is smaller than the
original string, the lpad function will truncate the string to the size of padded_length.
pad_string is optional. This is the string that will be padded to the left-hand side of string1. If this
parameter is omitted, the LPAD function will pad spaces to the left-side of string1.
eg: LPAD('abcd', 7) would return ' abcd';
LPAD('abcd', 2) would return 'ab';
LPAD('abcd', 8, '0') would return '0000abcd';
LPAD('abcd', 4, 'z') would return 'abcd';
17. RPAD
Pads the right-side of a string with a specific set of characters (when string1 is not null)
Usage: RPAD( string1, padded_length, [ pad_string ] )
string1 is the string to pad characters to (the right-hand side).
padded_length is the number of characters to return. If the padded_length is smaller than the
original string, the rpad function will truncate the string to the size of padded_length.
pad_string is optional. This is the string that will be padded to the right-hand side of string1. If
this parameter is omitted, the RPAD function will pad spaces to the right-side of string1.
eg: RPAD('abcd', 7); would return 'abcd '
RPAD('abcd', 2); would return 'ab'
RPAD('abcd', 8, '0'); would return 'abcd0000'
RPAD('abcd', 4, 'z'); would return 'abcd'
18. DECODE
in decode function
3 parameters -> e,s,r
4 -> e,s,r,d
5-> e,s1,r1,s2,r2
6 -> e,s1,r1,s2,r2,d
19. GREATEST
20. LEAST
21. CEIL
Returns the smallest integer value that is greater than or equal to a number
eg: CEIL(32.65) would return 33;
CEIL(32) would return 32;
CEIL(-32.65) would return -32;
CEIL(-32) would return -32
22. FLOOR
Returns the largest integer value that is equal to or less than a number
eg: FLOOR(5.9) would return 5;
FLOOR(34.29) would return 34;
FLOOR(-5.9) would return -6
23. TRUNC
24. ROUND
25. MOD
if empno is odd then display ename in uppercase, if even diplay ename in lower case
SELECT EMPNO, DECODE( MOD(EMPNO,2),1,UPPER(ENAME),0,LOWER(ENAME)) NEWNAME
FROM EMP;
Display first half of the ename in uppercase and second half in lowercase as newname
SELECT ENAME,
CONCAT(
UPPER(SUBSTR(ENAME,1,LENGTH(ENAME)/2))
,LOWER(SUBSTR(ENAME,1+LENGTH(ENAME)/2))
) NEWNAME FROM EMP;
26. ABS
27. SIGN
28. SQRT
Returns m raised to the nth power ( m is the base, n is the exponent; If m is negative, then n
must be an integer)
Usage: POWER( m, n )
eg: POWER(3, 2) would return 9;
POWER(5, 3) would return 125;
POWER(-5, 3) would return -125;
POWER(6.2, 3) would return 238.328;
30. NVL
NVL function lets you substitute a value when a null value is encountered. Can be used for
substituting any datatype value
Usage: NVL( string1, replace_with )
string1 is the string to test for a null value; replace_with is the value returned if string1 is null.
31. NVL2
NVL2 function extends the functionality found in the NVL function. It lets you substitute a value
when a null value is encountered as well as when a non-null value is encountered.
32. COALESCE
Returns the first non-null expression in the list. If all expressions evaluate to null, then the
coalesce function will return null. Coalesce function takes any number of parameters.
Usage: COALESCE(expr1, expr2, expr3) -> returns first non-null
33. NULLIF
NULLIF compares two expressions and returns null if they are equal, or the first expression if they
are not equal
34. REVERSE
REVERSE is Oracle string function, which returns the input string in its reverse order.
35. SYSDATE
SYSDATE is a date function that returns the current database server date and time. You can use
SYSDATE just as you would use any other column name
36. SYSTIMESTAMP
systimestamp function returns the current system date and time (including fractional seconds
and time zone). Current system denotes the system where database is installed.
Select systimestamp from dual;
37. CURRENT_DATE
current_date function returns the current date (in the time zone of the current SQL session)
Usage: SELECT CURRENT_DATE FROM DUAL;
38. CURRENT_TIMESTAMP
returns the current date and time in the time zone of the current SQL session. It returns a
TIMESTAMP WITH TIME ZONE value.
Usage: SELECT CURRENT_TIMESTAMP FROM DUAL;
39. LOCALTIMESTAMP
returns the current date and time in the time zone of the current SQL session. It returns a
TIMESTAMP value.
Usage: SELECT LOCALTIMESTAMP FROM DUAL;
40. TO_DATE
format_mask
dd - date - 01 - 31
dy - short name for day - wed
day - day of the week - wednesday
mm - 2 digit month - 02
mon - short name for month - feb
month - month name - february
yyyy - 4 digit year - 2011
yy - 2 digit year - 11
year - year in words - twenty eleven
w - week of the month - 01 to 05
ww - week of the year - 01 to 53
42. TO_NUMBER
to_number( string1)
string1 is the string that will be converted to a number.
Make sure string1 has all digits
SELECT '120.39' SALE_AMOUNT, TO_NUMBER('120.39') NEWSALEAMT FROM DUAL;
FORMAT MASK
43. LAST_DAY
the last_day function returns the last day of the month based on a date value.
last_day( date )
date is the date value to use to calculate the last day of the month
44. NEXT_DAY
47. ADD_MONTHS
48. MONTHS_BETWEEN
months_between function returns the number of months between date1 and date2.
Usage: months_between( date1, date2 )
date1 and date2 are the dates used to calculate the number of months.
If a fractional month is calculated, the months_between function calculates the fraction based on
a 31-day month.
50. NEW_TIME
The following new_time example converts an Eastern Standard Time into a Pacific Standard Time:
new_time (to_date ('2003/11/01 11:45', 'yyyy/mm/dd HH24:MI'), 'EST', 'PST')
This example would return '2003/11/01 08:45:00'.
CASE expressions let you use IF ... THEN ... ELSE logic in SQL statements without having to
invoke procedures
Simple CASE Expression
In a simple CASE expression, Oracle Database searches for the first WHEN ... THEN pair for
which expr is equal to comparison_expr and returns return_expr. If none of
the WHEN ... THEN pairs meet this condition, and an ELSE clause exists, then Oracle
returns else_expr. Otherwise, Oracle returns null. You cannot specify the literal NULL for
every return_expr and the else_expr.
In a searched CASE expression, Oracle searches from left to right until it finds an occurrence
of condition that is true, and then returns return_expr. If no condition is found to be true, and
an ELSE clause exists, Oracle returns else_expr. Otherwise, Oracle returns null.
Oracle Database uses short-circuit evaluation. That is, for a simple CASE expression, the
database evaluates each comparison_expr value only before comparing it to expr, rather than
evaluating all comparison_expr values before comparing any of them with expr. Consequently,
Oracle never evaluates a comparison_expr if a previous comparison_expr is equal to expr. For a
searched CASE expression, the database evaluates each condition to determine whether it is
true, and never evaluates a condition if the previous condition was true.
For both simple and searched CASE expressions, all of the return_exprs must either have the
same datatype or must all have a numeric datatype. If all return expressions have a numeric
datatype, then Oracle determines the argument with the highest numeric precedence, implicitly
converts the remaining arguments to that datatype, and returns that datatype.
The maximum number of arguments in a CASE expression is 255. All expressions count toward
this limit, including the initial expression of a simple CASE expression and the
optional ELSE expression. Each WHEN ... THEN pair counts as two arguments. To avoid exceeding
this limit, you can nest CASE expressions so that the return_expr itself is a CASE expression
SELECT ENAME,DEPTNO,SAL,
(CASE WHEN DEPTNO>=30 AND SAL=2000 THEN 'HELLO'
WHEN DEPTNO=20 THEN 'WELCOME'
WHEN ENAME!='KING' THEN 'PRESIDENT'
END) REMARKS
FROM EMP;
Set operators combine the results of two component queries into a single result. Queries
containing set operators are called compound queries
MINUS - returns all distinct rows selected by the first query but not the second
INTERSECT - returns all distinct rows selected by both queries
UNION - returns all distinct rows selected by either query
UNION ALL - returns all rows selected by either query, including all duplicates
You can combine multiple queries using the set operators UNION, UNION ALL, INTERSECT,
and MINUS. All set operators have equal precedence. If a SQL statement contains multiple set
operators, then Oracle Database evaluates them from the left to right unless parentheses
explicitly specify another order.
The corresponding expressions in the select lists of the component queries of a compound query
must match in number and must be in the same datatype group (such as numeric or character).
In queries using set operators, Oracle does not perform implicit conversion across datatype
groups. Therefore, if the corresponding expressions of component queries resolve to both
character data and numeric data, Oracle returns an error.
Aggregate/Group Functions
Aggregate functions return a single result row based on groups of rows, rather than on single
rows. Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They
are commonly used with the GROUP BY clause in a SELECT statement, where Oracle Database
divides the rows of a queried table or view into groups. In a query containing a GROUP BY clause,
the elements of the select list can be aggregate functions, GROUP BYexpressions, constants, or
expressions involving one of these. Oracle applies the aggregate functions to each group of rows
and returns a single result row for each group.
If you omit the GROUP BY clause, then Oracle applies aggregate functions in the select list to all
the rows in the queried table or view. You use aggregate functions in the HAVING clause to
eliminate groups from the output based on the results of the aggregate functions, rather than on
the values of the individual rows of the queried table or view.
51. MIN
This is a group function and takes all the rows related to a group and returns a single value as
output.
52. MAX
This is a group function and takes all the rows related to a group and returns a single value as
output.
53. AVG
Returns the average of a column of numbers. An average is obtained by adding all of the values
in a set and then dividing by the number of values in the set. Avg function takes only one
parameter.
54. COUNT
You can use the DISTINCT clause within the COUNT function
eg: count(distinct deptno) -> displays number of unique values in deptno column
55. SUM
SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO HAVING COUNT(*)<5 ORDER BY 1;
select deptno, sum(sal) from emp group by deptno having count(*)>3;
SELECT DEPTNO, COUNT(*) FROM EMP WHERE DEPTNO IN (10,20) GROUP BY DEPTNO; --I
SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO HAVING DEPTNO IN (10,20); --II
Display two rows (1 row with sum of positive numbers, 1 row with sum of negative numbers) in
the output
SELECT SUM(AMT) FROM SAMPLE WHERE AMT>0 UNION SELECT SUM(AMT) FROM SAMPLE
WHERE AMT<0;
A GROUPING SETS expression allows you to selectively specify the set of groups that you want to
create within a GROUP BY clause.
GROUPING SETS specifies multiple groupings of data in one query. Only the specified groups are
aggregated, instead of the full set of aggregations that are generated
by CUBE or ROLLUP. GROUPING SETS can contain a single element or a list of
elements. GROUPING SETS can specify groupings equivalent to those returned
by ROLLUP or CUBE.
Note that multiple grouping sets are supported against named states, but are not supported
against the corpus.
For example:
GROUP BY GROUPING SETS(a, (b), (c, d), ())
Keep in mind that the use of () to specify an empty group means that the following are all
equivalent:
GROUP = GROUP BY() = GROUP BY GROUPING SETS(())
ROLLUP
ROLLUP enables a SELECT statement to calculate multiple levels of subtotals across a specified
group of dimensions. It also calculates a grand total. ROLLUP is a simple extension to
the GROUP BY clause, so its syntax is extremely easy to use. The ROLLUP extension is highly
efficient, adding minimal overhead to a query.
Syntax
ROLLUP appears in the GROUP BY clause in a SELECT statement. Its form is:
SELECT ... GROUP BY
ROLLUP(grouping_column_reference_list)
Details
ROLLUP's action is straightforward: it creates subtotals which "roll up" from the most detailed
level to a grand total, following a grouping list specified in the ROLLUP clause. ROLLUP takes as
its argument an ordered list of grouping columns. First, it calculates the standard aggregate
values specified in the GROUP BY clause. Then, it creates progressively higher-level subtotals,
moving from right to left through the list of grouping columns. Finally, it creates a grand total.
ROLLUP will create subtotals at n+1 levels, where n is the number of grouping columns. For
instance, if a query specifies ROLLUP on grouping columns of Time, Region, and Department
( n=3), the result set will include rows at four aggregation levels.
Example
This example of ROLLUP uses the data in the video store database.
SELECT Time, Region, Department, sum(Profit) AS Profit FROM sales GROUP BY ROLLUP(Time,
Region, Dept)
CUBE
CUBE enables a SELECT statement to calculate subtotals for all possible combinations of a group
of dimensions. It also calculates a grand total. This is the set of information typically needed for
all cross-tabular reports, so CUBE can calculate a cross-tabular report with a
single SELECT statement. Like ROLLUP, CUBE is a simple extension to the GROUP BY clause, and
its syntax is also easy to learn.
Syntax
CUBE appears in the GROUP BY clause in a SELECT statement. Its form is:
SELECT ... GROUP BY
CUBE (grouping_column_reference_list)
Details
CUBE takes a specified set of grouping columns and creates subtotals for all possible
combinations of them. In terms of multi-dimensional analysis, CUBE generates all the subtotals
that could be calculated for a data cube with the specified dimensions. If you have
specified CUBE(Time, Region, Department), the result set will include all the values that would be
included in an equivalent ROLLUP statement plus additional combinations. If there are n columns
specified for a CUBE, there will be 2n combinations of subtotals returned.
Example
This example of CUBE uses the data in the video store database.
SELECT Time, Region, Department, sum(Profit) AS Profit FROM sales GROUP BY CUBE (Time,
Region, Dept);
select deptno, job, count(*) from emp group by grouping sets ((deptno),(job));
Analytical Functions
56. ROW_NUMBER
By nesting a subquery using ROW_NUMBER inside a query that retrieves the ROW_NUMBER
values for a specified range, you can find a precise subset of rows from the results of the inner
query. This use of the function lets you implement top-N, bottom-N, and inner-N reporting. For
consistent results, the query must ensure a deterministic sort order.
SELECT deptno, ename, empno, ROW_NUMBER() OVER (PARTITION BY deptno ORDER BY empno)
AS empid FROM emp;
57. RANK
RANK function returns the rank of a value in a group of values. The rank function can cause non-
consecutive rankings if the tested values are the same.
The rank function can be used two ways - as an Aggregate function or as an Analytic function.
select rank(2850) within group (order by sal desc) gr from emp; -> displays rank of 2850 in emp
table when ordered by sal in descending order
58. DENSE_RANK
the dense_rank function returns the rank of a row in a group of rows. It is very similar to the rank
function. However, the rank function can cause non-consecutive rankings if the tested values are
the same. Whereas, the dense_rank function will always result in consecutive rankings
above query displays dense_rank starting with 1 in each department - based on employee's
salary starting highest
59. LAG
The LAG analytic function gives access to multiple rows within a table, without the need for a
self-join. The LAG function is used to access data from a previous row
Select ename, sal, lag(sal) over (order by sal) lg_sal from emp order by 2;
displays all 14 rows from emp table in ascending order of sal and displays lg_sal column value as
sal from previous row - and displays null where offset is outside the scope
select ename, sal, lag(sal,1,0) over (order by sal) lg_sal from emp order by 2; -> similar to above
except it displays 0 in place of null in lg_sal column
60. LEAD
The LEAD analytic function gives access to multiple rows within a table, without the need for a
self-join. The LEAD function is used to access data from a following row
Select ename, sal, lead(sal) over (order by sal) ld_sal from emp order by 2;
displays all 14 rows from emp table in ascending order of sal and displays ld_sal column value as
sal from following row - and displays null where offset is outside the scope
select ename, sal, lead(sal,1,0) over (order by sal) ld_sal from emp order by 2; -> similar to
above except it displays 0 in place of null in ld_sal column
SELECT ENAME, DEPTNO, SUM(SAL) OVER (PARTITION BY DEPTNO), SUM(SAL) OVER () FROM
EMP;
SELECT DISTINCT DEPTNO, SUM(SAL) OVER (PARTITION BY DEPTNO), SUM(SAL) OVER () FROM
EMP;
SELECT ENAME, DEPTNO, SAL, RANK() OVER (ORDER BY SAL DESC) RK FROM EMP;
SELECT ENAME, DEPTNO, SAL, RANK() OVER (ORDER BY SAL DESC) RK FROM EMP;
Sub Queries
SELECT EMPNO, ENAME, (SELECT * FROM DEPT) AMOUNT FROM EMP WHERE DEPTNO=10;
SELECT EMPNO, ENAME, (SELECT DEPTNO FROM DEPT) AMOUNT FROM EMP WHERE DEPTNO=10;
SELECT EMPNO, ENAME, (SELECT dname FROM DEPT where deptno=40) AMOUNT
FROM EMP WHERE DEPTNO=10;
SELECT EMPNO, ENAME, (SELECT SYSDATE FROM DUAL) SQ FROM EMP WHERE DEPTNO=10;
SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=20;
WITH ABC AS (SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=20)
SELECT * FROM ABC;
WITH ABC AS (SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=20)
SELECT ENAME,DEPTNO FROM ABC;
WITH ABC AS (SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=20)
SELECT ENAME,SAL FROM ABC;
WITH ABC AS (SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=20)
SELECT ENAME,SALARY FROM ABC;
WITH ABC AS (SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=20)
SELECT ENAME,SAL FROM ABC WHERE COMM IS NULL;
SELECT ENAME, JOB, SAL, DEPTNO, (SELECT DNAME FROM DEPT WHERE DEPTNO=10) DNAME
FROM EMP;
SELECT ENAME, JOB, SAL, DEPTNO, (SELECT DNAME FROM DEPT WHERE DEPTNO=10) DNAME
FROM EMP
WHERE DEPTNO=10;
SELECT ENAME, SAL, DEPTNO, (SELECT DNAME FROM DEPT WHERE DEPTNO=10) DNAME FROM
EMP
WHERE SAL < (SELECT SAL FROM EMP WHERE ENAME='MILLER');
SELECT ENAME, SAL, DEPTNO, (SELECT DNAME FROM DEPT WHERE DEPTNO=10) DNAME FROM
EMP
WHERE SAL < (SELECT SAL FROM EMP WHERE DEPTNO = 20);
SELECT ENAME, SAL, DEPTNO, (SELECT DNAME FROM DEPT WHERE DEPTNO=20) DNAME
FROM EMP
WHERE SAL IN (SELECT SAL FROM EMP WHERE DEPTNO = 10);
TO DEAL WITH MULTIPLE ROW SUB QUERIES IN WHERE CLAUSE- WE NEED TO USE ANY OF THE
BELOW OPERATORS
IN
NOT IN
=ANY, >ANY, <ANY, >=ANY, <=ANY
>ALL, >=ALL, <ALL, <=ALL
TO DEAL WITH SINGLE ROW SUB QUERIES IN WHERE CLAUSE WE CAN USE BELOW
=, >, <, >=, <=, !=
SELECT ENAME, SAL, DEPTNO, (SELECT DNAME FROM DEPT WHERE DEPTNO=10) DNAME FROM
EMP
WHERE DEPTNO < (SELECT JOB FROM EMP WHERE ENAME='JONES');
SELECT ENAME, SAL, DEPTNO, (SELECT DNAME FROM DEPT WHERE DEPTNO=10) DNAME FROM
EMP
WHERE DEPTNO < (SELECT SAL FROM EMP WHERE ENAME='JONES');
EXISTS
NOT EXISTS;
PSEUDO COLUMNS
A pseudo column behaves like a table column, but is not actually stored in the table. You can
select from pseudo columns, but you cannot insert, update, or delete their values. Pseudo
columns typically return a different value for each row.
For each row in the database, the ROWID pseudocolumn returns the address of the row. Oracle
Database rowid values contain information necessary to locate a row. Usually, a rowid value
uniquely identifies a row in the database. However, rows in different tables that are stored
together in the same cluster can have the same rowid.
They can show you how the rows in a table are stored.
You should not use ROWID as the primary key of a table. If you delete and reinsert a row then its
rowid may change. If you delete a row, then Oracle may reassign its rowid to a new row inserted
later. Although you can use the ROWID pseudo column in the SELECT and WHERE clause of a
query, these pseudo column values are not actually stored in the database. You cannot insert,
update, or delete a value of the ROWID pseudo column.
ROWNUM Pseudo column
For each row returned by a query, the ROWNUM pseudo column returns a number indicating the
order in which Oracle selects the row from a table or set of joined rows. The first row selected has
a ROWNUM of 1, the second has 2, and so on.
You can use ROWNUM to limit the number of rows returned by a query, as in this example:
If an ORDER BY clause follows ROWNUM in the same query, then the rows will be reordered by
the ORDER BY clause. The results can vary depending on the way the rows are accessed. If you
embed the ORDER BY clause in a subquery and place the ROWNUM condition in the top-level
query, then you can force the ROWNUM condition to be applied after the ordering of the rows.
The following query returns the employees with the 10 smallest employee numbers. This is
sometimes referred to as top-N reporting:
SELECT * FROM (SELECT * FROM EMP ORDER BY EMPNO) WHERE ROWNUM < 11;
In the preceding example, the ROWNUM values are those of the top-level SELECT statement, so
they are generated after the rows have already been ordered by employee_id in the subquery.
Conditions testing for ROWNUM values greater than a positive integer are always false. For
example, this query returns no rows:
The first row fetched is assigned a ROWNUM of 1 and makes the condition false. The second row
to be fetched is now the first row and is also assigned a ROWNUM of 1 and makes the condition
false. All rows subsequently fail to satisfy the condition, so no rows are returned.
You can also use ROWNUM to assign unique values to each row of a table, as in this example:
UPDATE my_table SET column1 = ROWNUM;
for every qualified row - oracle assigns rownum (starts with 1 and increments by 1)
SELECT EMPNO, ENAME, SAL, DEPTNO, ROWNUM FROM EMP WHERE DEPTNO=10;
SELECT EMPNO, ENAME, SAL, DEPTNO, ROWNUM FROM EMP WHERE DEPTNO=10 ORDER BY SAL
DESC;
WHERE DEPTNO=10;
SELECT * FROM
(SELECT ENAME, ROWNUM RN FROM EMP WHERE ROWNUM<=7 ORDER BY ROWNUM DESC)
WHERE ROWNUM<=2;
(SELECT ENAME, ROWNUM RN FROM EMP WHERE ROWNUM<=7 ORDER BY ROWNUM DESC)
WHERE RN>=6;
WHERE RN=4;
MINUS
WHERE R=256;
SELECT * FROM
WHERE R=2;
(SELECT EMPNO, ENAME, JOB, SAL, DEPTNO, ROWNUM R FROM EMP ORDER BY ROWNUM DESC)
WHERE ROWNUM<=2;
MINUS
WHERE ROWNUM<=3;
) WHERE R=3;
(SELECT SAL, DENSE_RANK() OVER (ORDER BY SAL DESC) DRK FROM EMP)
WHERE DRK=3;
SELECT DEPTNO, DNAME, LOC FROM DEPT1 GROUP BY DEPTNO, DNAME, LOC;
SELECT DEPTNO, DNAME, LOC FROM DEPT1 GROUP BY DEPTNO, DNAME, LOC HAVING
COUNT(*)>1;
SELECT DEPTNO, DNAME, LOC FROM DEPT1 GROUP BY DEPTNO, DNAME, LOC HAVING
COUNT(*)=1;
('AAAXJQAAGAAAAG0AAA','AAAXJQAAGAAAAG0AAC','AAAXJQAAGAAAAG0AAD'
,'AAAXJQAAGAAAAG0AAE','AAAXJQAAGAAAAG0AAF','AAAXJQAAGAAAAG0AAG'
);
FROM DEPT1
SELECT MIN(ROWID)
FROM DEPT1
SQL*Loader Features
SQL*Loader loads data from external files into tables of an Oracle database. It has a powerful
data parsing engine that puts little limitation on the format of the data in the datafile. You can
use SQL*Loader to do the following:
Load data across a network. This means that you can run the SQL*Loader client on a
different system from the one that is running the SQL*Loader server.
Load data from multiple datafiles during the same load session.
Load data into multiple tables during the same load session.
Specify the character set of the data.
Selectively load data (you can load records based on the records' values).
Manipulate the data before loading it, using SQL functions.
Generate unique sequential key values in specified columns.
Use the operating system's file system to access the datafiles.
Load data from disk, tape, or named pipe.
Generate sophisticated error reports, which greatly aid troubleshooting.
A typical SQL*Loader session takes as input a control file, which controls the behavior of
SQL*Loader, and one or more datafiles. The output of SQL*Loader is an Oracle database (where
the data is loaded), a log file, a bad file, and potentially, a discard file.
The control file is a text file written in a language that SQL*Loader understands. The control file
tells SQL*Loader where to find the data, how to parse and interpret the data, where to insert the
data, and more.
Discarded and Rejected Records
Records read from the input file might not be inserted into the database. Such records are placed
in either a bad file or a discard file.
The bad file contains records that were rejected, either by SQL*Loader or by the Oracle database.
If you do not specify a bad file and there are rejected records, then SQL*Loader automatically
creates one. It will have the same name as the data file, with a.bad extension.
SQL*Loader Rejects
Datafile records are rejected by SQL*Loader when the input format is invalid. For example, if the
second enclosure delimiter is missing, or if a delimited field exceeds its maximum length,
SQL*Loader rejects the record. Rejected records are placed in the bad file.
After a datafile record is accepted for processing by SQL*Loader, it is sent to the Oracle database
for insertion into a table as a row. If the Oracle database determines that the row is valid, then
the row is inserted into the table. If the row is determined to be invalid, then the record is
rejected and SQL*Loader puts it in the bad file. The row may be invalid, for example, because a
key is not unique, because a required field is null, or because the field contains invalid data for
the Oracle datatype.
As SQL*Loader executes, it may create a file called the discard file. This file is created only when
it is needed, and only if you have specified that a discard file should be enabled. The discard file
contains records that were filtered out of the load because they did not match any record-
selection criteria specified in the control file.
The discard file therefore contains records that were not inserted into any table in the database.
You can specify the maximum number of such records that the discard file can accept. Data
written to any database table is not written to the discard file.
Invoking SQL*Loader
When you invoke SQL*Loader, you can specify certain parameters to establish session
characteristics. Parameters can be entered in any order, optionally separated by commas. You
specify values for parameters, or in some cases, you can accept the default without entering a
value.
For example:
Command-Line Parameters
This section describes each SQL*Loader command-line parameter. The defaults and maximum
values listed for these parameters are for UNIX-based systems. They may be different on your
operating system.
BAD specifies the name of the bad file created by SQL*Loader to store records that cause errors
during insert or that are improperly formatted. If you do not specify a filename, the default is
used. A bad file is not automatically created if there are no rejected records.
A bad file filename specified on the command line becomes the bad file associated with the
first INFILE statement in the control file. If the bad file filename was also specified in the control
file, the command-line value overrides it.
CONTROL (control file)
Default: none
CONTROL specifies the name of the SQL*Loader control file that describes how to load the data.
If a file extension or file type is not specified, it defaults to .ctl. If the filename is omitted,
SQL*Loader prompts you for it.
DISCARD (filename)
DISCARD specifies a discard file (optional) to be created by SQL*Loader to store records that are
neither inserted into a table nor rejected.
A discard file filename specified on the command line becomes the discard file associated with
the first INFILE statement in the control file. If the discard file filename is specified also in the
control file, the command-line value overrides it.
LOG specifies the log file that SQL*Loader will create to store logging information about the
loading process.
SKIP specifies the number of logical records from the beginning of the file that should not be
loaded.
USERID (username/password)
Default: none
USERID is used to provide your Oracle username/password. If it is omitted, you are prompted for
it. If only a slash is used, USERID defaults to your operating system login.
Control File Contents
The SQL*Loader control file is a text file that contains data definition language (DDL) instructions.
DDL is used to control the following aspects of a SQL*Loader session:
To create the SQL*Loader control file, use a text editor such as notepad, vi editor
In general, the control file has three main sections, in the following order:
Sessionwide information
LOAD DATA
INFILE 'C:\LOAD\student.txt'
TRUNCATE INTO TABLE SCHOOL
FIELDS TERMINATED BY ";"
(
SID
,SNAME
,SCORE
)
File->Save
File name: process.ctl
Save as type: all files
Step 4:
Loading of data is completed -please go and check in the table. If all records are not loaded
please check log file - if you have any errors - please open bad file, which is created with rejected
records
skip=1 -> skips first record (to skip the header record)
userid=scott/tiger -> to specify the schemaname and password
If you want to apply small transformations like converting source data into upper case and load -
you can use below
61. LISTAGG
For a specified measure, LISTAGG orders data within each group specified in the ORDER BY
clause and then concatenates the values of the measure column separated by comma or any
specified character like (, ; |:)
As a single-set aggregate function, LISTAGG operates on all rows and returns a single output row.
As a group-set aggregate, the function operates on and returns an output row for each group
defined by the GROUP BY clause.
As an analytic function, LISTAGG partitions the query result set into groups based on one or more
expression in the query_partition_clause.
62. WIDTH_BUCKET
WIDTH_BUCKET lets you construct equiwidth histograms, in which the histogram range is divided
into intervals that have identical size.
For a given expression, WIDTH_BUCKET returns the bucket number into which the value of this
expression would fall after being evaluated.
HIERARCHICAL QUERIES
====================
RELATIVES
ID,NAME,PARENT_ID,LOC
START PREPARING DATA FROM YOUR GRANDFATHER
10, SCOTT, NULL, CA
101,FORD,10,DELHI
102,SMITH,10,MUMBAI
103,BLAKE,10
104,TURNER
105,MARTIN
SELECT DEPTNO, LISTAGG(ENAME,';') WITHIN GROUP (ORDER BY ENAME) PTH FROM EMP GROUP
BY DEPTNO;
COMMENTS
========
SELECT
EMPNO
/*,ENAME
,JOB
,SAL
,DEPTNO*/
FROM EMP;
JOINS
=====
------
SELECT * FROM EMP, SALGRADE
WHERE EMP.SAL BETWEEN SALGRADE.LOSAL AND SALGRADE.HISAL;
T1 T2
C1 C2 C3 C4
1 A 1 X
2 B 1 P
3 C 3 Z
4 R
SELECT C1,C2,C3,C4 FROM T1, T2;
SELECT C1,C2,C3,C4 FROM T1 INNER JOIN T2 ON T1.C1=T2.C3;
SELECT C1,C2,C3,C4 FROM T1 LEFT OUTER JOIN T2 ON T1.C1=T2.C3;
SELECT C1,C2,C3,C4 FROM T1 RIGHT OUTER JOIN T2 ON T1.C1=T2.C3;
SELECT C1,C2,C3,C4 FROM T1 FULL OUTER JOIN T2 ON T1.C1=T2.C3;
SELECT D.DNAME, COUNT(*) FROM DEPT D LEFT OUTER JOIN EMP E ON D.DEPTNO=E.DEPTNO
GROUP BY D.DNAME;
SELECT D.DNAME, E.ENAME FROM DEPT D LEFT OUTER JOIN EMP E ON D.DEPTNO=E.DEPTNO;
SELECT EMP.ENAME,DEPTNO,DNAME
FROM EMP JOIN DEPT USING (DEPTNO)
JOIN EMP1 USING (DEPTNO);
DATABASE LINK
ABC
SCOTT (EMP, DEPT, SALGRADE, PRODUCT)
HR (CUSTOMER)
XYZ
ITA (PRODUCT, PRODUCT)
SYSTEM (SALES, ITEM,DIM_COUNTRY )
LOGIN TO SCOTT@ABC -> YOU CAN ACCESS ONLY EMP, DEPT, SALGRADE, PRODUCT