0% found this document useful (0 votes)
188 views90 pages

Oracle Notes

The document provides an introduction to databases, including key concepts such as data, database objects, attributes, rows, tables, metadata, data dictionaries, database users, schemas, and benefits and disadvantages of databases. It discusses relational databases and Dr. E.F. Codd's 12 rules for relational database management systems (RDBMS). It also summarizes Oracle databases, SQL, PL/SQL, SQL statements, and Oracle SQL data types including character datatypes.

Uploaded by

Milan Koirala
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
188 views90 pages

Oracle Notes

The document provides an introduction to databases, including key concepts such as data, database objects, attributes, rows, tables, metadata, data dictionaries, database users, schemas, and benefits and disadvantages of databases. It discusses relational databases and Dr. E.F. Codd's 12 rules for relational database management systems (RDBMS). It also summarizes Oracle databases, SQL, PL/SQL, SQL statements, and Oracle SQL data types including character datatypes.

Uploaded by

Milan Koirala
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 90

INTRODUCTION Database

Data: Raw facts and figures that can be recorded (facts and statistics collected together for
reference or analysis)

Database: A database is defined as a collection of related information (logical collection of


relevant data)

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)

Attribute: an attribute is a characteristic

Row: a set of attribute values

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)

Metadata: Metadata is data that describes other data

Data Dictionary: Repository of metadata is usually called a data dictionary.

Database User: An account through which you can log in to an Oracle database

Database Schema: 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.

Benefits of Database approach:


Redundancy can be reduced
Inconsistency can be avoided
Data can be shared
Standards can be enforced
Security restrictions can be applied
Integrity can be maintained

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.

DBMS Dr.E.F.Codds 12 Rules

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.

Relational database management system (RDBMS): is a database management


system that is based on the relational model as introduced by E.F.Codd.
About Oracle Database

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.)

- SQL statements are not case sensitive, unless indicated.


- SQL statements can be entered on one or many lines
- Keywords cannot be split across lines or abbreviated
- Clauses are usually placed on separate lines for readability and ease of editing
- Indents should be used to make code more readable
- Keywords typically are entered in uppercase; all other words, such as table names and columns,
are entered in lowercase

Oracle SQL Data types:

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.

CHAR [(size [BYTE | CHAR])]

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.

VARCHAR2(size [BYTE | CHAR])

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.

The following numbers can be stored in a NUMBER column:

Positive numbers in the range 1x10-130 to 9.99...9x10125 with up to 38 significant digits


Negative numbers from -1x10-130 to 9.99...99x10125 with up to 38 significant digits
Zero

For numeric columns, you can specify the column as below:

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.

Input Data Specified As Stored As


7,456,123.89 NUMBER 7456123.89
7,456,123.89 NUMBER(*,1) 7456123.9
7,456,123.89 NUMBER(9) 7456124
7,456,123.89 NUMBER(9,2) 7456123.89
7,456,123.89 NUMBER(9,1) 7456123.9
7,456,123.89 NUMBER(6) (not accepted, exceeds precision)
7,456,123.89 NUMBER(7,-2) 7456100

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:

TO_DATE ('November 13, 1992', 'MONTH DD, YYYY')

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:

INSERT INTO birthdays (bname, bday) VALUES ('ANDY',TO_DATE('13-AUG-66 12:56 A.M.','DD-


MON-YY HH:MI A.M.'));

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.

Here are some valid text literals:

'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

SQL Sub Languages


1) Data Definition Language (DDL)
2) Data Manipulation Language (DML)
3) Transaction Control Language (TCL)
4) Data Control Language (DCL)

DDL (Data Definition Language) STATEMENTS

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)

1- Copying all columns from another table


2- Copying SELECTed columns from another table
3- Copying SELECTed columns from multiple tables

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

1- To add a column to an existing table:


ALTER TABLE <table_name> ADD <column_name column-definition>
2- To add multiple columns to an existing table:
ALTER TABLE <table_name> ADD ( col1 coldef, col2 coldef, ... coln col_def)
3- To modify a column in an existing table:
ALTER TABLE <table_name> MODIFY col_name col_type
4- To modify multiple columns in an existing table:
ALTER TABLE <table_name> MODIFY (col1 type, col2 type, ... coln type)
5- To drop a column in an existing table:
ALTER TABLE <table_name> DROP COLUMN column_name
6- To rename a column in an existing table:
ALTER TABLE <table_name> RENAME COLUMN <old_name> to <new_name>
7- The basic syntax for renaming a table is:
ALTER TABLE <table_name> RENAME TO <new_table_name>

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.

TRUNCATE TABLE <tablename>;

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 ' '.

DML (Data Manipulation Language) STATEMENTS

SELECT (SELECT is also known as Data Retrieval Statement)


SELECT statement allows you to retrieve records from one or more tables in your database.

1 - To retrieve all columns from a table:


SELECT * FROM <table_name> (* signifies that we wish to view all fields from table)
2 - To retrieve individual fields in the table:
SELECT col1, col2 from <table_name>
3 - To retrieve filtered rows in the table:
SELECT col1, col2 from <table_name> where <condition>
4 - To retrieve fields from multiple tables:
SELECT tab1.col, tab2.col FROM <tab1>, <tab2> WHERE tab1.join_col = tab2.join_col

Projection: columns that are returned by a query


SELECTion: rows that are returned by a query
Joining: bring data from multiple tables by specifying link between them

SELECT [distinct/all] column/expression [alias] FROM table;

DISTINCT -> supresses duplicates


ALL -> displays all values
alias -> gives SELECTed columns different headings
; -> statement terminator

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

MERGE (sometimes referred to as "UPSERT") is a DML statement that enables us to optionally


update or insert data into a target table, depending on whether matching records already exist.

MERGE INTO <target_table> t USING <source_table> s


ON ( s.obj_id = t.obj_id )
WHEN MATCHED THEN
UPDATE SET t.obj_name = s.obj_name, t.obj_type = s.obj_type
WHEN NOT MATCHED THEN
INSERT (t.obj_id, t.obj_name, t.obj_type) VALUES (s.obj_id, s.obj_name, s.obj_type );

TCL (Transaction Control Language) STATEMENTS

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

Until your changes are committed:


- You can see the changes when you query the tables you modified, but other users cannot see
the changes.
- If you change your mind or need to correct a mistake, you can use the ROLLBACK statement to
roll back (undo) the changes

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

DCL (Data Control Language) STATEMENTS

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

SELECT - Ability to query the table with a SELECT statement.


Insert - Ability to add new rows to the table with the insert statement.
Update - Ability to update rows in the table with the update statement.
Delete - Ability to delete rows from the table with the delete statement.

1 GRANT SELECT, update, insert on EMP to XYZ;


to grant SELECT,update,insert privilege on EMP table to other user XYZ.
2 - GRANT all on EMP to XYZ;
to grant all privileges on EMP table to XYZ
3 - GRANT SELECT on EMP to public;
to grant SELECT privilege on EMP to all other users of the database
4 - GRANT update (ename),insert (empno, ename) on EMP to XYZ;
to grant update on ename column only and insert on empno and ename columns only
5 - GRANT SELECT on EMP to XYZ WITH GRANT OPTION;
To grant SELECT privilege on EMP table to XYZ and to make XYZ be able further pass on
this privilege

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.

1 - revoke SELECT, update, insert on EMP from XYZ;


to revoke SELECT, update, insert privilege you have granted to XYZ
2 - revoke SELECT on EMP from public;
To revoke SELECT statement on EMP granted to public
3 - revoke update, insert on EMP from XYZ;
To revoke update privilege on ename column and insert privilege on empno and ename
columns

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

Login to database as user itamerica with password edison


sql> connect itamerica/edison
sql> grant SELECT, insert on BANK to scott;
sql> connect scott/tiger
sql> SELECT * from itamerica.BANK;

insert into itamerica.bank values(2,'bank of america');


SELECT * from itamerica.bank;
commit;

GRANT SELECT, INSERT ON BANK TO SCOTT;


REVOKE INSERT ON BANK FROM SCOTT;

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)

WITH GRANT OPTION:


USER itamerica/edison
sql> GRANT SELECT,INSERT ON BANK to scott WITH GRANT OPTION;
now database use scott has with grant option granted so user scott can grant SELECT, insert
permissions on itamerica.bank to other users in same database

DIFFERENCE BETWEEN TRUNCATE, DELETE & DROP STATEMENTS

TRUNCATE DELETE DROP


DDL DML DDL
ROLLBACK CAN BE NO ROLLBACK
NO ROLLBACK PERFORMED
NO CONDITION CAN BE CONDITION CAN BE NO CONDITION CAN BE
SPECIFIED SPECIFIED SPECIFIED
FAST SLOW FAST
TRIGGER CANNOT BE FIRED TRIGGER CAN BE FIRED TRIGGER CANNOT BE FIRED
TCL NOT REQUIRED TCL REQUIRED TCL NOT REQUIRED
REDO LOGS NOT GENERATED REDO LOGS GENERATED REDO LOGS NOT GENERATED
REMOVES DATASPACE AND REMOVES ONLY REMOVES INDEXES AND
INDEXSPACE DATASPACE PRIVILEGES
DESCRIBE Command
The DESCRIBE command provides a description of a specified table or view. The description for
tables and views contains the following information:

Column names

Whether null values are allowed (NULL or NOT NULL) for each column

Data type of columns, such as DATE, NUMBER, VARCHAR2

Precision of columns, such as VARCHAR2(50)

Syntax: DESC [RIBE] <table>

Execute the following command to view the description of the EMP table:

DESCRIBE EMP; or DESC EMP;

Database Constraints

Column level constraints Vs. Table level constraints


A column level constraint has scope only to the column it is defined on. A table level constraint
can see every column in the table. That is the major difference between the two - that of
"scoping". Any column level constraint (exception: not null) can be expressed at the table level -
but the opposite is not true. A column level constraint is syntactically clearer - it is OBVIOUS it
applies to that single column. It is more meaningful therefore. You would use a column level
constraint if your constraint is in fact a column constraint. You would use a table constraint
otherwise.

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).

In SQL, we have the following constraints:


NOT NULL - Indicates that a column cannot store NULL value
UNIQUE - Ensures that each row for a column must have a unique value
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or
combination of two or more columns) have a unique identity which helps to find a particular
record in a table more easily and quickly
FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in
another table
CHECK - Ensures that the value in a column meets a specific condition
DEFAULT - Specifies a default value for a column
SQL NOT NULL Constraint
By default, a table column can hold NULL values.
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.

The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL
values:

CREATE TABLE PersonsNotNull


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

SQL UNIQUE Constraint


The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and
PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of
columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint
per table

The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is
created:

CREATE TABLE Persons


(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

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

ALTER TABLE Persons ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName);

To drop a UNIQUE constraint

ALTER TABLE Persons DROP CONSTRAINT uc_PersonID;

SQL PRIMARY KEY Constraint


The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys
must contain UNIQUE values. A primary key column cannot contain NULL values. Most tables
should have a primary key, and each table can have only ONE primary key.

The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is
created

CREATE TABLE Persons


(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on
multiple columns

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
);

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

ALTER TABLE Persons ADD PRIMARY KEY (P_Id);

or

ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName);

To drop a PRIMARY KEY constraint


ALTER TABLE Persons DROP CONSTRAINT pk_PersonID;

SQL FOREIGN KEY Constraint


A FOREIGN KEY in one table points to a PRIMARY KEY in a same table or another table.
The "Persons" table:

P_Id LastNam FirstNam Address City


e e

1 Matthew James 23 Main Minneapolis


Street

2 Oscar Robert 18 Park Ave New York

3 Porter Richard 100 Fort Drive Dallas

The "Orders" table:

O_Id OrderNo P_Id

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:

CREATE TABLE Orders


(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
);

CREATE TABLE Orders


(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
);

To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already
created, use the following:

ALTER TABLE Orders ADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id);

To DROP a FOREIGN KEY Constraint

ALTER TABLE Orders DROP CONSTRAINT fk_PerOrders;

FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)


Do not allow deleting parent record when child record found
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) ON DELETE CASCADE
when deleting parent record - delete all corresponding child records
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) ON DELETE SET NULL
when deleting parent record - set child record value as null

SQL CHECK Constraint


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.

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.

CREATE TABLE Persons


(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns,
use the following:

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=Dallas)
);

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')

To DROP a CHECK Constraint

ALTER TABLE Persons DROP CONSTRAINT chk_Person;

SQL DEFAULT Constraint


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 following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is
created:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT Dallas
);

To create a DEFAULT constraint on the "City" column when the table is already created, use the
following SQL:

ALTER TABLE Persons MODIFY City DEFAULT Dallas;

To DROP a DEFAULT Constraint

ALTER TABLE Persons ALTER COLUMN City DROP DEFAULT;

Development Environments for SQL


There are two development environments for this course:
The primary tool is Oracle SQL Developer.
SQL Command Line interface can also be used
Other: TOAD for Oracle

To display current user


SQL> show user;

To display list of users from database

SELECT * from dba_users;


SELECT * from all_users;
SELECT * from user_users;

To display list of tables from current user / database


SELECT owner, table_name FROM dba_tables;
SELECT owner, table_name FROM all_tables;
SELECT table_name FROM user_tables;
SELECT * from TAB;

Sample tables used in our course

Table: EMP

EMP ENAM MG HIREDAT SA DEPTN


NO E JOB R E L COMM O
790 17-Dec-
7369 SMITH CLERK 2 80 800 20
SALESM 769 160
7499 ALLEN AN 8 20-Feb-81 0 300 30
SALESM 769 125
7521 WARD AN 8 22-Feb-81 0 500 30
MANAGE 783 297
7566 JONES R 9 2-Apr-81 5 20
MARTI SALESM 769 28-Sep- 125
7654 N AN 8 81 0 1400 30
MANAGE 783 285
7698 BLAKE R 9 1-May-81 0 30
MANAGE 783 245
7782 CLARK R 9 9-Jun-81 0 10
756 300
7788 SCOTT ANALYST 6 9-Dec-82 0 20
PRESIDE 17-Nov- 500
7839 KING NT 81 0 10
TURN SALESM 769 150
7844 ER AN 8 8-Sep-81 0 0 30
ADAM 778 110
7876 S CLERK 8 12-Jan-83 0 20
769
7900 JAMES CLERK 8 3-Dec-81 950 30
756 300
7902 FORD ANALYST 6 3-Dec-81 0 20
7934 MILLE CLERK 778 23-Jan-82 130 10
R 2 0

Table: DEPT Table: SALGRADE


GRAD LOSA HISA
DEPTN DNAME LOC
E L L
O
1 700 1200
ACCOUNTIN NEW
2 1201 1400
10 G YORK
3 1401 2000
20 RESEARCH DALLAS
4 2001 3000
30 SALES CHICAGO
5 3001 9999
OPERATION BOSTON
40 S

SELECT statement

SELECT DEPTNO, DNAME, LOC FROM DEPT;


SELECT DNAME, LOC FROM DEPT;
SELECT DNAME, LOC, DEPTNO FROM DEPT;
SELECT DNAME FROM DEPT;
SELECT DNAME, EMPNO FROM DEPT;
SELECT DNAME, HELLO FROM DEPT;
SELECT * FROM DEPT;
SELECT EMPNO, SAL FROM EMP;
SELECT * FROM EMP;

DISTINCT -> suppresses duplicate rows in the output

SELECT * FROM EMP;


SELECT EMPNO FROM EMP;
SELECT DEPTNO FROM EMP;
SELECT DISTINCT DEPTNO FROM EMP;
SELECT DISTINCT JOB FROM EMP;
SELECT DISTINCT MGR FROM EMP;
SELECT * FROM EMP;
SELECT DISTINCT COMM FROM EMP;
SELECT DISTINCT EMPNO FROM EMP;
SELECT DEPTNO, JOB FROM EMP;
SELECT DISTINCT DEPTNO, JOB FROM EMP;
SELECT JOB, MGR FROM EMP;
SELECT DISTINCT JOB, MGR FROM EMP;
SELECT DISTINCT * FROM EMP;

COLUMN ALIAS -> display user defined column header in the output

SELECT * FROM EMP;


SELECT ENAME, SAL, SAL*12 FROM EMP;
SELECT ENAME, SAL, SAL*12 AS ANNUAL FROM EMP;
SELECT ENAME, SAL, SAL*12 AS annualsalary FROM EMP;
SELECT ENAME, SAL, SAL*12 AS ANNUAL_SALARY FROM EMP;
SELECT ENAME, SAL, SAL*12 AS "annual salary" FROM EMP;
SELECT ENAME, SAL, SAL*12 AS "ANNUAL SALARY" FROM EMP;

SELECT EMPNO, ENAME, SAL, SAL+1000 MODIFIED_SAL FROM EMP;


SELECT EMPNO, ENAME, SAL, SAL+1000 MODIFIED_SAL, 1000 ITAMERICA FROM EMP;
SELECT 1000 ITAMERICA FROM EMP;
SELECT 1000 ITAMERICA FROM DEPT;

SELECT * FROM DEPT;

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 'HELLO' GREETING, 1000 BONUS FROM DEPT;


SELECT DISTINCT 'HELLO' GREETING, 1000 BONUS 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.

SELECT 100+3 FROM EMP;


SELECT 1000*3 FROM EMP;
SELECT 56*95 FROM EMP;
SELECT 567*195 FROM DEPT;
SELECT 567*195 CALC FROM DUAL;

SELECT * FROM DUAL;


SELECT 'Welcome' FROM DUAL;
SELECT 'Welcome' FROM DEPT;
SELECT 'Welcome' Greeting FROM DUAL;
SELECT 538*764 FROM DUAL;
SELECT 1000 sal FROM DUAL;
SELECT 1000 FROM DUAL;
SELECT 'abc' FROM DUAL;

Concatenation Operator (||)

SELECT * FROM EMP;


SELECT ENAME||JOB FROM EMP;
SELECT ENAME||JOB NEWDATA FROM EMP;
SELECT ENAME||' '||JOB FROM EMP;
SELECT ENAME||' is working as '||job DESCRIPTION FROM EMP;
SELECT 'ENAME'||JOB description FROM EMP;
SELECT ENO||JOB description FROM EMP;

SELECT 'Happy Father's Day' greeting FROM DUAL;


SELECT 'Happy Father''s Day' greeting FROM DUAL;

SELECT 'welcome to oracle sql' FROM DUAL;

q (quote) operator - q'[ ]'

SELECT q'[welcome to father's day]' FROM DUAL;


SELECT q'[welcome to father's day]' FROM DUAL;

SELECT 'Welcome' Msg FROM DUAL;

Relational Operators (<, <=, >, >=, !=, <>)


Arithmetic Operators (+, -, *, /)
Comparison Operator (=)
Logical Operators (And, Or, NOT)
IN, Between, LIKE, ANY, ALL

Restricting data

SELECT * FROM EMP;


SELECT * FROM EMP WHERE DEPTNO=10;
SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP WHERE SAL>3000;
SELECT EMPNO, ENAME, MGR, DEPTNO FROM EMP WHERE SAL=3000;
SELECT ENAME, MGR, DEPTNO FROM EMP WHERE SAL>=3000;
SELECT ENAME, MGR, DEPTNO FROM EMP WHERE SAL<3000;
SELECT ENAME, SAL, COMM, DEPTNO FROM EMP WHERE SAL<2000;
SELECT * FROM EMP;
SELECT ENAME, SAL, COMM, DEPTNO FROM EMP WHERE COMM<2000;
SELECT ENAME, SAL, COMM, SAL+COMM TOTSAL, DEPTNO FROM EMP WHERE SAL<2000;
SELECT * FROM EMP WHERE COMM = NULL;
SELECT * FROM EMP WHERE COMM IS NULL;
SELECT * FROM EMP WHERE COMM IS NOT NULL;
SELECT * FROM EMP WHERE NOT COMM IS NULL;
SELECT * FROM DEPT;
SELECT * FROM DEPT WHERE DEPTNO!=10;
SELECT * FROM DEPT WHERE DEPTNO<>10;
SELECT * FROM DEPT WHERE DEPTNO>20;
SELECT * FROM DEPT WHERE DEPTNO>=30;
SELECT * FROM EMP;
SELECT * FROM EMP WHERE JOB IN (CLERK,MANAGER);
SELECT * FROM EMP WHERE JOB IN ('CLERK','MANAGER');
SELECT * FROM EMP;
SELECT * FROM EMP WHERE JOB='manager';

SELECT * FROM EMP WHERE JOB='MANAGER';

Logical Operators

AND
OR
NOT

SELECT * FROM EMP WHERE DEPTNO=20 AND SAL <1400;


SELECT * FROM EMP WHERE DEPTNO=20 AND DEPTNO=10;
SELECT * FROM EMP WHERE DEPTNO=20 AND DEPTNO!=10;

SELECT * FROM EMP;


SELECT * FROM EMP WHERE DEPTNO = 20 AND COMM IS NULL;
SELECT * FROM EMP WHERE DEPTNO=30 AND COMM IS NOT NULL;
SELECT * FROM EMP WHERE SAL>3000 OR COMM IS NOT NULL;
SELECT * FROM EMP WHERE DEPTNO = 10 OR DEPTNO!=30;
SELECT * FROM EMP WHERE SAL=1250 OR DEPTNO = 10 OR COMM IS NOT NULL;

Expression: can be a single condition or more than one conditions


where job='MANAGER' -> is one condition -> if this is true - then expression is true
when you have more than one conditions in an expression... we need to logically combine the
outputs and evaluate..

SELECT * from emp where (deptno,sal)in ((10,5000),(20,3000),(30,2850));

*Evaluate Non-null expression first

AND - TRUTH TABLE


------------------
TRUE AND TRUE =
TRUE AND FALSE =
FALSE AND FALSE =
TRUE AND NULL =
FALSE AND NULL =

OR - TRUTH TABLE
------------------

TRUE OR TRUE =
TRUE OR FALSE =
FALSE OR FALSE =
TRUE OR NULL =
FALSE OR NULL =

SELECT * FROM EMP WHERE JOB= 'MANAGER' OR JOB='SALESMAN';


SELECT * FROM EMP WHERE JOB IN ('MANAGER','SALESMAN');
SELECT * FROM EMP WHERE JOB =ANY ('MANAGER','SALESMAN');

SELECT * FROM EMP WHERE JOB NOT IN ('MANAGER','SALESMAN');


SELECT * FROM EMP WHERE JOB!='MANAGER' AND JOB!='SALESMAN';
SELECT * FROM EMP WHERE JOB != ALL ('MANAGER','SALESMAN');

Between Operator
================

SELECT * FROM EMP;


SELECT * FROM EMP WHERE SAL>=850 AND SAL<=1200;
SELECT * FROM EMP WHERE SAL BETWEEN 2450 AND 3000;
SELECT * FROM EMP WHERE SAL BETWEEN 3000 AND 5000;
SELECT * FROM EMP WHERE SAL BETWEEN 5000 AND 3000; --
SELECT * FROM EMP WHERE SAL NOT BETWEEN 3000 AND 5000;
SELECT * FROM EMP WHERE SAL NOT BETWEEN 5000 AND 3000; --
SELECT * FROM EMP WHERE SAL<3000 OR SAL>5000;
SELECT * FROM EMP;
SELECT * FROM EMP WHERE HIREDATE BETWEEN '30-JUN-1980' AND '30-JUN-1981';
SELECT * FROM EMP WHERE ENAME BETWEEN 'A' AND 'K';

Like Operator
=============
To match pattern
% (PERCENTILE) -> Represents zero or more characters
_ (UNDERSCORE)-> Represents one (any) character;

SELECT * FROM EMP;


SELECT * FROM EMP WHERE ENAME LIKE '%S';
SELECT * FROM EMP WHERE ENAME LIKE '_A%';
SELECT * FROM EMP WHERE ENAME LIKE '%M%';
SELECT * FROM EMP WHERE JOB LIKE 'S%';
SELECT * FROM EMP WHERE JOB = 'K%';
SELECT * FROM EMP WHERE JOB = 'M%';

Sorting Data (Order by)


===================

To sort data please specify ORDER BY column_name| column_alias | column order in SELECT list

SELECT * FROM EMP;


SELECT * FROM EMP WHERE DEPTNO=10 ORDER BY ENAME;
SELECT * FROM EMP WHERE DEPTNO=20 ORDER BY ENAME;
SELECT * FROM EMP ORDER BY ENAME;
SELECT * FROM EMP ORDER BY JOB;
SELECT * FROM EMP ORDER BY JOB, ENAME;
SELECT * FROM EMP ORDER BY MGR;
SELECT * FROM EMP ORDER BY MGR NULLS FIRST;
SELECT * FROM EMP ORDER BY DEPTNO, JOB, ENAME;
SELECT * FROM EMP WHERE DEPTNO=20 ORDER BY MGR, JOB, ENAME;

SELECT * FROM EMP ORDER BY ENAME DESC;


SELECT * FROM EMP ORDER BY SAL DESC;
SELECT * FROM EMP ORDER BY COMM;
SELECT * FROM EMP ORDER BY COMM DESC;
SELECT * FROM EMP ORDER BY COMM DESC NULLS LAST;
SELECT * FROM EMP ORDER BY JOB, ENAME DESC;
SELECT * FROM EMP ORDER BY JOB DESC, ENAME DESC;
SELECT EMPNO, JOB, ENAME, MGR, SAL FROM EMP ORDER BY 3;
SELECT EMPNO, JOB, ENAME, MGR, SAL FROM EMP ORDER BY 2,1;
SELECT ENAME, EMPNO, SAL, SAL*12 YEARLYSAL FROM EMP ORDER BY 4;
SELECT ENAME, EMPNO, SAL, SAL*-12 YEARLYSAL FROM EMP ORDER BY 4 DESC;
SELECT ENAME, EMPNO, SAL, SAL*-12 YEARLYSAL FROM EMP ORDER BY 4;
SELECT EMPNO, SAL, SAL*12 YEARLYSAL FROM EMP ORDER BY YEARLYSAL;
SELECT EMPNO, ENAME, MGR, SAL FROM EMP ORDER BY JOB,2;
SELECT ENAME, EMPNO FROM EMP ORDER BY JOB DESC, ENAME;
SELECT * FROM EMP;

FUNCTIONS

Functions are used to customize/modify output

PRE (SYSTEM) DEFINED FUNCTIONS


SINGLE ROW FUNCTIONS
GROUP FUNCTIONS
ANALYTICAL FUNCTIONS
USER DEFINED FUNCTIONS

SINGLE ROW FUNCTIONS: Returns one result per row


MULTIPLE ROW FUNCTIONS: Returns one result per set of rows

Character Functions: That modify character value


Conversion Functions: converts from one data type to another
Number functions: that work on numeric data
Date functions: working with date values

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'

SELECT 'Welcome to IT America' GREETING FROM DUAL;


SELECT UPPER('Welcome to IT America') GREETING FROM DUAL;
SELECT UPPER('ename') FROM EMP;
SELECT EMPNO, ENAME, UPPER(ENAME) FROM EMP;
SELECT EMPNO, UPPER(SAL) FROM EMP;
SELECT UPPER(200) FROM DUAL;

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'

SELECT initcap(ename) from emp;


SELECT initcap('Welcome to iT america') Greeting from dual;

4. ASCII

returns the NUMBER code that represents the specified character.


Usage: ascii( single_character )
single_character is the specified character to retrieve the NUMBER code for. If more than one
character is entered, the function will return the value for the first character and ignore all of the
characters after the first.
eg: ascii('t') would return 116; ascii('T') would return 84; ascii('T2') would also return 84.

SELECT ascii('A') from dual;


SELECT ascii('a') from dual;
SELECT ascii('B') from dual;
SELECT ascii('AB') from dual;

5. CHR

It returns the character based on the NUMBER code.


Usage: chr( number_code )
number_code is the NUMBER code used to retrieve the character.
eg: chr(116); would return 't'; chr(84); would return 'T'

SELECT chr(65) from dual;


SELECT chr(32) from dual;
SELECT chr(44) from dual;
SELECT chr(9) from dual;

SELECT 'a'||chr(32)||'a' from dual;


SELECT 'a'||chr(44)||'a' from dual;
6. LENGTH

returns the length of the specified string.


Usage: length( string1 )
string1 is the string to return the length for. If string1 is NULL, then the function returns NULL.

eg: length(NULL) would return NULL;


length('') would return NULL.
length('Sample text') would return 11.
length('Sample text ') would return 12.

SELECT length('hello') from dual;


SELECT empno, ename, length(ename) from emp;

7. LENGTHB

Returns the number of bytes in char (use for double-byte char sets)

SELECT lengthb('hello') from dual;


SELECT length(' Yellow') from dual;
SELECT lengthb(' Yellow') from dual;
SELECT lengthb(' Yellow') from dual;
SELECT length(' lo') from dual;
SELECT lengthb(' lo') from dual;

8. LTRIM

removes all specified characters from the left-hand side of a string.


Usage: LTRIM(string1, [ trim_string ] )

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.

ltrim('xyxzyyyTech', 'xyz'); would return 'Tech'


It actually removes the individual occurrences of 'x', 'y', and 'z', as opposed to the pattern of
'xyz'.

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.

SELECT LENGTH(' IT AMERICA') FROM DUAL;

SELECT ' IT AMERICA', LTRIM(' IT AMERICA') FROM DUAL;


SELECT LTRIM('AAAAAIT AMERICA','A') SAMPLE FROM DUAL;
SELECT LTRIM('XYZXYZIT AMERICA','XYZ') FROM DUAL;
SELECT LTRIM('XYZXZYIT AMERICA','XYZ') FROM DUAL;
SELECT LTRIM('ZZZZZIT AMERICA','XYZ') FROM DUAL;

9. RTRIM

Removes all specified characters from the right-hand side of a string


Usage: RTRIM( string1, [ trim_string ] )
string1 is the string to trim the characters from the right-hand side.
trim_string is the string that will be removed from the right-hand side of string1. If this parameter
is omitted, the rtrim function will remove all trailing spaces from string1.

eg: RTRIM('abcd '); would return 'abcd'


RTRIM('abcd ', ' '); would return 'abcd'
RTRIM('123000', '0'); would return '123'
RTRIM('abcd123123', '123'); would return 'abcd'
RTRIM('123abcd123', '123'); would return '123abcd'
RTRIM('abcdxyxzyyy', 'xyz'); would return 'abcd'
RTRIM('abcd6372', '0123456789'); would return 'abcd'

SELECT RTRIM('XYZIT AMERICAXYZXYZ','XYZ') FROM DUAL;


SELECT RTRIM('XZYIT AMERICAXYZXYZ','XYZ') FROM DUAL;
SELECT RTRIM('xyzIT AMERICAXYzXY','XYZ') FROM DUAL;

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'

SELECT TRIM(' IT AMERICA ') ABC FROM DUAL;


SELECT TRIM('AAAAAIT AMERICA','A') FROM DUAL; --incorrect
SELECT RTRIM (LTRIM ('AAAAAIT AMERICA','A'),'A') abc from dual;

SELECT TRIM(both 'A' from 'AIT AMERICA') abc FROM DUAL;


SELECT TRIM(trailing 'A' from 'AIT AMERICA') abc FROM DUAL;
SELECT TRIM(leading 'A' from 'AIT AMERICA') abc FROM DUAL;

11. CONCAT

Allows you to concatenate two strings together.


Usage: CONCAT( string1, string2 )
string1 is the first string to concatenate.
string2 is the second string to concatenate.
eg: CONCAT('IT', ' America'); would return 'IT America';
CONCAT('a', 'b') would return 'ab'.

SELECT CONCAT(ENAME,JOB) FROM EMP;


SELECT CONCAT(CONCAT(ENAME,JOB),DEPTNO) FROM EMP;

12. REPLACE

Replaces a sequence of characters in a string with another set of characters.


Usage: REPLACE( string1, string_to_replace, [ replacement_string ] )
string1 is the string to replace a sequence of characters with another set of characters.
string_to_replace is the string that will be searched for in string1.
replacement_string is optional. All occurrences of string_to_replace will be replaced with
replacement_string in string1. If the replacement_string parameter is omitted, the replace
function simply removes all occurrences of string_to_replace, and returns the resulting string.
eg: REPLACE('123123abcd', '123'); would return 'abcd';
REPLACE('123abcd123', '123'); would return 'abcd';
REPLACE('222abcd', '2', '3'); would return '333abcd';
REPLACE('0000123', '0'); would return '123';
REPLACE('0000123', '0', ' '); would return ' 123';

SELECT REPLACE('it america','I','J') FROM DUAL;


SELECT REPLACE('it america','i','J') FROM DUAL;
SELECT REPLACE('it america','i','bc') FROM DUAL;
SELECT REPLACE('it america','ia','bc') FROM DUAL;
SELECT REPLACE('it america','i') FROM DUAL;

DROP table tab1;


CREATE table tab1
(
id number(4),
description varchar2(50)
);

insert into tab1 values(1,'welcome to oracle sql');


insert into tab1 values(2,'united states');
insert into tab1 values(3,'this is the rhythm of life');
insert into tab1 values(4,'edison');
insert into tab1 values(5,'air conditioner is not working');
commit;
SELECT * from tab1;

display 3 columns in the output


id, description, number of words in column description

update tab1 set description=' united states' where id=2;


SELECT * from tab1;

display 3 columns in the output


id, description, number of words in column description

SELECT replace('allen','n','m') from dual;


SELECT replace('america','a','e') from dual;
SELECT replace('america','am','en') from dual;

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.

Usage: translate( string1, string_to_replace, replacement_string )


string1 is the string to replace a sequence of characters with another set of characters.
string_to_replace is the string that will be searched for in string1.
replacement_string - All characters in the string_to_replace will be replaced with the
corresponding character in the replacement_string.
eg: translate('1test23', '123', '456'); would return '4test56'; translate('222test', '2es', '3il'); would
return '333tilt'

SELECT translate('america','am','en') from dual;


SELECT translate('america','a','bc') from dual;
SELECT translate('america','ja','j') from dual;
SELECT translate('america','a',' ') abc from dual;
SELECT translate('america','a','') from dual;
SELECT translate('america','a') from dual;
SELECT translate('america','am','b') from dual;
SELECT translate('it america','i','J') FROM DUAL;
SELECT translate('it america','ia','bc') FROM DUAL;
SELECT translate('it america','i','bc') FROM DUAL;
SELECT translate('it america','iam','bc') FROM DUAL;
SELECT translate('it america','iam',' bc') FROM DUAL;

14. INSTR

returns the location of a substring in a string.


Usage: instr( string1, string2 [, start_position [, nth_appearance ] ] )
string1 is the string to search.
string2 is the substring to search for in string1.
start_position is the position in string1 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
function counts back start_position number of characters from the end of string1 and then
searches towards the beginning of string1.
nth_appearance is the nth appearance of string2. This is optional. If omitted, it defaults to 1.
- If string2 is not found in string1, then the instr Oracle function will return 0.
eg: instr('This is sample text', 'i') would return 3; 1st occurrence of 'i';
instr('This is sample text', 'i', 1, 2) would return 6; 2nd occurrence of 'i' starting from 1st position;
instr('This is sample text', 'i', 4, 1) would return 6; 1st occurrence of 'i' starting from 4th position;
instr('This is sample text', 'e', -1, 2) would return 14; 2nd occurance of 'e' from reverse order
starting from 1st position from end;

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;

drop table strdemo;


create table strdemo(id number, description varchar2(200));
insert into strdemo values (1,'Our new office is near to train station');
insert into strdemo values (2,'Laptop you bought is not new and I need other laptop');
commit;
SELECT * from strdemo;

Display 3 columns in the output


1) ID
2) Description
3) POS -> position of string 'new' in column description

SELECT id, description, instr(description,'new',1) POS from strdemo;

please display 3 columns in the output


1) ID
2) Description
3) POS -> position of "second word's start point" from column description

SELECT id, description, instr(description,' ',1)+1 POS from strdemo;

please display 3 columns in the output


1) ID
2) Description
3) POS -> position of "3rd word's start point" from column description

SELECT id, description, instr(description,' ',1,2)+1 POS from strdemo;

please display 3 columns in the output


1) ID
2) Description
3) POS -> position of "last word's start point" from column description

SELECT id, description, instr(description,' ',-1)+1 POS from strdemo;

15. SUBSTR

allows you to extract a substring from a string.


Usage: substr( string, start_position, [ length ] )
string is the source string.
start_position is the position for extraction. The first position in the string is always 1.
length is optional. It is the number of characters to extract. If this parameter is omitted, substr
will return the entire string.
Note:
- If start_position is 0, then substr treats start_position as 1 (ie: the first position in the string).
- If start_position is a positive number, then substr starts from the beginning of the string.
- If start_position is a negative number, then substr starts from the end of the string and counts
backwards.
- If length is a negative number, then substr will return a NULL value.
eg: substr('This is a test', 6, 2) would return 'is'
substr('This is a test', 6) would return 'is a test'
substr('ThisIsATest', 1, 4) would return 'This'
substr('ThisIsATest', -3, 3) would return 'est'
substr('ThisIsATest', -6, 3) would return 'sAT'
substr('ThisIsATest', -8, 2) would return 'sI'

SELECT substr('IT AMERICA',2) from dual;


SELECT substr('IT AMERICA',5) from dual;
SELECT substr('IT AMERICA',4,2) from dual;
SELECT ename, substr(ename,4) from emp;
SELECT ename, substr(ename,2) from emp;
SELECT ename, substr(ename,2,2) from emp;
SELECT ename, substr(ename,1,3) from emp;
SELECT ename, substr(ename,-3) from emp;
SELECT ename, substr(ename,-1) from emp;
SELECT substr('america',5,4) from dual;
SELECT substr('america',-4,2) from dual;
SELECT substr('america',-4,-2) from dual; --
SELECT substr('america',-2) from dual;
SELECT substr('america',-2,3) from dual;

SELECT substr('SMITH',1,length('SMITH')/2) FROM DUAL;

Display 3 columns in the output (using table EMP)


1) ENAME
2) FNAME -> first half of the ENAME
3) LNAME -> second half of the ENAME

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;

SELECT * from strdemo;


truncate table strdemo;
insert into strdemo values(101,'Refunded: 55.75; for the order o1756');
insert into strdemo values(102,'I Refunded: 299.3725; on behalf of my company');
insert into strdemo values(103,'My company REFUNDED: 3.27; to ITA');
SELECT * from strdemo;

display 3 columns in output


1) id
2) Description
3) AMT -> refund amount

SELECT ID, DESCRIPTION,


SUBSTR(DESCRIPTION,INSTR(DESCRIPTION,':',1)+2,INSTR(DESCRIPTION,';',1)-
(INSTR(DESCRIPTION,':',1)+2))AMT FROM STRDEMO;

TRUNCATE TABLE STRDEMO;


insert into strdemo values(101,'modified from 7.99 to 10.99');
insert into strdemo values(102,'modified from 177.22 to 210.89.');
SELECT * from strdemo;

display 4 columns in output


1) ID
2) description
3) Old_amount
4) New_Amount

SELECT ID, DESCRIPTION,


SUBSTR(DESCRIPTION,INSTR(DESCRIPTION,' ',1,2)+1,
INSTR(DESCRIPTION,' ',1,3)-(INSTR(DESCRIPTION,' ',1,2)+1)) OLD_AMOUNT
,RTRIM(SUBSTR(DESCRIPTION,INSTR(DESCRIPTION,' ',-1)+1),'.') NEW_AMOUNT
FROM STRDEMO;

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'

SELECT ENAME, LPAD(ENAME,10) FROM EMP;


SELECT ENAME, LPAD(ENAME,10,'*') FROM EMP;
SELECT ENAME, LPAD(ENAME,10,'A') FROM EMP;
SELECT ENAME, LPAD(ENAME,10,'ABC') FROM EMP;
select lpad('ita',6) from dual;
select lpad('ita',6,'z') from dual;
select lpad('ita',6,'ab') from dual;
SELECT LPAD('ita',5,'Z') FROM DUAL;
SELECT LPAD('ita',5,'PQR') FROM DUAL;
SELECT LPAD('ITA',3) FROM DUAL;
SELECT LPAD('ITA',2) FROM DUAL;
select lpad('america',7,'ab') from dual;
select lpad('america',8,'ab') from dual;
select lpad('america',6,'ab') from dual;
SELECT RPAD('america',6) ab FROM DUAL;
select rpad('america',8,'s') abc from dual;

select lpad(ename,length(ename)) newname from emp;


select lpad(ename,length(ename)+4) newname from emp;
select lpad(ename,length(ename)+5,'*') newname from emp;

18. DECODE

Decode function has the functionality of an IF-THEN-ELSE statement


Usage: DECODE( expression , search , result [, search , result]... [, default] )

Expression is the value to compare.


Search is the value that is compared against expression.
Result is the value returned, if expression is equal to search.
Default is optional. If no matches are found, the DECODE function returns default. If default is
omitted, then the decode statement returns null.

SELECT ENAME, SAL, DEPTNO, DECODE(DEPTNO,10,100,20,200,30,300) NEWCOL FROM EMP;


SELECT ENAME, SAL, DEPTNO, DECODE(DEPTNO,10,100,20,200) NEWCOL FROM EMP;
SELECT ENAME, SAL, DEPTNO, DECODE(DEPTNO,10,100) NEWCOL FROM EMP;
SELECT ENAME, SAL, DEPTNO, DECODE(DEPTNO,10,100,20,'A') NEWCOL FROM EMP;
SELECT ENAME, SAL, DEPTNO, DECODE(DEPTNO,10,'B',20,'A') NEWCOL FROM EMP;
SELECT ENAME, SAL, DEPTNO, DECODE(DEPTNO,10,100,200) NEWCOL FROM EMP;
SELECT EMPNO, ENAME, SAL, DEPTNO, DECODE(DEPTNO,10,'WELCOME',20,'HELLO') ABC FROM
EMP;
SELECT EMPNO, ENAME, SAL, DEPTNO, DECODE(DEPTNO,10,'TEN','NON-TEN') ABC FROM EMP;
SELECT EMPNO, ENAME, SAL, DEPTNO, DECODE(DEPTNO,10,100,'OTHERS') DEPARTMENT FROM
EMP;
SELECT EMPNO, ENAME, SAL, DEPTNO, DECODE(DEPTNO,10,'OTHERS',100) DEPARTMENT FROM
EMP;
SELECT EMPNO, ENAME, SAL, DEPTNO, DECODE(DEPTNO,10,100,'200') DEPARTMENT FROM EMP;
SELECT EMPNO,ENAME, DEPTNO, DECODE(DEPTNO,10,300,20,200,30,100) NEWCOL FROM EMP;
SELECT EMPNO, ENAME, DECODE(ENAME,'KING',1,2) NEWCOL FROM EMP;
SELECT EMPNO, ENAME, DECODE(ENAME,'KING',1,2) NEWCOL FROM EMP ORDER BY 3;
SELECT EMPNO, ENAME, DECODE(ENAME,'KING',1,2) NEWCOL FROM EMP ORDER BY 3,ENAME;
SELECT ENAME FROM EMP ORDER BY DECODE(ENAME,'MILLER',1,2),ENAME;
SELECT distinct job FROM EMP ORDER BY DECODE(JOB,'MANAGER',1,2),JOB;

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

Returns the largest in a list of expressions


select greatest(30,10,20) from dual
select greatest('A','b') from dual

SELECT GREATEST(10,20,5) FROM DUAL;


SELECT GREATEST(10,20,5,null) FROM DUAL;
SELECT GREATEST(10,'20',5) FROM DUAL;
SELECT GREATEST('A','Z','s') FROM DUAL;

20. LEAST

Returns the least in a list of expressions


select least(30,10,20) from dual
select least('A','b') from dual

SELECT LEAST(10,20,5) FROM DUAL;


SELECT LEAST(10,20,5,null) FROM DUAL;
SELECT EMPNO, ENAME, SAL, COMM, LEAST(SAL,COMM), GREATEST(SAL,COMM) FROM EMP;

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

SELECT CEIL(20.99) FROM DUAL;


SELECT CEIL(-20.99) FROM DUAL;
SELECT CEIL(20.01) FROM DUAL;

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

SELECT FLOOR(20.99) FROM DUAL;


SELECT FLOOR(-20.01) FROM DUAL;
SELECT CEIL(20.35), FLOOR(20.35) FROM DUAL;

23. TRUNC

Number truncated to a certain number of decimal places.


Usage: TRUNC(number, [ decimal_places ] )
number is the number to truncate.
decimal_places is the number of decimal places to truncate to. This value must be an integer. If
this parameter is omitted, the trunc function will truncate the number to 0 decimal places.
eg: TRUNC(125.815) would return 125;
TRUNC(125.815, 0) would return 125;
TRUNC(125.815, 1) would return 125.8;
TRUNC(125.815, 2) would return 125.81;
TRUNC(125.815, 3) would return 125.815;
TRUNC(-125.815, 2) would return -125.81;
TRUNC(125.815, -1) would return 120;
TRUNC(125.815, -2) would return 100;
TRUNC(125.815, -3) would return 0

SELECT TRUNC(20.99) FROM DUAL;


SELECT TRUNC(-3.2) FROM DUAL;
SELECT TRUNC(12345.768) FROM DUAL;
SELECT TRUNC(12345.768,0) FROM DUAL;
SELECT TRUNC(12345.768,2) FROM DUAL;
SELECT TRUNC(12345.768,-1) FROM DUAL;
SELECT TRUNC(12345.768,-2) FROM DUAL;
SELECT TRUNC(12345.768,-3) FROM DUAL;
SELECT TRUNC(12345.768,-5) FROM DUAL;
SELECT TRUNC(247.589) FROM DUAL;
SELECT TRUNC(247.7) FROM DUAL;
SELECT TRUNC(247.489,2) FROM DUAL;
SELECT TRUNC(123.449,1) FROM DUAL;
SELECT TRUNC(123.45,-1) FROM DUAL;
SELECT TRUNC(1234.56,-2) FROM DUAL;
SELECT TRUNC(1834.56,-3) FROM DUAL;
SELECT TRUNC(-2.7) FROM DUAL;

24. ROUND

Returns a number rounded to a certain number of decimal places


Usage: ROUND(number, [ decimal_places ] )
number is the number to round
decimal_places is the number of decimal places rounded to. This value must be an integer. If this
parameter is omitted, the round function will round the number to 0 decimal places.
eg: ROUND(125.315) WOULD RETURN 125;
ROUND(125.315, 0) WOULD RETURN 125;
ROUND(125.315, 1) WOULD RETURN 125.3;
ROUND(125.315, 2) WOULD RETURN 125.32;
ROUND(125.315, 3) WOULD RETURN 125.315;
ROUND(-125.315, 2) WOULD RETURN -125.32;
ROUND(125.315,-1) WOULD RETURN 130;
ROUND(125.315, -2) WOULD RETURN 100;

SELECT ROUND(20.99) FROM DUAL;


SELECT ROUND(-2.7) FROM DUAL;
SELECT ROUND(-2.5) FROM DUAL;
SELECT ROUND(20.5) FROM DUAL;
SELECT ROUND(-3.5) FROM DUAL;
SELECT ROUND(12345.768,2) FROM DUAL;
SELECT ROUND(12345.7649,2) FROM DUAL;
SELECT ROUND(12345.768,0) FROM DUAL;
SELECT ROUND(12345.768,-1) FROM DUAL;
SELECT ROUND(1234.567,-2) FROM DUAL;
SELECT ROUND(12345.768,-3) FROM DUAL;
SELECT ROUND(12345.768,-5) FROM DUAL;
SELECT ROUND(52345.768,-5) FROM DUAL;
SELECT ROUND(247.489) FROM DUAL;
SELECT ROUND(247.7) FROM DUAL;
SELECT ROUND(247.489,2) FROM DUAL;
SELECT ROUND(123.449,1) FROM DUAL;
SELECT ROUND(123.45,-1) FROM DUAL;
SELECT ROUND(1834.56,-3) FROM DUAL;

25. MOD

Returns the remainder of m divided by n (when used as mod( m, n ) )


MOD(15, 4) would return 3;
MOD(15, 0) would return 15;
MOD(11.6, 2) would return 1.6;
MOD(11.6, 2.1) would return 1.1;
MOD(-15, 4) would return -3;
MOD(-15, 0) would return -15

SELECT MOD(5,2) FROM DUAL;


SELECT MOD(9,3) FROM DUAL;
SELECT MOD(5,10) FROM DUAL;
SELECT MOD(3,7) FROM DUAL;

SELECT MOD(-5,2) FROM DUAL;


SELECT MOD(5,-2) FROM DUAL;
SELECT MOD(-5,-2) FROM DUAL;

SELECT * FROM EMP WHERE MOD(EMPNO,2)=0;


SELECT * FROM EMP WHERE MOD(EMPNO,2)=1;

SELECT * FROM EMP WHERE MOD(EMPNO,3)=0;


SELECT * FROM EMP WHERE MOD(EMPNO,3)=1;
SELECT * FROM EMP WHERE MOD(EMPNO,3)=2;

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;

SELECT ENAME FROM EMP WHERE MOD(LENGTH(ENAME),2)=0;

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

Returns the absolute value of a number


eg: ABS(-23) would return 23;
ABS(-23.6) would return 23.6;
ABS(23.65) would return 23.65

SELECT ABS(MOD(-9,2)) FROM DUAL;

27. SIGN

Returns a value indicating the sign of a number


Usage: SIGN( number )
number is the number to test for its sign.
If number < 0, then sign returns -1
If number = 0, then sign returns 0
If number > 0, then sign returns 1
eg: SIGN(-23) would return -1; sign(-0.001) would return -1; sign(0) would return 0; sign(0.001)
would return 1;
SIGN(23) would return 1; sign(23.601) would return 1

SELECT SIGN(25) FROM DUAL;


SELECT SIGN(0) FROM DUAL;
SELECT SIGN(2) FROM DUAL;
SELECT SIGN(-2) FROM DUAL;
SELECT SIGN(null) FROM DUAL;

28. SQRT

Returns the square root of n


Usage: SQRT( n )
eg: SQRT(9) would return 3;
SQRT(-5) would return argument -5 is out of range >

SELECT SQRT(25) FROM DUAL;


SELECT SQRT(5) FROM DUAL;
SELECT SQRT(-25) FROM DUAL;
SELECT SQRT(0) FROM DUAL;
29. POWER

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;

SELECT POWER(2,2) FROM DUAL;


SELECT POWER(4,3) FROM DUAL;
SELECT POWER(-4,3) FROM DUAL;
SELECT POWER(-4,2) FROM DUAL;
SELECT POWER(2,-3) FROM DUAL;

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.

SELECT SUPPLIER_ID, NVL(SUPPLIER_DESC, SUPPLIER_NAME) FROM SUPPLIERS;


WOULD RETURN THE SUPPLIER_NAME FIELD IF THE SUPPLIER_DESC CONTAINED A NULL VALUE.
OTHERWISE, IT WOULD RETURN THE SUPPLIER_DESC.

SELECT NVL(COMMISSION, 0) FROM SALES;


would return 0 if the commission field contained a null value. Otherwise, it would return the
commission field.

SELECT ENAME, SAL, COMM, NVL(COMM,9) FROM EMP;


SELECT ENAME, SAL, COMM, NVL(COMM,100) FROM EMP;
SELECT ENAME, SAL, COMM, NVL(COMM,'ABC') FROM EMP;
SELECT ENAME, SAL, COMM, SAL+NVL(COMM,0) TS FROM EMP;

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.

Usage: NVL2( string1, value_if_NOT_null, value_if_null )


string1 is the string to test for a null value.
value_if_NOT_null is the value returned if string1 is not null.
value_if_null is the value returned if string1 is null.

select NVL2(supplier_city, 'Completed', 'n/a') from suppliers;


would return 'n/a' if the supplier_city field contained a null value. Otherwise, it would return the
'Completed'.

select supplier_id, NVL2(supplier_desc, supplier_name, supplier_name2) from suppliers;


would return the supplier_name2 if the supplier_desc contained a null value. Otherwise, it would
return the supplier_name.
SELECT EMPNO, SAL, COMM, DEPTNO, NVL2(COMM,10,20) FROM EMP;
SELECT EMPNO, ENAME, SAL, COMM, DEPTNO, NVL2(COMM,SAL,DEPTNO) FROM emp;

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

SELECT ENAME, MGR, SAL, COMM, COALESCE(COMM,MGR,SAL,0) MD FROM EMP;


SELECT ENAME, MGR, SAL, COMM, COALESCE(COMM,MGR) MD FROM EMP;

33. NULLIF

NULLIF compares two expressions and returns null if they are equal, or the first expression if they
are not equal

SELECT NULLIF(10,20) FROM DUAL;


SELECT NULLIF(2,2) FROM DUAL;
SELECT NULLIF(3,2) FROM DUAL;
SELECT NULLIF(3,3) FROM DUAL;
SELECT NULLIF(3,NULL) FROM DUAL;

SELECT * FROM EMP;


SELECT ENAME, SAL, COMM, DECODE(NVL(NULLIF(COMM,SAL),0),0,'HELLO','WELCOME') ABC
FROM EMP;
SELECT NVL2(NULLIF(3,3),'EQUAL','NOT EQUAL') FROM DUAL;
SELECT DECODE(3,2,'NOT EQUAL','EQUAL') FROM DUAL;

34. REVERSE

REVERSE is Oracle string function, which returns the input string in its reverse order.

Syntax: REVERSE( string )


Usage: The SQL below uses the REVERSE function to reverse the order of input string "ORACLE".

SELECT REVERSE('ORACLE') FROM DUAL;


SELECT REVERSE('HELLO') FROM DUAL;
SELECT REVERSE('1056') FROM DUAL;
SELECT REVERSE(2016) FROM DUAL;

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

Select sysdate from dual;


Select empno, ename, sysdate from emp;

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;

SELECT SYSDATE FROM DUAL;


SELECT CURRENT_DATE FROM DUAL;
SELECT CURRENT_TIMESTAMP FROM DUAL;
SELECT LOCALTIMESTAMP FROM DUAL;
SELECT SYSTIMESTAMP FROM DUAL;

SELECT SYSDATE FROM DUAL;


ALTER SESSION SET NLS_DATE_FORMAT = 'MM/DD/YYYY';
SELECT * FROM EMP;

SELECT SYSDATE FROM DUAL;


ALTER SESSION SET NLS_DATE_FORMAT = 'MM/DD/YYYY HH:MI:SS';

SELECT SYSDATE FROM DUAL;


SELECT * FROM EMP;

ALTER SESSION SET TIME_ZONE = '-8:00';


ALTER SESSION SET TIME_ZONE = '+5:30';

SELECT CURRENT_DATE FROM DUAL;

SELECT SYSTIMESTAMP,LOCALTIMESTAMP,CURRENT_TIMESTAMP FROM DUAL;


SELECT SYSDATE FROM DUAL;

SELECT CURRENT_DATE FROM DUAL;


ALTER SESSION SET TIME_ZONE = '-4:00';
SELECT CURRENT_TIMESTAMP FROM DUAL;
SELECT SYSTIMESTAMP FROM DUAL;
SELECT LOCALTIMESTAMP FROM DUAL;

SELECT CURRENT_TIMESTAMP, LOCALTIMESTAMP, SYSTIMESTAMP FROM DUAL;

ARITHMETIC WITH DATES


ALTER SESSION SET NLS_DATE_FORMAT='MM/DD/YYYY HH24:MI:SS';

SELECT SYSDATE FROM DUAL;


SELECT SYSDATE, SYSDATE+1 FROM DUAL;
SELECT SYSDATE, SYSDATE+0.25 FROM DUAL;

SELECT SYSDATE, SYSDATE-3 FROM DUAL;


SELECT SYSDATE, SYSDATE+2 FROM DUAL;
SELECT SYSDATE, SYSDATE-'12/17/2016' FROM DUAL;
SELECT SYSDATE, SYSDATE-'17-DEC-16' FROM DUAL;

40. TO_DATE

to_date function converts a string to a date.


to_date( string1, format_mask)
string1 is the string that will be converted to a date.
This is the format that will be used to convert string1 to a 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

select to_date('2003/03/15', 'yyyy/mm/dd') from dual;

SELECT SYSDATE, SYSDATE-TO_DATE('12/17/2016','MM/DD/YYYY') FROM DUAL;


SELECT SYSDATE, SYSDATE-TO_DATE('03/08/1988','DD/MM/YYYY') FROM DUAL;
SELECT SYSDATE, SYSDATE-TO_DATE('10/01/1991','DD/MM/YYYY') FROM DUAL;

SELECT ENAME, SYSDATE, HIREDATE, DEPTNO, SYSDATE-HIREDATE


FROM EMP WHERE ENAME='SMITH';
SELECT SYSDATE FROM DUAL;
SELECT TO_DATE('05-06-16','MM-DD-YY') FROM DUAL;
SELECT TO_DATE('05-06-16','YY-MM-DD') FROM DUAL;
SELECT TO_DATE('05-06-16','MM-YY-DD') FROM DUAL;
SELECT * FROM EMP;
SELECT ENAME, SYSDATE, HIREDATE, DEPTNO, (SYSDATE-HIREDATE)/365
FROM EMP WHERE ENAME='SMITH';
SELECT ENAME FROM EMP WHERE SYSDATE-(30*365)<HIREDATE;
SELECT ENAME FROM EMP WHERE SYSDATE-(34*365)<HIREDATE;
SELECT ENAME FROM EMP WHERE SYSDATE-(35*365)<HIREDATE;
SELECT ENAME FROM EMP WHERE SYSDATE-HIREDATE>=(36*365);

41. TO_CHAR (datetime)


to_char function converts a number or date to a string.
to_char( value, [ format_mask ])
value can either be a number or date that will be converted to a string.

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

SELECT SYSDATE FROM DUAL;


SELECT TO_CHAR(SYSDATE,'YYYY-MONTH-DD') FROM DUAL;
SELECT TO_CHAR(SYSDATE,'YYYY/MONTH-DD') FROM DUAL;
SELECT TO_CHAR(SYSDATE,'YYYY-YY-YEAR-MONTH-MON-MM-DD-DY-DAY') FROM DUAL;
SELECT TO_CHAR(SYSDATE+30,'YYYY-YY-YEAR-MONTH-MON-MM-DD-DY-DAY') FROM DUAL;
SELECT * FROM EMP;
SELECT ENAME,HIREDATE, TO_CHAR(HIREDATE,'DD,MON-YYYY') FROM EMP WHERE DEPTNO=10;
SELECT ENAME,HIREDATE, TO_CHAR(HIREDATE,'DDTH,MON-YYYY') FROM EMP WHERE
DEPTNO=10;

SELECT SYSDATE FROM DUAL;

SELECT TO_CHAR(SYSDATE,'W') FROM DUAL;


SELECT TO_CHAR(SYSDATE,'WW') FROM DUAL;
SELECT TO_CHAR(SYSDATE,'HH:MI:SS AM') FROM DUAL;
SELECT TO_CHAR(SYSDATE+0.25,'HH:MI:SS AM') FROM DUAL;
SELECT TO_CHAR(SYSDATE+0.25,'HH24:MI:SS') FROM DUAL;
SELECT TO_CHAR(SYSDATE,'HH24:MI:SS') FROM DUAL;
SELECT ENAME, SAL, DEPTNO, TO_CHAR(SAL) FROM EMP;
SELECT ENAME, SAL, DEPTNO, TO_CHAR(SAL,'$9999.99') FROM EMP;
SELECT ENAME, SAL, DEPTNO, TO_CHAR(SAL,'$9,999.99') FROM EMP;
SELECT ENAME, SAL, DEPTNO, TO_CHAR(COMM,'$9,999.99') AMT FROM EMP;

42. TO_NUMBER

to_number function converts a string to a 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

YYYY - 4 DIGIT YEAR


YY - 2 DIGIT YEAR
YEAR- FULL YEAR IN WORDS
MONTH- FULL MONTH
MON- SHORT MONTH
MM-2 DIGIT MONTH
DD - 2 DIGIT DAY(DATE)
DY- SHORT NAME OF THE DAY
DAY-FULL NAME OF THE DAY
TH - ND, ST, RD,TH
Q-QUARTER
W - WEEK OF MONTH
WW - WEEK OF YEAR
HH-HOURS
HH24-HOURS IN 24HOUR FORMAT
MI-MINUTES
SS-SECONDS

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

SELECT LAST_DAY(SYSDATE) FROM DUAL;


select * from emp;
select ename, hiredate, last_day(hiredate) from emp where ename='SMITH';
select ename, hiredate, last_day(hiredate) from emp where ename='CLARK';
select ename, hiredate, last_day(hiredate) from emp where ename='ADAMS';
select ename, hiredate, last_day(hiredate) from emp where ename='WARD';

Display employees who got hired in first half of the month

select * from emp where


to_char(hiredate,'dd')<=to_char(last_day(hiredate),'dd')/2;

44. NEXT_DAY

returns the first weekday that is greater than a date.


Usage: next_day(date, weekday)
date -> is used to find the next weekday.
weekday -> is a day of the week (ie: SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY)
eg: next_day('01-Aug-03', 'TUESDAY') would return '05-Aug-03'; next_day('06-Aug-03',
'WEDNESDAY') would return '13-Aug-03';
next_day('06-Aug-03', 'SUNDAY') would return '10-Aug-03'
<if you give current weekday - will return next occurance of that weekday>

SELECT NEXT_DAY(SYSDATE,'WEDNESDAY') FROM DUAL;


SELECT NEXT_DAY(SYSDATE,'FRIDAY') FROM DUAL;
SELECT NEXT_DAY(SYSDATE,'THURSDAY') FROM DUAL;
SELECT NEXT_DAY(SYSDATE,'MONDAY') FROM DUAL;
SELECT * FROM EMP;
SELECT ENAME, HIREDATE FROM EMP;
display employees who got hired on monday

SELECT * FROM EMP WHERE TO_CHAR(HIREDATE,'DY')='MON';

display employees who got hired on monday using next_day function

select * from emp where next_day(hiredate,'TUESDAY')=HIREDATE+1;


select * from emp where next_day(hiredate,'MONDAY')=HIREDATE+7;
select * from emp where next_day(hiredate-1,'MONDAY')=HIREDATE;

45. TRUNC (date)

trunc(sysdate,'dy') - displays nearest sunday prior to current date


trunc(sysdate,'dd') or trunc(sysdate) - displays date ignoring timestamp
trunc(sysdate,'MONTH') - displays 1st day of current month
trunc(sysdate,'YEAR') - displays January 1st of current year
trunc(sysdate,'mi') - displays sysdate with nearest minute prior to current time
trunc(sysdate,'hh') - displays sysdate with nearest hour prior to current time
trunc(sysdate,'ww') - displays same day of the week as the first day of the year prior or equal to
current date
trunc(sysdate,'w') - displays same day of the week as the first day of the month prior or equal to
current date

select sysdate from dual;

ALTER SESSION SET NLS_DATE_FORMAT = 'MM/DD/YYYY HH24:MI:SS';


SELECT SYSDATE FROM DUAL;

SELECT SYSDATE, TRUNC(SYSDATE) FROM DUAL;


SELECT SYSDATE, TRUNC(SYSDATE,'DD') FROM DUAL;
SELECT SYSDATE, TRUNC(SYSDATE,'HH') FROM DUAL;
SELECT SYSDATE, TRUNC(SYSDATE,'MI') FROM DUAL;
SELECT SYSDATE, TRUNC(SYSDATE,'W') FROM DUAL;
SELECT SYSDATE, TRUNC(SYSDATE,'WW') FROM DUAL;
SELECT SYSDATE, TRUNC(SYSDATE,'MM') FROM DUAL;
SELECT SYSDATE, TRUNC(SYSDATE,'Q') FROM DUAL;
SELECT SYSDATE, TRUNC(SYSDATE,'YY') FROM DUAL;

46. ROUND (date)

round function returns a date rounded to a specific unit of measure.


Usage: round(date,[format])
date is the date to round; format is the unit of measure to apply for rounding. If the format
parameter is omitted, the round function will round to the nearest day.
Valid format parameters are: year, month, dd, dy, hh, mi, ww, w etc.,
round(sysdate,'dy') - displays nearest sunday
round(sysdate,'dd') or round(sysdate) - displays nearest day
round(sysdate,'MONTH') - displays nearest 1st day of month
round(sysdate,'YEAR') - displays nearest year (January 1st of nearest year)
round(sysdate,'mi') - displays sysdate with nearest minute
round(sysdate,'hh') - displays sysdate with nearest hour
round(sysdate,'ww') - displays same day of the week as the first day of the year
round(sysdate,'w') - displays same day of the week as the first day of the month
SELECT SYSDATE FROM DUAL;
SELECT SYSDATE, ROUND(SYSDATE,'DD') FROM DUAL;
SELECT SYSDATE, ROUND(SYSDATE,'MM') FROM DUAL;
SELECT SYSDATE, ROUND(SYSDATE,'Q') FROM DUAL;
SELECT ROUND(SYSDATE,'YY') FROM DUAL;
SELECT ROUND(SYSDATE,'W') FROM DUAL;
SELECT TRUNC(SYSDATE,'W') FROM DUAL;
SELECT TRUNC(SYSDATE+3,'W') FROM DUAL;
SELECT ROUND(SYSDATE+3,'W') FROM DUAL;
SELECT SYSDATE FROM DUAL;
SELECT TO_CHAR(TRUNC(SYSDATE,'HH'),'HH:MI:SS AM') FROM DUAL;
SELECT TO_CHAR(SYSDATE,'HH:MI:SS AM')
, TO_CHAR(ROUND(SYSDATE,'MI'),'HH:MI:SS AM') FROM DUAL;
SELECT * FROM EMP;

SELECT * FROM EMP WHERE TO_CHAR(TRUNC(HIREDATE,'Q'),'MON')='JUL';

47. ADD_MONTHS

add_months function returns a date plus n months


Usage: add_months(date1,n); date1-> is the starting date; n-> is the number of months to add
to date1
add_months('01-Aug-03', 3) would return '01-Nov-03'; ADD_MONTHS('01-Aug-03', -3) would
return '01-May-03'

SELECT SYSDATE FROM DUAL;


SELECT SYSDATE, ADD_MONTHS(SYSDATE,3) FROM DUAL;
SELECT SYSDATE, ADD_MONTHS(SYSDATE,-3) FROM DUAL;

SELECT ADD_MONTHS( (TRUNC(SYSDATE,'YY')+27), 1) FROM DUAL;


SELECT ADD_MONTHS( (TRUNC(SYSDATE,'YY')+28), 1) FROM DUAL;
SELECT ADD_MONTHS( (TRUNC(SYSDATE,'YY')+29), 1) FROM DUAL;
SELECT ADD_MONTHS( (TRUNC(SYSDATE,'YY')+30), 1) FROM DUAL;
SELECT ADD_MONTHS( (TRUNC(SYSDATE,'YY')+31), 1) FROM DUAL;

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.

SELECT MONTHS_BETWEEN(SYSDATE, to_date('8/1/2016','mm/dd/yyyy')) FROM DUAL;


SELECT MONTHS_BETWEEN(to_date('8/1/2016','mm/dd/yyyy'),SYSDATE) FROM DUAL;

SELECT MONTHS_BETWEEN(SYSDATE,TO_DATE('03/20/1994','MM/DD/YYYY')) FROM DUAL;

49. EXTRACT (datetime)

extracts a value from a date/datetime


We can extract
YEAR, MONTH, DAY FROM SYSDATE;
HOUR, MINUTE, SECOND also FROM LOCALTIMESTAMP;
TIMEZONE_HOUR, TIMEZONE_REGION, TIMEZONE_ABBR also from CURRENT_TIMESTAMP

EXTRACT(MONTH FROM CURRENT_TIMESTAMP) D_MONTH


, EXTRACT(DAY FROM CURRENT_TIMESTAMP) D_DAY
, EXTRACT(YEAR FROM CURRENT_TIMESTAMP) D_YEAR
, EXTRACT(HOUR FROM CURRENT_TIMESTAMP) D_HOUR
, EXTRACT(MINUTE FROM CURRENT_TIMESTAMP) D_MIN
, EXTRACT(SECOND FROM CURRENT_TIMESTAMP) D_SECOND
, EXTRACT(TIMEZONE_HOUR FROM CURRENT_TIMESTAMP) D_HOUR_TZ
, EXTRACT(TIMEZONE_REGION FROM CURRENT_TIMESTAMP) D_REGION
, EXTRACT(TIMEZONE_ABBR FROM CURRENT_TIMESTAMP) D_ABBR

SELECT EXTRACT(YEAR FROM SYSDATE) FROM DUAL;


SELECT EXTRACT(MONTH FROM SYSDATE) FROM DUAL;
SELECT EXTRACT(DAY FROM SYSDATE) FROM DUAL;
alter session set nls_date_format = 'dd-MON-YY';

Query to display employees who got hired in first half of month


select * from emp;

select * from emp where extract(day from hiredate)<=extract(day from last_day(hiredate))/2;

50. NEW_TIME

returns a date in time zone1 to a date in time zone2.


Usage: new_time( date, zone1, zone2 )

zone1 and zone2 can be any of the following values:


CST - Central Standard Time; CDT - Central Daylight Time
EST - Eastern Standard Time; EDT - Eastern Daylight Time
MST - Mountain Standard Time; MDT - Mountain Daylight Time
PST - Pacific Standard Time; PDT - Pacific Daylight Time
GMT - Greenwich Mean 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'.

ALTER SESSION SET NLS_DATE_FORMAT = 'MM/DD/YYYY HH24:MI:SS';


SELECT SYSDATE, SYSTIMESTAMP FROM DUAL;
SELECT SYSDATE FROM DUAL;

SELECT SYSDATE, NEW_TIME(SYSDATE,'EST','PST') FROM DUAL;


SELECT SYSDATE, NEW_TIME(SYSDATE,'PST','EST') FROM DUAL;
SELECT SYSDATE, NEW_TIME(SYSDATE,'EST','MST') FROM DUAL;
CASE Expression

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.

Searched CASE Expression

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 DEPTNO
WHEN 10 THEN 'HELLO'
WHEN 20 THEN 'WELCOME'
END REMARKS
FROM EMP;

SELECT ENAME, DEPTNO, SAL,


(CASE DEPTNO
WHEN 10 THEN 'HELLO'
WHEN 20 THEN 'WELCOME'
ELSE 'GREETING'
END) REMARKS
FROM EMP;

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;

SELECT ENAME,DEPTNO, SAL,


CASE WHEN DEPTNO=20 AND SAL<2000 THEN SAL*1.2
WHEN DEPTNO=20 AND SAL>=2000 THEN SAL*1.15
WHEN DEPTNO!=20 THEN SAL*1.1
END INCR
FROM EMP;

SET OPERATORS (Compound queries)

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.

SELECT DEPTNO FROM EMP


INTERSECT
SELECT DEPTNO FROM DEPT;

SELECT EMPNO FROM EMP


INTERSECT
SELECT DEPTNO FROM DEPT;

SELECT EMPNO, ENAME FROM EMP


INTERSECT
SELECT DEPTNO, DNAME FROM DEPT;
SELECT EMPNO, ENAME FROM EMP
INTERSECT
SELECT DNAME, DEPTNO FROM DEPT;

SELECT DEPTNO FROM EMP


INTERSECT
SELECT DEPTNO FROM EMP;

SELECT DEPTNO FROM DEPT


MINUS
SELECT DEPTNO FROM EMP;

SELECT DEPTNO FROM DEPT


UNION
SELECT DEPTNO FROM EMP;

SELECT DEPTNO FROM DEPT


UNION ALL
SELECT DEPTNO FROM EMP;

SELECT DEPTNO FROM DEPT ORDER BY 1


UNION ALL
SELECT DEPTNO FROM EMP ORDER BY 1;

SELECT DEPTNO FROM DEPT


UNION ALL
SELECT DEPTNO FROM EMP ORDER BY 1;

SELECT DEPTNO FROM DEPT


UNION ALL
SELECT empno FROM EMP
UNION ALL
SELECT SAL FROM EMP ORDER BY 1;

SELECT * FROM SALGRADE


UNION
SELECT * FROM DEPT;

SELECT * FROM DEPT


UNION
SELECT * FROM SALGRADE;

SELECT ENAME FROM EMP


UNION
SELECT EMPNO FROM EMP;

SELECT DEPTNO, DNAME, LOC FROM DEPT


UNION
SELECT GRADE, LOSAL, HISAL FROM SALGRADE;

SELECT DEPTNO, DNAME, LOC FROM DEPT


UNION
SELECT GRADE, TO_CHAR(LOSAL), TO_CHAR(HISAL) FROM SALGRADE;
SELECT DEPTNO, DNAME FROM DEPT
UNION
SELECT DEPTNO, ENAME FROM EMP;

SELECT DEPTNO, DNAME FROM DEPT


UNION
SELECT GRADE, 'HELLO' FROM SALGRADE;

SELECT DEPTNO, DNAME FROM DEPT


UNION
SELECT GRADE, NULL FROM SALGRADE;

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.

*** NULLS DO NOT PARTICIPATE IN GROUP FUNCTIONS***

51. MIN

The MIN function returns the minimum value of an expression


SELECT MIN(col/expr ) FROM table WHERE condition;

This is a group function and takes all the rows related to a group and returns a single value as
output.

52. MAX

The MAX function returns the maximum value of an expression


SELECT MAX(col/expr ) FROM table WHERE condition;

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

COUNT is a group function returns the number of rows in a query


The COUNT function will only count those records in which the field in the brackets is NOT NULL

You can use the DISTINCT clause within the COUNT function
eg: count(distinct deptno) -> displays number of unique values in deptno column

55. SUM

SUM function returns the summed value of an expression.


SELECT SUM(expression ) FROM table WHERE condition

- expression can be a numeric field or formula.

SELECT SUM(salary) as "Total Salary" FROM emp WHERE deptno=10;

select * from emp;

select max(sal) from emp;


select max(ename) from emp;
select max(hiredate) from emp;
SELECT MIN(SAL) FROM EMP;
SELECT SUM(SAL) FROM EMP;
SELECT COUNT(EMPNO) FROM EMP;
select count(deptno) from emp;
select count(distinct deptno) from emp;

** NULLS DO NOT PARTICIPATE IN GROUP FUNCTIONS **

select * from emp;

SELECT COUNT(MGR) FROM EMP;


SELECT COUNT(COMM) FROM EMP;
SELECT COUNT(NVL(COMM,0)) FROM EMP;
SELECT COUNT(DISTINCT DEPTNO) FROM EMP;
SELECT COUNT(*) FROM EMP;

select 9 from emp;


select count(9) from emp;
select count(1) from emp;
select count('a') from emp;

select * from salgrade;

INSERT INTO SALGRADE VALUES(NULL, NULL, NULL);


SELECT COUNT(GRADE) FROM SALGRADE;
SELECT COUNT(*) FROM SALGRADE;
SELECT count(1) FROM SALGRADE;
SELECT COUNT(1) FROM EMP;
SELECT AVG(SAL) FROM EMP WHERE DEPTNO=10;
SELECT AVG(COMM) FROM EMP WHERE DEPTNO=30;

select sum(comm)/count(comm) from emp;


select sum(comm)/count(comm) from emp where deptno=30;
SELECT AVG(SAL) FROM EMP WHERE DEPTNO=30;
select * from emp;
SELECT COUNT(COMM) FROM EMP WHERE DEPTNO IN (10,20);
SELECT sum(COMM) FROM EMP WHERE DEPTNO IN (10,20);

select max(sal) from emp;


select max(sal) from emp group by deptno;
select ENAME, max(sal) from emp group by DEPTNO; --

select deptno,max(sal) from emp group by deptno;

select * from emp;


SELECT DEPTNO, sum(SAL) FROM EMP GROUP BY DEPTNO;
SELECT job, MAX(SAL) FROM EMP GROUP BY job;
select ename, sum(sal) from emp group by ename;
select deptno, sum(sal) from emp group by deptno;

SELECT DEPTNO FROM EMP GROUP BY DEPTNO;


SELECT DEPTNO, MAX(SAL) FROM EMP WHERE DEPTNO IN (10,20) GROUP BY DEPTNO;
SELECT JOB, MAX(SAL) FROM EMP WHERE DEPTNO IN (10,20) GROUP BY JOB;
SELECT DEPTNO, MAX(SAL) FROM EMP WHERE DEPTNO IN (10,20,30) GROUP BY DEPTNO
ORDER BY 1;

select deptno, max(sal) from emp;


select deptno, max(sal) from emp group by empno;
select deptno, min(sal) from emp group by deptno;
select deptno from emp group by deptno;
select * from emp;

select count(*) from emp;


select * from emp;
SELECT deptno,COUNT(*) FROM EMP GROUP BY DEPTNO;
SELECT DEPTNO, COUNT(*) FROM EMP;
select * from emp;
SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO;
SELECT JOB, COUNT(*) FROM EMP GROUP BY JOB;
SELECT COMM, COUNT(*) FROM EMP GROUP BY COMM;
SELECT COMM, COUNT(comm) FROM EMP GROUP BY COMM;

SELECT DEPTNO, JOB FROM EMP;


SELECT DEPTNO, JOB, COUNT(*) FROM EMP GROUP BY DEPTNO, JOB;
SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO, JOB;
SELECT COUNT(*) FROM EMP GROUP BY DEPTNO, JOB;

select max(sal) from emp group by deptno;


SELECT DEPTNO, count(*) FROM EMP GROUP BY DEPTNO;

select * from emp;


SELECT DEPTNO, COUNT(*) FROM EMP WHERE DEPTNO IN (20,30) GROUP BY DEPTNO ORDER BY
1;
SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO;
SELECT DEPTNO, COUNT(*) FROM EMP where count(*)>=5 GROUP BY DEPTNO; --
SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO HAVING count(*)>=5;

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 COUNT(*) FROM EMP HAVING deptno=10;


SELECT COUNT(*) FROM EMP GROUP BY DEPTNO HAVING deptno=10;
select count(*) from emp;
SELECT COUNT(*) FROM EMP HAVING count(*)>10;
SELECT COUNT(*) FROM EMP HAVING count(*)<10;
SELECT SUM(SAL), MIN(SAL), MAX(HIREDATE) FROM EMP HAVING count(*)>10;
SELECT COUNT(*) FROM EMP HAVING count(*)<10;
SELECT COUNT(*) FROM EMP where deptno=10;

SELECT DEPTNO, MAX(SAL) FROM EMP GROUP BY DEPTNO HAVING COUNT(*)<5;


SELECT DEPTNO 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

SELECT DEPTNO, SUM(SAL) FROM EMP GROUP BY DEPTNO HAVING COUNT(*)>3;


SELECT DEPTNO FROM EMP GROUP BY DEPTNO HAVING COUNT(*)>3;

SELECT COUNT(*) FROM EMP HAVING COUNT(*)<3;

DROP TABLE SAMPLE;


CREATE TABLE SAMPLE (AMT NUMBER);
INSERT INTO SAMPLE VALUES(100);
INSERT INTO SAMPLE VALUES(400);
INSERT INTO SAMPLE VALUES(-300);
INSERT INTO SAMPLE VALUES(-700);
INSERT INTO SAMPLE VALUES(900);
INSERT INTO SAMPLE VALUES(0);

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;

SELECT SUM(AMT) FROM SAMPLE WHERE AMT!=0 GROUP BY SIGN(AMT);

GROUPING SETS expression

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.

The GROUPING SETS syntax is: GROUPING SETS(groupingSetList)


where groupingSetList is a single attribute, a comma-separated list of multiple
attributes, CUBE, ROLLUP, or () to specify an empty group. The empty group generates a total.
Note that nested grouping sets are not allowed.

For example:
GROUP BY GROUPING SETS(a, (b), (c, d), ())

Multiple grouping sets expressions can exist in the same query.


GROUP BY a, GROUPING SETS(b, c), GROUPING SETS((d, e))
is equivalent to:
GROUP BY GROUPING SETS((a, b, d, e),(a, c, d, e))

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(())

Note: Multiple grouping sets cannot be used on the corpus.

How duplicate attributes in a grouping set are handled


Specifying duplicate attributes in a given grouping set will not raise an error, but only one
instance of the attribute will be used. For example, these two queries are equivalent:

SELECT SUM(PROD_NAME) AS Products GROUP BY PROD_LIST_PRICE, PROD_LIST_PRICE

SELECT SUM(PROD_NAME) AS Products GROUP BY PROD_LIST_PRICE

GROUPING SETS example

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 * from emp;

select deptno, job, count(*) from emp group by deptno, job


union
select deptno, null, count(*) from emp group by deptno
union
select null, null, count(*) from emp;

select deptno, job, count(*) from emp


group by grouping sets((deptno,job),(deptno),());

select deptno, job, count(*) from emp


group by grouping sets((deptno,job),(deptno),(job),());

select count(*) from emp group by grouping sets


((deptno),(job),(deptno,job),());
3 5 6 - 4 4 3 1 2 - 1 1 1, 2 2 1, 4 1 1 - 14

select deptno, job, count(*) from emp group by grouping sets


((deptno),(job),(deptno,job),());

select deptno, job, count(*) from emp group by deptno, job


union
select deptno, NULL, count(*) from emp group by deptno
UNION
SELECT NULL, JOB,COUNT(*) FROM EMP GROUP BY JOB
union
select NULL, NULL, count(*) from emp;

select deptno, job, count(*) from emp group by cube(deptno,job);

select mgr,deptno, job, count(*) from emp group by cube(mgr,deptno,job);


select * from emp;

select deptno,job,mgr,sal from emp group by cube (deptno,job,mgr,sal);

select deptno, job, count(*) from emp group by rollup(deptno,job);


select mgr,deptno, job, count(*) from emp group by rollup(mgr,deptno,job);

select deptno,job,mgr,sal from emp group by rollup (deptno,job,mgr,sal);

select deptno, job, count(*) from emp group by grouping sets ((deptno),(job));

Analytical Functions

56. ROW_NUMBER

ROW_NUMBER is an analytic function. It assigns a unique number to each row to which it is


applied (either each row in the partition or each row returned by the query), in the ordered
sequence of rows specified in the order_by_clause, beginning with 1.

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.

Used as an Aggregate Function


As an Aggregate function, the rank returns the rank of a row within a group of rows.
select rank(2450) WITHIN GROUP (order by sal desc) from emp;

Used as an Analytic Function


As an Analytic function, the rank returns the rank of each row of a query with respective to the
other rows.
select rank() OVER (partition by deptno ORDER BY sal desc )

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

select ename, sal,


dense_rank() OVER (PARTITION BY deptno ORDER BY salary desc)
from emp

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

LAG (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)

value_expression - Can be a column or a built-in function.


offset - The number of rows preceeding the current row, from which the data is to be retrieved.
The default value is 1.
default - The value returned if the offset is outside the scope of the window. The default value is
NULL.

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

LEAD (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)

value_expression - Can be a column or a built-in function.


offset - The number of rows following the current row, from which the data is to be retrieved. The
default value is 1.
default - The value returned if the offset is outside the scope of the window. The default value is
NULL.

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 RANK(1500) WITHIN GROUP (ORDER BY SAL DESC) RK FROM EMP;


SELECT RANK(1650) WITHIN GROUP (ORDER BY SAL DESC) RK FROM EMP;
SELECT RANK(1500) WITHIN GROUP (ORDER BY SAL DESC) RK FROM EMP GROUP BY DEPTNO;

SELECT ENAME, SAL, RANK() OVER (ORDER BY SAL DESC) RK


, DENSE_RANK() OVER (ORDER BY SAL DESC) DRK
, ROW_NUMBER() OVER (ORDER BY SAL DESC) RN
FROM EMP;

SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO;


SELECT SUM(SAL) FROM EMP;
SELECT * FROM EMP;

SELECT ENAME, SUM(SAL) FROM EMP;


SELECT ENAME, SAL, SUM(SAL) FROM EMP GROUP BY ENAME,SAL;
SELECT ENAME, SAL, SUM(SAL) FROM EMP;
SELECT ENAME, SAL, SUM(SAL) OVER () FROM EMP;
SELECT ENAME, SAL, SUM(SAL) OVER (PARTITION BY DEPTNO) FROM EMP;
SELECT ENAME, SAL, DEPTNO, JOB, COUNT(*) OVER (PARTITION BY DEPTNO) FROM EMP;
SELECT ENAME, SAL, DEPTNO, JOB, COUNT(*) OVER (PARTITION BY JOB) FROM EMP;
SELECT ENAME, SAL, DEPTNO, SUM(SAL) OVER () FROM EMP;

SELECT DEPTNO, SUM(SAL), SUM(SAL) OVER () FROM EMP GROUP BY DEPTNO;

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, SAL, DEPTNO, SUM(SAL) OVER () TOTCOMPSAL FROM EMP;

SELECT ENAME, SAL, DEPTNO


, SUM(SAL) OVER (PARTITION BY DEPTNO) TOTDEPSAL
, SUM(SAL) OVER () TOTCOMPSAL FROM EMP;

SELECT ENAME, HIREDATE,DEPTNO, MAX(HIREDATE) OVER (PARTITION BY DEPTNO) FROM EMP;


SELECT ENAME, HIREDATE,DEPTNO FROM EMP WHERE HIREDATE=MAX(HIREDATE) OVER
(PARTITION BY DEPTNO); --
SELECT ENAME, HIREDATE,DEPTNO FROM EMP HAVING HIREDATE=MAX(HIREDATE) OVER
(PARTITION BY DEPTNO);--
SELECT ENAME, HIREDATE, DEPTNO
, DECODE(HIREDATE, MAX(HIREDATE) OVER (PARTITION BY DEPTNO),'YES','NO') RECENT
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
, DENSE_RANK() OVER (ORDER BY SAL DESC) DRK
FROM EMP;

SELECT ENAME, DEPTNO, SAL


, RANK() OVER (ORDER BY SAL DESC) RK
, DENSE_RANK() OVER (ORDER BY SAL DESC) DRK
, ROW_NUMBER() OVER (ORDER BY SAL DESC) RN
FROM EMP;

SELECT ENAME, DEPTNO, SAL


, RANK() OVER (ORDER BY SAL DESC) RK
, DENSE_RANK() OVER (ORDER BY SAL DESC) DRK
, ROW_NUMBER() OVER (ORDER BY SAL DESC,ENAME) RN
FROM EMP;

SELECT ENAME, DEPTNO, SAL, RANK() OVER (ORDER BY SAL DESC) RK FROM EMP;

SELECT ENAME, DEPTNO, SAL


, RANK() OVER (PARTITION BY DEPTNO ORDER BY SAL DESC) RK FROM EMP;

select * from emp;


SELECT ENAME, DEPTNO, SAL, RANK() OVER (ORDER BY ENAME) RK FROM EMP;
SELECT ENAME, DEPTNO, SAL, LAG(SAL) OVER (ORDER BY ENAME) LG FROM EMP;
SELECT ENAME, DEPTNO, SAL, LAG(ENAME) OVER (ORDER BY SAL DESC) LG FROM EMP;

SELECT * FROM EMP;


SELECT ENAME, DEPTNO, SAL
, LEAD(ENAME) OVER (PARTITION BY DEPTNO ORDER BY SAL) LD FROM EMP;

SELECT ENAME, DEPTNO, SAL


, LEAD(ENAME) OVER (ORDER BY SAL) LD FROM EMP;

Sub Queries

SELECT EMPNO, ENAME FROM EMP


WHERE DEPTNO=10;

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 sum(sal) from emp) AMOUNT


FROM EMP WHERE DEPTNO=10;

SELECT EMPNO, ENAME, (SELECT DNAME FROM DEPT WHERE DEPTNO=10) SQ


FROM EMP WHERE DEPTNO=10;

SELECT EMPNO, ENAME, (SELECT DEPTNO FROM DEPT WHERE DNAME='SALES') SQ


FROM EMP WHERE DEPTNO=10;
SELECT EMPNO, ENAME, (SELECT LOSAL FROM SALGRADE WHERE LOSAL>3000) SQ
FROM EMP WHERE DEPTNO=10;

SELECT EMPNO, ENAME, (SELECT SYSDATE FROM DUAL) SQ FROM EMP WHERE DEPTNO=10;

SELECT ENAME, DEPTNO, SAL


,(SELECT SAL FROM EMP WHERE ENAME='KING') NEWCOL
FROM EMP WHERE SAL>500;

SELECT ENAME, DEPTNO, SAL


,(SELECT ENAME FROM EMP WHERE SAL=5000) NEWCOL
FROM EMP WHERE SAL>500;

SELECT ENAME, DEPTNO, SAL


,(SELECT ENAME FROM EMP WHERE SAL=3000) NEWCOL
FROM EMP WHERE SAL>500;

SELECT ENAME, DEPTNO, SAL


,(SELECT MIN(ENAME) FROM EMP WHERE SAL=3000) NEWCOL
FROM EMP WHERE SAL>500;

SELECT ENAME, DEPTNO, SAL


,(SELECT SYSDATE FROM DUAL) NEWCOL
FROM EMP WHERE SAL>500;

SELECT ENAME, DEPTNO, SAL


,(SELECT 'WELCOME TO ITA' FROM DUAL) NEWCOL
FROM EMP WHERE SAL>500;

SELECT * FROM EMP;

SELECT ENAME, DEPTNO, SAL


FROM EMP
WHERE SAL>(SELECT SAL FROM EMP WHERE ENAME='JONES');

SELECT ENAME, DEPTNO, SAL


FROM EMP
WHERE SAL=(SELECT SAL FROM EMP WHERE ENAME='FORD');

SELECT ENAME, DEPTNO, SAL


FROM EMP
WHERE SAL=(SELECT SAL FROM EMP WHERE DEPTNO=20);

SELECT ENAME, DEPTNO, SAL


FROM EMP
WHERE SAL>(SELECT SAL FROM EMP WHERE DEPTNO=30);

SELECT ENAME, DEPTNO, SAL


FROM EMP
WHERE SAL >ALL (SELECT SAL FROM EMP WHERE DEPTNO=30);

SELECT ENAME, DEPTNO, SAL


FROM EMP
WHERE SAL IN (SELECT SAL FROM EMP WHERE DEPTNO=30);

SELECT ENAME, DEPTNO, SAL


FROM EMP
WHERE SAL >ANY (SELECT SAL FROM EMP WHERE DEPTNO=30);

SELECT * FROM EMP;

SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=20;

SELECT ENAME,SAL FROM


(SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=20);

SELECT ENAME, DNO FROM EMP;

SELECT * FROM EMP;

SELECT ENAME,SALARY FROM


(SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=30)
WHERE COMM IS NULL;

SELECT ENAME,SALARY FROM


(SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=30
WHERE COMM IS NULL);

SELECT ENAME,SALARY FROM


(SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=30
AND COMM IS NULL);

SELECT ENAME,SALARY FROM


(SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=30
OR COMM IS NULL);

SELECT ENAME,SALARY FROM


(SELECT ENAME, JOB, SAL SALARY, DEPTNO FROM EMP WHERE DEPTNO=30
OR COMM IS NULL) 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 * FROM EMP;

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');

CREATE TABLE EMP101 AS SELECT * FROM EMP;


INSERT INTO EMP101
SELECT 1001,'PRATIKSHA',JOB,MGR,HIREDATE,3000,COMM,10 FROM EMP WHERE ENAME='KING';
COMMIT;
SELECT * FROM EMP101;

SELECT ENAME FROM EMP101 WHERE SAL IN


(SELECT MAX(SAL) FROM EMP101 GROUP BY DEPTNO);

SELECT * FROM EMP WHERE DEPTNO=30 AND SAL=1250;


SELECT * FROM EMP WHERE (DEPTNO,SAL) = (30,1250);
SELECT * FROM EMP WHERE (DEPTNO,SAL) = ((30,1250));
SELECT * FROM EMP WHERE (DEPTNO,SAL) = (SELECT 30,1250 FROM DUAL);

SELECT * FROM EMP;


SELECT * FROM EMP WHERE (DEPTNO,SAL) IN ((30,1250),(20,3000));
SELECT * FROM EMP101;
SELECT ENAME FROM EMP101 WHERE (DEPTNO,SAL) IN
(SELECT DEPTNO, MAX(SAL) FROM EMP101 GROUP BY DEPTNO);

SELECT * FROM EMP;

SELECT E.EMPNO, E.ENAME, E.DEPTNO, E.DEPTNO+100


FROM EMP E;

SELECT E.EMPNO, E.ENAME, E.DEPTNO


, (SELECT D.DNAME FROM DEPT D WHERE D.DEPTNO=10) DN
FROM EMP E;

SELECT E.EMPNO, E.ENAME, E.DEPTNO


, (SELECT D.DNAME FROM DEPT D WHERE D.DEPTNO=E.DEPTNO) DN
FROM EMP E;

SELECT EMPNO, ENAME, DEPTNO


, (SELECT DNAME FROM DEPT WHERE DEPT.DEPTNO=EMP.DEPTNO) DN
FROM EMP;

SELECT * FROM EMP;


SELECT E.EMPNO, E.ENAME, E.DEPTNO
, (SELECT D.DNAME FROM DEPT D WHERE D.DEPTNO=40-E.DEPTNO) DN
FROM EMP E;

SELECT H.ENAME, H.DEPTNO, H.SAL FROM EMP H WHERE H.SAL =


(SELECT MAX(P.SAL) FROM EMP P WHERE P.DEPTNO=H.DEPTNO);

SELECT * FROM EMP WHERE (DEPTNO,SAL) IN


(SELECT DEPTNO, MAX(SAL) FROM EMP GROUP BY DEPTNO);

SELECT * FROM EMP;

SELECT E.ENAME FROM EMP E


WHERE E.SAL = (SELECT MAX(F.SAL) FROM EMP F WHERE F.JOB=E.JOB);

SELECT * FROM EMP;

SELECT E.JOB, E.ENAME FROM EMP E


WHERE E.HIREDATE =(SELECT MAX(F.HIREDATE) FROM EMP F WHERE F.JOB = E.JOB);

DISPLAY DETAILS OF EMPLOYEE(S) DRAWING SECOND HIGHEST SAL IN EMPLOYEES TABLE


SELECT * FROM EMP;

SELECT ENAME FROM


(SELECT ENAME, SAL, DENSE_RANK() OVER (ORDER BY SAL DESC) DRK FROM EMP)
WHERE DRK=2;

SELECT E.ENAME, E.SAL FROM EMP E WHERE


(SELECT COUNT(DISTINCT F.SAL) FROM EMP F WHERE F.SAL>E.SAL)=1;

SELECT E.ENAME, E.SAL FROM EMP E WHERE


(SELECT COUNT(DISTINCT F.SAL) FROM EMP F WHERE F.SAL>E.SAL)=4;
DISPLAY DEPTNO, ENAME OF THE EMPLOYEE(S) DRAWING SECOND HIGHEST SALARY IN EACH
DEPTNO

SELECT E.ENAME, E.SAL FROM EMP E WHERE


(SELECT COUNT(DISTINCT F.SAL) FROM EMP F WHERE F.SAL>E.SAL AND
F.DEPTNO=E.DEPTNO)=1;

SELECT ENAME, DRK FROM


(SELECT ENAME, DENSE_RANK() OVER (ORDER BY SAL DESC) DRK FROM EMP)
WHERE ENAME='JAMES';

EXISTS
NOT EXISTS;

SELECT * FROM EMP;

SELECT * FROM DEPT WHERE DEPTNO IN


(SELECT DISTINCT DEPTNO FROM EMP);

SELECT * FROM DEPT WHERE DEPTNO NOT IN


(SELECT DISTINCT DEPTNO FROM EMP);

SELECT * FROM DEPT;

SELECT D.* FROM DEPT D WHERE EXISTS


(SELECT 1 FROM EMP E WHERE E.DEPTNO=D.DEPTNO);

SELECT D.* FROM DEPT D WHERE NOT EXISTS


(SELECT 1 FROM EMP E WHERE E.DEPTNO=D.DEPTNO);

SELECT D.* FROM DEPT D WHERE EXISTS


(SELECT E.* FROM EMP E WHERE E.DEPTNO=D.DEPTNO);

SELECT D.DEPTNO, D.DNAME, D.LOC FROM DEPT D WHERE EXISTS


(SELECT E.EMPNO FROM EMP E WHERE E.DEPTNO=D.DEPTNO);

SELECT D.DEPTNO, D.DNAME, D.LOC FROM DEPT D WHERE NOT EXISTS


(SELECT E.EMPNO FROM EMP E WHERE E.DEPTNO=D.DEPTNO);

SELECT * FROM DEPT D WHERE EXISTS


(SELECT 1 FROM EMP E WHERE E.DEPTNO = D.DEPTNO);

SELECT * FROM DEPT D WHERE EXISTS


(SELECT 1 FROM EMP E WHERE E.DEPTNO != D.DEPTNO);

SELECT * FROM DEPT D WHERE EXISTS


(SELECT NULL FROM EMP E WHERE E.DEPTNO = D.DEPTNO);

SELECT * FROM DEPT D WHERE NOT EXISTS


(SELECT 9 FROM EMP E WHERE E.DEPTNO = D.DEPTNO);

SELECT * FROM DEPT D WHERE NOT EXISTS


(SELECT NULL FROM EMP E WHERE E.DEPTNO = D.DEPTNO);
SELECT * FROM DEPT D WHERE EXISTS
(SELECT 1 FROM EMP E WHERE E.DEPTNO = D.DEPTNO+10);

SELECT * FROM DEPT D WHERE EXISTS


(SELECT 1 FROM EMP E WHERE E.DEPTNO = D.DEPTNO-10);

SELECT * FROM DEPT D WHERE EXISTS


(SELECT 1 FROM EMP E WHERE E.DEPTNO+10 = D.DEPTNO-10);

SELECT * FROM DEPT D WHERE EXISTS


(SELECT 1 FROM EMP E WHERE E.DEPTNO-10 = D.DEPTNO-10);

SELECT * FROM DEPT D WHERE EXISTS


(SELECT 1 FROM EMP E WHERE E.DEPTNO-10 = D.DEPTNO+10);

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.

ROWID Pseudo column

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.

Rowid values have several important uses:

They are the fastest way to access a single row.

They can show you how the rows in a table are stored.

They are unique identifiers for rows in a table.

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:

SELECT * FROM emp WHERE ROWNUM < 10;

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:

SELECT * FROM EMP WHERE ROWNUM > 1;

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;

SELECT * FROM EMP;

SELECT EMPNO,ENAME,SAL,DEPTNO,ROWNUM FROM EMP WHERE SAL>2000;

for every qualified row - oracle assigns rownum (starts with 1 and increments by 1)

SELECT * FROM EMP;

SELECT EMPNO, ENAME, SAL, DEPTNO, ROWNUM FROM EMP;

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;

SELECT ENAME, JOB, SAL, DEPTNO, ROWNUM FROM

(SELECT * FROM EMP ORDER BY SAL DESC)

WHERE DEPTNO=10;

SELECT * FROM EMP;

SELECT * FROM EMP ORDER BY ROWNUM DESC;

SELECT * FROM EMP;

SELECT * FROM EMP WHERE ROWNUM=1;

SELECT * FROM EMP WHERE ROWNUM<=2;

SELECT * FROM EMP WHERE ROWNUM=2;

SELECT * FROM

(SELECT * FROM EMP WHERE ROWNUM<=7 ORDER BY ROWNUM DESC)


WHERE ROWNUM<=2;

SELECT ENAME, RN, ROWNUM FROM

(SELECT ENAME, ROWNUM RN FROM EMP WHERE ROWNUM<=7 ORDER BY ROWNUM DESC)

WHERE ROWNUM<=2;

SELECT ENAME FROM

(SELECT ENAME, ROWNUM RN FROM EMP WHERE ROWNUM<=7 ORDER BY ROWNUM DESC)

WHERE RN>=6;

SELECT ENAME FROM

(SELECT ENAME, JOB, ROWNUM RN FROM EMP)

WHERE RN=4;

SELECT * FROM EMP;

SELECT * FROM EMP WHERE ROWNUM<=4

MINUS

SELECT * FROM EMP WHERE ROWNUM<=3;

SELECT * FROM EMP;

SELECT EMPNO, ENAME, SAL, DEPTNO, ROWNUM R FROM EMP;

SELECT EMPNO,ENAME,SAL,DEPTNO FROM

(SELECT E.*, ROWNUM R FROM EMP E)


WHERE R=7;

SELECT EMPNO,ENAME,SAL,DEPTNO FROM

(SELECT E.*, ROWNUM R FROM EMP E WHERE ROWNUM<=260)

WHERE R=256;

SELECT * FROM

(SELECT EMPNO, ENAME, JOB, SAL, DEPTNO, ROWNUM R FROM EMP)

WHERE R=2;

SELECT * FROM EMP;

SELECT ENAME,ROWNUM, R FROM

(SELECT EMPNO, ENAME, JOB, SAL, DEPTNO, ROWNUM R FROM EMP ORDER BY ROWNUM DESC)

WHERE ROWNUM<=2;

SELECT * FROM EMP;

SELECT ENAME FROM

(SELECT EMPNO, ENAME, JOB, SAL, DEPTNO, ROWNUM R FROM EMP)

WHERE R BETWEEN 4 AND 7;

SELECT * FROM EMP WHERE ROWNUM<=7

MINUS

SELECT * FROM EMP WHERE ROWNUM<=3;

SELECT * FROM EMP;


Display 3rd highest salary from emp table

SELECT MIN(SAL) FROM

(SELECT DISTINCT SAL FROM EMP ORDER BY SAL DESC)

WHERE ROWNUM<=3;

SELECT SAL FROM

(SELECT SAL, ROWNUM R FROM

(SELECT DISTINCT SAL FROM EMP ORDER BY SAL DESC)

) WHERE R=3;

SELECT SAL FROM

(SELECT SAL, DENSE_RANK() OVER (ORDER BY SAL DESC) DRK FROM EMP)

WHERE DRK=3;

SELECT E.SAL FROM EMP E

WHERE (SELECT COUNT(DISTINCT F.SAL) FROM EMP F WHERE F.SAL>E.SAL)=2;

SELECT * FROM EMP;

QUERY TO DISPLAY ENAME FROM EVERY THIRD ROW OF TABLE EMP;

SELECT ENAME FROM

(SELECT ENAME, ROWNUM R FROM EMP)


WHERE MOD(R,3)=0;

CREATE TABLE DEPT1 AS SELECT * FROM DEPT;

SELECT * FROM DEPT1;

INSERT INTO DEPT1 SELECT * FROM DEPT;

INSERT INTO DEPT1 SELECT * FROM DEPT WHERE DEPTNO>20;

INSERT INTO DEPT1 SELECT * FROM DEPT WHERE DEPTNO>30;

DELETE FROM DEPT1 WHERE DEPTNO>40;

SELECT * FROM DEPT1;

SELECT DISTINCT DEPTNO, DNAME, LOC FROM DEPT1;

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;

SELECT DISTINCT * FROM DEPT1;

CREATE TABLE DEPT2 AS SELECT DISTINCT * FROM DEPT1;

SELECT * FROM DEPT2;

DROP TABLE DEPT1;

RENAME DEPT2 TO DEPT1;

SELECT * FROM DEPT1;

SELECT DEPTNO, DNAME, LOC, ROWID FROM DEPT1;


DELETE FROM DEPT1 WHERE ROWID IN

('AAAXJQAAGAAAAG0AAA','AAAXJQAAGAAAAG0AAC','AAAXJQAAGAAAAG0AAD'

,'AAAXJQAAGAAAAG0AAE','AAAXJQAAGAAAAG0AAF','AAAXJQAAGAAAAG0AAG'

);

SELECT DEPTNO,DNAME, LOC, ROWID FROM DEPT1;

SELECT DEPTNO, DNAME, LOC, MIN(ROWID)

FROM DEPT1

GROUP BY DEPTNO, DNAME, LOC;

SELECT MIN(ROWID)

FROM DEPT1

GROUP BY DEPTNO, DNAME, LOC;

DELETE FROM DEPT1 WHERE ROWID NOT IN

(SELECT MIN(ROWID) FROM DEPT1 GROUP BY DEPTNO, DNAME, LOC);

SELECT * FROM DEPT1;

How to delete duplicate rows from a table

DELETE FROM TABLE WHERE ROWID NOT IN

(SELECT MAX(ROWID) FROM TABLE GROUP BY ALL THE COLUMNS)


SQL*Loader

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.

SQL*Loader Control 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

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.

Oracle Database Rejects

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.

The Discard File

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.

Log File and Logging Information


When SQL*Loader begins execution, it creates a log file. If it cannot create a log file, execution
terminates. The log file contains a detailed summary of the load, including a description of any
errors that occurred during the load.

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:

SQLLDR CONTROL=sample.ctl, LOG=sample.log, BAD=baz.bad, USERID=scott/tiger,


DISCARD=toss.dsc,
DISCARDMAX=5

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 (bad file)

Default: The name of the datafile, with an extension of .bad.

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)

Default: The name of the datafile, with an extension of .dsc.

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 (log file)

Default: The name of the control file, with an extension of .log.

LOG specifies the log file that SQL*Loader will create to store logging information about the
loading process.

SKIP (records to skip)

Default: No records are skipped.

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:

Where SQL*Loader will find the data to load

How SQL*Loader expects that data to be formatted

How SQL*Loader will be configured (memory management, rejecting records, interrupted


load handling, and so on) as it loads the data

How SQL*Loader will manipulate the data being loaded

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

Table and field-list information

Input data (optional section)

Step1: target table

CREATE TABLE SCHOOL


(
SID NUMBER(3) PRIMARY KEY
,SNAME VARCHAR2(10)
,SCORE NUMBER(3)
);

SELECT * FROM SCHOOL;

Step 2: source data file

new file in notepad to be created with below name & contents


C:\LOAD\student.txt
Sno;sname;marks
101;scott;35
102;martin;45
103;Miller ITamerica;44
104;FORD;100
105;ALLen;87

Step 3: control file

Open notepad and type below content

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:

open command prompt (not sql prompt)

c:\> sqlldr control=C:\LOAD\process.ctl log=C:\LOAD\stulog.txt userid=scott/tiger skip=1

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

Below loading options can be specified in control file

TRUNCATE - truncates table before loading data


REPLACE - deletes table data before loading file data
APPEND - appends file data to existing table data
INSERT - Table to be empty

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

FIELDS TERMINATED BY ";"


(
SID,
SNAME"UPPER(:SNAME)",
SCORE
)

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.

select listagg(ename,',') within group (order by ename) enames from emp;


select deptno, listagg (ename, ',') WITHIN GROUP (ORDER BY ename) enames FROM emp GROUP
BY deptno;
select deptno, ename, listagg(ename,',') within group (order by ename) over (partition by
deptno) enames from emp;

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.

select sal, WIDTH_BUCKET(sal, 1, 10000, 10) grp from emp;


select ename, HIREDATE, WIDTH_BUCKET(HIREDATE, TO_DATE('01/01/1980','MM/DD/YYYY'),
TO_DATE('12/31/1989','MM/DD/YYYY'), 10) grp from emp;

WRITE A QUERY TO DISPLAY

1) THE EMPLOYEE NAME


2) HIREDATE
3) DEPTNO
4) NAME OF IMMEDIATE HIRE IN THE ORGANIZATION
5) NAME OF IMMEDIATE HIRE IN SAME DEPARTMENT

SELECT ENAME,HIREDATE,DEPTNO,LEAD(ENAME) OVER (ORDER BY HIREDATE) IHO,


LEAD(ENAME) OVER (PARTITION BY DEPTNO ORDER BY HIREDATE) IHD FROM EMP;

DROP TABLE TRANSACTION;


CREATE TABLE TRANSACTION
(
TXN_DATE DATE,
TXN_AMOUNT NUMBER
);

INSERT INTO TRANSACTION VALUES('10-APR-16',500);


INSERT INTO TRANSACTION VALUES('7-APR-16',200);
INSERT INTO TRANSACTION VALUES('17-APR-16',-600);
INSERT INTO TRANSACTION VALUES('28-APR-16',500);
INSERT INTO TRANSACTION VALUES('14-APR-16',-100);
INSERT INTO TRANSACTION VALUES('4-APR-16',1000);

SELECT * FROM TRANSACTION;


SELECT TXN_DATE, TXN_AMOUNT, SUM(TXN_AMOUNT) OVER (PARTITION BY TXN_DATE)
DAYTOTAL
FROM TRANSACTION;

INSERT INTO TRANSACTION VALUES('14-APR-16',200);

SELECT TXN_DATE, TXN_AMOUNT, SUM(TXN_AMOUNT) OVER (PARTITION BY TXN_DATE)


DAYTOTAL
FROM TRANSACTION;

SELECT TXN_DATE, TXN_AMOUNT, SUM(TXN_AMOUNT) OVER (ORDER BY TXN_DATE) BALANCE


FROM TRANSACTION;

SELECT TXN_DATE, TXN_AMOUNT, SUM(TXN_AMOUNT) OVER (ORDER BY TXN_DATE,ROWID)


BALANCE
FROM TRANSACTION;
SELECT * FROM EMP ORDER BY SAL DESC;

SELECT EMPNO, ENAME, DEPTNO, SAL, WIDTH_BUCKET(SAL,950,5000,4) WB FROM EMP;

SELECT 3498, WIDTH_BUCKET(3498,1,7000,2) WB FROM DUAL;


SELECT 3499, WIDTH_BUCKET(3499,1,7000,2) WB FROM DUAL;
SELECT 3500, WIDTH_BUCKET(3500,1,7000,2) WB FROM DUAL;
SELECT 3501, WIDTH_BUCKET(3501,1,7000,2) WB FROM DUAL;
SELECT 1, WIDTH_BUCKET(1,1,7000,2) WB FROM DUAL;
SELECT 7000, WIDTH_BUCKET(7000,1,7000,2) WB FROM DUAL;
SELECT 70000, WIDTH_BUCKET(70000,1,7000,2) WB FROM DUAL;
SELECT -20, WIDTH_BUCKET(-20,1,7000,2) WB FROM DUAL;

SELECT EMPNO, ENAME, DEPTNO, SAL, WIDTH_BUCKET(SAL,1,7000,7) WB FROM EMP;


SELECT EMPNO, ENAME, DEPTNO, SAL, WIDTH_BUCKET(SAL,1,4000,2) WB FROM EMP;
SELECT EMPNO, ENAME, DEPTNO, SAL, WIDTH_BUCKET(SAL,2000,5000,3) WB FROM EMP;

SELECT EMPNO, ENAME, HIREDATE


, WIDTH_BUCKET(EXTRACT(DAY FROM HIREDATE),1,EXTRACT(DAY FROM LAST_DAY(HIREDATE))
+1,2) BUCKET
FROM EMP;

SELECT * FROM EMP;

SELECT LISTAGG(ENAME,';') WITHIN GROUP (ORDER BY ENAME) NAMES FROM EMP;

SELECT LISTAGG(ENAME,';') WITHIN GROUP (ORDER BY ENAME) NAMES FROM EMP


GROUP BY DEPTNO;

SELECT DEPTNO, LISTAGG(ENAME,';') WITHIN GROUP (ORDER BY ENAME) NAMES


FROM EMP GROUP BY DEPTNO;

SELECT DEPTNO, LISTAGG(ENAME,'-') WITHIN GROUP (ORDER BY ENAME) NAMES


FROM EMP GROUP BY DEPTNO;

SELECT * FROM CUSTOMER;


DROP TABLE CUSTOMER;
CREATE TABLE CUSTOMER (NAME VARCHAR2(20), LOC VARCHAR2(10), MOVE_DT DATE);
INSERT INTO CUSTOMER VALUES('SCOTT','PA','10-SEP-2011');
INSERT INTO CUSTOMER VALUES('MARTIN','NY','22-JUN-1997');
INSERT INTO CUSTOMER VALUES('KING','CA','28-JUN-2009');
INSERT INTO CUSTOMER VALUES('BLAKE','NJ','18-JAN-2009');
INSERT INTO CUSTOMER VALUES('SCOTT','NJ','15-JUN-2012');
INSERT INTO CUSTOMER VALUES('MARTIN','NJ','16-SEP-2003');
INSERT INTO CUSTOMER VALUES('KING','NY','02-MAY-2010');
INSERT INTO CUSTOMER VALUES('KING','NJ','19-JUL-2012');
COMMIT;

SELECT * FROM CUSTOMER;

SELECT NAME, LISTAGG(LOC,',') WITHIN GROUP (ORDER BY MOVE_DT) LOCATION


,LISTAGG(MOVE_DT,',') WITHIN GROUP (ORDER BY MOVE_DT) MOVE_DT
FROM CUSTOMER GROUP BY NAME;

SELECT NAME, LISTAGG(LOC,',') WITHIN GROUP (ORDER BY MOVE_DT) LOCATION,


SUBSTR(LISTAGG(LOC,',') WITHIN GROUP (ORDER BY MOVE_DT),-2) CURRENTLOC
FROM CUSTOMER GROUP BY NAME;

SELECT NAME, LISTAGG(LOC,',') WITHIN GROUP (ORDER BY MOVE_DT DESC) LOCATION,


SUBSTR(LISTAGG(LOC,',') WITHIN GROUP (ORDER BY MOVE_DT DESC),1,2) CURRENTLOC
FROM CUSTOMER GROUP BY NAME;

SELECT JOB, LISTAGG(ENAME,';') WITHIN GROUP (ORDER BY ENAME DESC) GRP


FROM EMP GROUP BY JOB;

HIERARCHICAL QUERIES
====================

SELECT ENAME, LEVEL FROM EMP


START WITH ENAME='KING'
CONNECT BY MGR = PRIOR EMPNO;

SELECT * FROM EMP;

START WITH SPECIFIES THE ROOT ROW(S) OF THE HIERARCHY.


CONNECT BY SPECIFIES THE RELATIONSHIP BETWEEN PARENT AND CHILD ROWS OF THE
HIERARCHY;

SELECT ENAME, LEVEL FROM EMP


START WITH ENAME='KING'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, LEVEL FROM EMP


START WITH ENAME = 'JONES'
CONNECT BY SUBSTR(PRIOR ENAME,-1)=SUBSTR(ENAME,1,1);

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 ENAME, LEVEL FROM EMP WHERE LEVEL=2


START WITH ENAME='KING'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, LEVEL FROM EMP WHERE LEVEL=4


START WITH ENAME='KING'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, LEVEL FROM EMP WHERE LEVEL=3


START WITH ENAME='KING'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, LEVEL FROM EMP WHERE LEVEL=1


START WITH ENAME='KING'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, LEVEL FROM EMP


START WITH JOB='MANAGER'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, LEVEL FROM EMP


START WITH ENAME='JONES'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, LEVEL, CONNECT_BY_ROOT ENAME FROM EMP


START WITH ENAME='JONES'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, LEVEL, CONNECT_BY_ISLEAF FROM EMP


START WITH ENAME='JONES'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, LEVEL, CONNECT_BY_ROOT ENAME FROM EMP


START WITH JOB='MANAGER'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, SAL, CONNECT_BY_ROOT ENAME RT FROM EMP


START WITH JOB='MANAGER'
CONNECT BY MGR = PRIOR EMPNO;

SELECT RT, SUM(SAL) FROM


(SELECT ENAME, SAL, CONNECT_BY_ROOT ENAME RT FROM EMP
START WITH JOB='MANAGER' CONNECT BY MGR = PRIOR EMPNO)
GROUP BY RT;

SELECT ENAME, LEVEL FROM EMP


START WITH ENAME='KING'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, SYS_CONNECT_BY_PATH(ENAME,'-') PTH FROM EMP


START WITH ENAME='KING'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, LTRIM(SYS_CONNECT_BY_PATH(ENAME,';'),';') PTH FROM EMP


START WITH ENAME='KING'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, DEPTNO, ROW_NUMBER() OVER (PARTITION BY DEPTNO ORDER BY ENAME) RN


FROM EMP;

SELECT DEPTNO,ENAME, LEVEL FROM


(SELECT ENAME, DEPTNO, ROW_NUMBER() OVER (PARTITION BY DEPTNO ORDER BY ENAME) RN
FROM EMP)
START WITH RN=1 CONNECT BY RN = PRIOR RN+1 AND DEPTNO = PRIOR DEPTNO;

SELECT DEPTNO,ENAME, SYS_CONNECT_BY_PATH(ENAME,';') PTH FROM


(SELECT ENAME, DEPTNO, ROW_NUMBER() OVER (PARTITION BY DEPTNO ORDER BY ENAME) RN
FROM EMP)
START WITH RN=1 CONNECT BY RN = PRIOR RN+1 AND DEPTNO = PRIOR DEPTNO;

SELECT DEPTNO, LTRIM(SYS_CONNECT_BY_PATH(ENAME,';'),';') PTH FROM


(SELECT ENAME, DEPTNO, ROW_NUMBER() OVER (PARTITION BY DEPTNO ORDER BY ENAME) RN
FROM EMP)
START WITH RN=1 CONNECT BY RN = PRIOR RN+1 AND DEPTNO = PRIOR DEPTNO;

SELECT DEPTNO, MAX(LTRIM(SYS_CONNECT_BY_PATH(ENAME,';'),';')) PTH FROM


(SELECT ENAME, DEPTNO, ROW_NUMBER() OVER (PARTITION BY DEPTNO ORDER BY ENAME) RN
FROM EMP)
START WITH RN=1 CONNECT BY RN = PRIOR RN+1 AND DEPTNO = PRIOR DEPTNO
GROUP BY DEPTNO;

SELECT DEPTNO, LISTAGG(ENAME,';') WITHIN GROUP (ORDER BY ENAME) PTH FROM EMP GROUP
BY DEPTNO;

SELECT ENAME, LEVEL, LPAD(ENAME,LENGTH(ENAME)+5*LEVEL) FROM EMP


START WITH ENAME='KING'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, LEVEL, LPAD(ENAME,LENGTH(ENAME)


+LEVEL*5,DECODE(LEVEL,1,'-',2,'*',3,'>',4,'.')) FROM EMP
START WITH ENAME='KING'
CONNECT BY MGR = PRIOR EMPNO;

SELECT ENAME, LEVEL, LPAD(ENAME,LENGTH(ENAME)+LEVEL*5,'1234567890') FROM EMP


START WITH ENAME='KING'
CONNECT BY MGR = PRIOR EMPNO;

COMMENTS
========

SINGLE LINE (--)


MULTILINE COMMENTS (/* */)
--BELOW QUERY
SELECT
EMPNO
,ENAME
--,JOB
,SAL
,DEPTNO
FROM EMP;

SELECT
EMPNO
/*,ENAME
,JOB
,SAL
,DEPTNO*/
FROM EMP;

JOINS
=====

SELECT ENAME,SAL,DEPTNO FROM EMP;

SELECT * FROM EMP;


SELECT * FROM EMP,DEPT;
SELECT * FROM SALGRADE,DEPT;
SELECT * FROM SALGRADE;
SELECT * FROM EMP,DEPT;
SELECT * FROM EMP,DEPT WHERE EMP.DEPTNO>20;
SELECT * FROM EMP,DEPT WHERE EMP.DEPTNO>20 AND DEPT.DEPTNO<30;
SELECT * FROM EMP,DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO;
SELECT ENAME, EMP.DEPTNO, DEPT.DEPTNO, DNAME FROM EMP,DEPT WHERE
EMP.DEPTNO=DEPT.DEPTNO;
SELECT ENAME, EMP.DEPTNO, DEPT.DEPTNO, DNAME FROM EMP,DEPT WHERE EMP.DEPTNO!
=DEPT.DEPTNO;

SELECT ENAME, EMP.DEPTNO, DEPT.DEPTNO, DNAME FROM EMP,DEPT WHERE


EMP.DEPTNO>DEPT.DEPTNO;

SELECT ENAME, EMP.DEPTNO, DEPT.DEPTNO, DNAME FROM EMP,DEPT WHERE


EMP.DEPTNO>=DEPT.DEPTNO;

SELECT ENAME, EMP.DEPTNO, DEPT.DEPTNO, DNAME FROM EMP,DEPT WHERE


EMP.DEPTNO<DEPT.DEPTNO;

SELECT ENAME, EMP.DEPTNO, DEPT.DEPTNO, DNAME FROM EMP,DEPT WHERE


EMP.DEPTNO<=DEPT.DEPTNO;

SELECT * FROM DEPT1;


UPDATE DEPT1 SET DEPTNO=20 WHERE DEPTNO=40;
SELECT ENAME, EMP.DEPTNO, DEPT1.DEPTNO, DNAME
FROM EMP, DEPT1
WHERE EMP.DEPTNO=DEPT1.DEPTNO;

------
SELECT * FROM EMP, SALGRADE
WHERE EMP.SAL BETWEEN SALGRADE.LOSAL AND SALGRADE.HISAL;

SELECT E.* FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO;


SELECT * FROM EMP;

SELECT EMP.ENAME,DEPT.DNAME FROM


EMP INNER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;

SELECT * FROM EMP INNER JOIN DEPT ON EMP.DEPTNO!=DEPT.DEPTNO;


SELECT * FROM EMP INNER JOIN DEPT ON EMP.DEPTNO>DEPT.DEPTNO;
SELECT * FROM DEPT D INNER JOIN EMP E ON D.DEPTNO=E.DEPTNO;

SELECT * FROM DEPT D INNER JOIN EMP E ON D.DEPTNO=E.DEPTNO+10;

SELECT * FROM DEPT D INNER JOIN EMP E ON D.DEPTNO=E.DEPTNO-10;

SELECT * FROM DEPT D INNER JOIN EMP E ON D.DEPTNO-10=E.DEPTNO-10;

SELECT * FROM DEPT D INNER JOIN EMP E ON D.DEPTNO+10=E.DEPTNO-10;

SELECT D.DNAME, COUNT(*) FROM DEPT D INNER JOIN EMP E ON D.DEPTNO=E.DEPTNO


GROUP BY D.DNAME;

-INNER JOIN (GETS MATCHING RECORDS FROM BOTH THE TABLES)


LEFT OUTER JOIN (GETS ALL ROWS FROM LEFT TABLE AND MATCHING FROM RIGHT TABLE)
RIGHT OUTER JOIN (GETS ALL ROWS FROM RIGHT TABLE AND MATCHING FROM LEFT)
FULL OUTER JOIN (GETS ALL ROWS FROM BOTH TABLES)
SELF JOIN (JOINING TABLE TO ITSELF)
-EQUI JOIN (JOIN CONDITION USING '=' OPERATOR)
-NON-EQUI JOIN (JOIN CONDITION USING OTHER THAN '=' OPERATOR)
-CROSS JOIN (CARTESIAN PRODUCT) - WHERE NO JOIN CONDITION IS SPECIFIED
;
SELECT * FROM T1;
SELECT * FROM T2;
CREATE TABLE T1(C1 NUMBER(2), C2 VARCHAR2(3));
CREATE TABLE T2(C3 NUMBER(2), C4 VARCHAR2(3));
INSERT INTO T1 VALUES(1,'A');
INSERT INTO T1 VALUES(2,'B');
INSERT INTO T1 VALUES(3,'C');
INSERT INTO T2 VALUES(1,'X');
INSERT INTO T2 VALUES(1,'P');
INSERT INTO T2 VALUES(3,'Z');
INSERT INTO T2 VALUES(4,'R');
COMMIT;

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, COUNT(E.EMPNO) 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 * FROM DEPT D INNER JOIN EMP E ON D.DEPTNO=E.DEPTNO;


SELECT * FROM DEPT D INNER JOIN EMP E ON D.DEPTNO=E.DEPTNO+10;
SELECT * FROM DEPT D LEFT OUTER JOIN EMP E ON D.DEPTNO=E.DEPTNO+10;
SELECT * FROM DEPT D INNER JOIN EMP E ON D.DEPTNO=E.DEPTNO-10;
SELECT * FROM DEPT D LEFT OUTER JOIN EMP E ON D.DEPTNO=E.DEPTNO-10;
SELECT * FROM DEPT D INNER JOIN EMP E ON D.DEPTNO-10=E.DEPTNO-10;
SELECT * FROM DEPT D LEFT OUTER JOIN EMP E ON D.DEPTNO-10=E.DEPTNO-10;
SELECT * FROM DEPT D INNER JOIN EMP E ON D.DEPTNO+10=E.DEPTNO-10;
SELECT * FROM DEPT D LEFT OUTER JOIN EMP E ON D.DEPTNO+10=E.DEPTNO-10;
SELECT * FROM DEPT D LEFT OUTER JOIN EMP E ON D.DEPTNO-10=E.DEPTNO+10;

SELECT EMP.ENAME, SALGRADE.GRADE


FROM EMP INNER JOIN SALGRADE
ON (EMP.SAL BETWEEN SALGRADE.LOSAL AND SALGRADE.HISAL);

SELECT E.ENAME, M.ENAME


FROM EMP E INNER JOIN EMP M ON E.MGR=M.EMPNO;

SELECT * FROM EMP;

SELECT E.ENAME, D.DNAME, S.GRADE


FROM EMP E INNER JOIN DEPT D ON E.DEPTNO=D.DEPTNO
INNER JOIN SALGRADE S ON E.SAL BETWEEN S.LOSAL AND S.HISAL;

SELECT * FROM EMP;

SELECT E.ENAME, M.ENAME


FROM EMP E INNER JOIN EMP M ON E.MGR=M.EMPNO;

SELECT E.ENAME, M.ENAME


FROM EMP E INNER JOIN EMP M
ON E.DEPTNO<M.DEPTNO;

SELECT * FROM EMP;

SELECT E.ENAME, M.ENAME


FROM EMP E INNER JOIN EMP M
ON E.DEPTNO=M.DEPTNO;

SELECT * FROM EMP;

SELECT E.ENAME, M.ENAME


FROM EMP E INNER JOIN EMP M
ON E.MGR=M.EMPNO;

SELECT E.ENAME, M.ENAME


FROM EMP E LEFT OUTER JOIN EMP M
ON E.MGR=M.EMPNO;

SELECT D.DNAME, E.ENAME


FROM DEPT D LEFT OUTER JOIN EMP E
ON D.DEPTNO=E.DEPTNO;

SELECT D.DNAME, E.ENAME


FROM DEPT D RIGHT OUTER JOIN EMP E
ON D.DEPTNO=E.DEPTNO;

SELECT D.DNAME, E.ENAME


FROM EMP E RIGHT OUTER JOIN DEPT D
ON D.DEPTNO=E.DEPTNO;

SELECT * FROM EMP;

SELECT E.ENAME, M.ENAME, B.ENAME


FROM EMP E INNER JOIN EMP M ON E.MGR = M.EMPNO
INNER JOIN EMP B ON M.MGR = B.EMPNO;

SELECT E.ENAME, M.ENAME, B.ENAME


FROM EMP E INNER JOIN EMP M ON E.MGR = M.EMPNO
INNER JOIN EMP B ON M.MGR = B.EMPNO;

SELECT * FROM EMP;

SELECT E.ENAME, M.ENAME, B.ENAME


FROM EMP E INNER JOIN EMP M ON E.MGR = M.EMPNO
LEFT OUTER JOIN EMP B ON M.MGR = B.EMPNO;

SELECT E.ENAME, M.ENAME, B.ENAME


FROM EMP E LEFT OUTER JOIN EMP M ON E.MGR = M.EMPNO
LEFT OUTER JOIN EMP B ON M.MGR = B.EMPNO;

SELECT E.ENAME, M.ENAME, B.ENAME


FROM EMP E LEFT OUTER JOIN EMP M ON E.MGR = M.EMPNO
INNER JOIN EMP B ON M.MGR = B.EMPNO;
SELECT E.ENAME, M.ENAME, B.ENAME
FROM EMP E LEFT OUTER JOIN EMP M ON E.MGR = M.EMPNO
LEFT OUTER JOIN EMP B ON M.MGR = B.EMPNO;

SELECT E.ENAME EMPLOYEE, M.ENAME MANAGER, B.ENAME BOSS


, COALESCE(B.ENAME,M.ENAME,E.ENAME) BOSS1
FROM
EMP E LEFT OUTER JOIN EMP M ON E.MGR=M.EMPNO
LEFT OUTER JOIN EMP B ON M.MGR=B.EMPNO;

SELECT E.EMPNO, E.ENAME EMPLOYEE


, COALESCE(B.ENAME,M.ENAME,E.ENAME) BOSS
FROM EMP E LEFT OUTER JOIN EMP M ON E.MGR = M.EMPNO
LEFT OUTER JOIN EMP B ON M.MGR = B.EMPNO;

SELECT E.ENAME EMPLOYEE,


DECODE(MOD(E.EMPNO,2),0,NVL(M.ENAME,E.ENAME),COALESCE(B.ENAME,M.ENAME,E.ENAME))
BOSS
FROM EMP E LEFT OUTER JOIN EMP M ON E.MGR = M.EMPNO
LEFT OUTER JOIN EMP B ON M.MGR = B.EMPNO;

SELECT ENAME,EMP.DEPTNO, DEPT.DEPTNO, DNAME


FROM EMP JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;

SELECT ENAME,EMP.DEPTNO, DEPT.DEPTNO, DNAME


FROM DEPT JOIN EMP ON DEPT.DEPTNO=EMP.DEPTNO;

SELECT ENAME, DEPTNO, DNAME


FROM EMP JOIN DEPT USING (DEPTNO);

SELECT ENAME, DEPTNO, DNAME


FROM EMP JOIN DEPT; --

SELECT EMP.ENAME,DEPTNO,DNAME
FROM EMP JOIN DEPT USING (DEPTNO)
JOIN EMP1 USING (DEPTNO);

SELECT ENAME, DEPTNO, DNAME


FROM EMP NATURAL JOIN DEPT;

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

IF YOU WANT TO ACCESS ITA.PRODUCT, SYSTEM.DIM_COUNTRY (BEING IN SCOTT@ABC)


THEN WE NEED TO CREATE A DATABASE LINK
DATABASE LINK CAN BE CREATED USING BELOW SCRIPT
(LOGIN TO SCOTT@ABC AND EXECUTE BELOW SCRIPT)
CREATE DATABASE LINK DL1 CONNECT TO ITA IDENTIFIED BY ITAMERICA USING 'XYZ';

(AM IN SCOTT@ABC) ->

SELECT * FROM EMP; -> VALID


SELECT * FROM DEPT; -> VALID
SELECT * FROM PRODUCT; -> VALID AND GETS DATA FROM SCOTT.PRODUCT
SELECT * FROM PRODUCT@DL1; -> VALID AND GETS DATA FROM ITA.PRODUCT@XYZ

NOW I WILL LOGON TO ITA@XYZ ->


SQL> SELECT * FROM PRODUCT -> VALID
SELECT * FROM EMP -> NOT VALID
SELECT * FROM EMP@DL1 -> NOT VALID

SELECT query sequence of execution


1) FROM clause
2) ON clause (in case of joins)
3) WHERE clause
4) GROUP BY clause
5) HAVING clause
6) SELECT clause
7) ORDER BY clause

You might also like