Professional Documents
Culture Documents
2 Quick Reference-SQL
2 Quick Reference-SQL
SQL
General Instructions
1. SQL commands are not at all case sensitive. You can type the command in any
case one case or a mix of cases.
2. While typing commands at the SQL prompt, the cursor cannot be moved back
using the left arrow key. The cursor can be moved back using the back space key.
In other words, a mistake in the typed command cannot be corrected directly
without deleting the command.
3. For correcting the mistake in a typed command without deleting it, you have to
open the editor. For opening the editor, simply type ed at the SQL prompt. The
last typed command will always remain in the SQL Buffer, and the same shall be
seen and edited by opening the editor.
If he editor is used to edit a command, save it after the edition and close the editor
window. Subsequently type / (forward slash) a the SQL prompt to execute the
command saved in the editor.
4. The table name should not exceed 30 characters.
5. No spaces are permitted in a table name
6. The column name should not exceed 30 characters
7. No spaces are permitted in a column name
Data Types
Data Type Width Type of Value
CHAR 1 – 255 Alphanumeric
VARCHAR2 1 – 4000 Alphanumeric
NUMBER 38 Numeric
DATE DD-MON-YY Date
LONG 2 GB CHAR
RAW 1 – 4000 Binary
LONG RAW 2 GB Binary
A field having CHAR data type will accept alphanumeric characters. The database will
hold memory for all the defined length of a CHAR data type field irrespective of the
actual length occupied by a value in that field.
A field having VARCHAR2 data type will accept alphanumeric characters. The database
will hold memory only for the length occupied by the value of a VARCHAR2 data type
Thampy Mathew 1
Oracle Complete – A Quick Reference
SQL
field. Like the CHAR data type, it will not hold memory for the entire field width without
considering the actual length occupied by a value.
The maximum data width of a NUMBER data type field is limited to 38. For NUMBER
data type fields, it is optional to specify field with.
Syntax:
Number OR
Number(Precision) OR
Number (Precision, Scale)
The scale can range from –84 to 127.
Example:
Salary Number
Salary Number(5)
Salary Number(7, 2) – Total 7 digits out of which 2 is reserved for decimals.
A DATE data type field can accept dates ranging from Jan 1 4712 BC to Dec 31, 4712
AD. In the database the date is stored as a numeric value derived from the given date.
A LONG or LONG RAW data type field can accept image files, sound files etc. Both
LONG and LONG RAW data types cannot be used in the same table. Either use LONG
or LONG RAW.
Thampy Mathew 2
Oracle Complete – A Quick Reference
SQL
EXPIRY_DATE DATE,
DEFAULT_TABLESPACE VARCHAR2(30) NOT NULL,
TEMPORARY_TABLESPACE VARCHAR2(30) NOT NULL,
CREATED DATE NOT NULL,
EXTERNAL_NAME VARCHAR2(4000)
Syntax:
Caution:
Within a database the table names cannot be repeated. Similarly, within a table
the column names also cannot be repeated. Column names may be repeated across
tables within a database.
Note:
The coma after every column definition indicates the continuity of the table
definition and hence it is known as the continuity sign.
The semi-colon or sometimes a forward slash (/) used at the end of the create
command is known as the execution sign as Oracle will try to execute the
command as soon as it come across the execution sign.
Thampy Mathew 3
Oracle Complete – A Quick Reference
SQL
Example:
Note:
Specifying width for a Number Data Type is optional.
Example:
Syntax:
Example:
Thampy Mathew 4
Oracle Complete – A Quick Reference
SQL
Syntax:
rename <Current Name of the Table > To <New Name for the Table>;
Example:
Syntax:
Example:
Desc EMP
Cle Scr
Thampy Mathew 5
Oracle Complete – A Quick Reference
SQL
Caution:
Irrespective of the case in which you typed the table name at the time of creating,
the table name will get stored only in uppercase in the TAB Table. So ensure that
you mention the Tname (full or partial) in upper case only.
The performance of queries against the tables may improve, since Oracle
may have to search only one partition (one part of the table) instead of the
entire table to resolve a query.
The table may be easier to manage. Since the portioned table’s data is
stored in multiple parts, it may be easier to load and delete data in the
partitions than in the large table.
Thampy Mathew 6
Oracle Complete – A Quick Reference
SQL
Backup and recovery operations may perform better. Since the partitions
are smaller than the partitioned table, you may have more options for
backing up and recovering the partitions than you would have for a single
large table.
Range Partitioning
Hash Partitioning
In the Hash Partition also you can name the partition and tablespace as follows.
Thampy Mathew 7
Oracle Complete – A Quick Reference
SQL
A hash partition determines the physical placement of data by performing a hash function
on the values of the partition key. In Range Partitioning, consecutive values of the
partition key are usually stored in the same partition. In hash partitioning, consecutive
values of the partition key are not necessarily stored in the same partition. Hash
partitioning distributes a set of records over a greater set of partitions than range
partitioning does, potentially decreasing the likelihood for I/O contention.
Select *
From WORKER Partition (PART3)
Where Name Like ‘R%’ ;
Stored Objects
Views
Synonyms
Sequences
Indexes
Views
A View is nothing but a query stored in a data dictionary table called USER_VIEWS. A
view does not consume any memory except for storing the query statement. The records
displayed on the terminal through a view are not data it stores but fetching them from the
base tables involved in the query statement when ever a DML operation is performed
Thampy Mathew 8
Oracle Complete – A Quick Reference
SQL
with it. All DML operations are possible on views depending upon the query from which
it is created.
Features of Views
Creating a View
Syntax:
Example:
OR
Thampy Mathew 9
Oracle Complete – A Quick Reference
SQL
Views Having Order By Clause
Note:
No DML operation is possible through views having Order By clause in its query
text. This is because, when the user deletes the first record from the view, the
system will try to delete the same first row from the base table which will be
another record.
Note:
No DML operation is possible through views having Order By clause in its query
text.
Note:
Only delete operation is possible on Master Table
All DMLs are possible on Child Table
Thampy Mathew 10
Oracle Complete – A Quick Reference
SQL
TYPE_TEXT_LENGTH VARCHAR2(4000),
OLD_TEXT_LENGTH NUMBER,
OLD_TEXT VARCHAR2(4000),
VIEW_TYPE_OWNER VARCHAR2(30),
VIEW_TYPE VARCHAR2(30)
Set Long4000
Synonyms
Synonyms are pointers on database objects like Tables Procedures, Functions, Database
Triggers and Views. As the name suggests it is only an alternate name for a database
object.
Thampy Mathew 11
Oracle Complete – A Quick Reference
SQL
Differences Between Views and Synonyms
Sl.No. Views Synonyms
1. Views can be created on limited Synonyms are always created on the
columns of a table complete table
2. View cannot be created as public Synonyms can be created as private or
directly. public.
(It may be made public using a
synonym.)
3. View is created from table(s) or Synonyms are created for database
other view(s) objects like Tables Procedures,
Functions, Database Triggers and Views.
4. A view cannot be created without A Synonym can be created for any object
the involved tables existing. even when the object does not exist. The
object shall be created later.
5. Only limited DML operations are All DML operations are possible using a
possible using a View synonym.
Schema
In the most simple terms a schema is a User/Password
Syntax:
Syntax:
Thampy Mathew 12
Oracle Complete – A Quick Reference
SQL
Example:
Indexes
Indexing will make the execution of a select statement faster. When an index is created
on a column of a table, implicitly an index segment will be created which will store
ROWIDs and column values of the indexed columns in ascending order.
When the user fires a select statement, using the indexed column as a where condition
based on the ROWID of the index, Oracle will fetch the corresponding records from the
table.
When the table is dropped, all the indexes will be dropped implicitly because an index
physically stores records of the indexed column.
Index on Deptno
Deptno ROWID
10 001
10 003
20 004
30 005
40 002
40 006
Thampy Mathew 13
Oracle Complete – A Quick Reference
SQL
For the primary key of a table oracle implicitly creates an index segment and stores data
of the PK column.
Creating an Index
Syntax:
Example:
Thampy Mathew 14
Oracle Complete – A Quick Reference
SQL
NUM_ROWS NUMBER
SAMPLE_SIZE NUMBER
LAST_ANALYZED DATE
DEGREE VARCHAR2(40)
INSTANCES VARCHAR2(40)
PARTITIONED VARCHAR2(3)
TEMPORARY VARCHAR2(1)
GENERATED VARCHAR2(1)
BUFFER_POOL VARCHAR2(7)
Sequences
Sequences are used to create unique numbers automatically.
Creating a Sequence
Syntax:
Example:
Simple Syntax:
Example:
Thampy Mathew 15
Oracle Complete – A Quick Reference
SQL
Choosing the Next Value from the Sequence
Dropping Sequence
Thampy Mathew 16
Oracle Complete – A Quick Reference
SQL
Inserting Records by Including All Fields of a Table
Syntax:
Insert into <table name>
values(<field 1 value>,
<field 2 value>,
…………………….
…………………….
<field n value>);
Example:
Caution:
1. The specified values must be in the same order of columns defined in the
table.
2. If the data type of the field is CHAR or VARCHAR2, then he values must be
enclosed in single quotes.
3. If no value is to be inserted into a particular field, then it must be indicated by
typing two single quotes without spaces. In the given example, a null is
inserted into the field ‘Comm’ by typing two quotes without spaces.
Syntax:
Example:
Insert into EMP (Sal, Ename)
values(5000, ‘MOHAN’);
Note:
If you want to insert values only for selected columns of a table, the column
names must be specified. When you specify the column name, the order of the
Thampy Mathew 17
Oracle Complete – A Quick Reference
SQL
columns in the table need not to be considered. But, subsequently when you
specify the values, they must come in the same order in which the columns are
specified in the Insert command.
Syntax:
Example:
Caution:
1. The update command as given above will set the value of the specified field of
all records with the given value.
2. If the data type of the field being updated is CHAR or VARCHAR2 then the
given value must be enclosed in single quotes.
Conditional Update
Example:
Update EMP Set Sal = 7000 where Ename = ‘Mohan’;
Syntax:
Example:
Thampy Mathew 18
Oracle Complete – A Quick Reference
SQL
Syntax:
Example:
Conditional Deletion
Caution:
For deleting values only from one field of a table, you should not use the ‘Delete’
command. In such cases use the ‘Update’ command.
If single quotes are not used for character data type columns along with the &,
you will have to enter values in single quotes later. To avoid it, the statement can
be rewritten as follows.
Thampy Mathew 19
Oracle Complete – A Quick Reference
SQL
When the above command is executed, Oracle will ask for values of Ename and
Empno to the user. This command can be executed n number of times without
retyping the command all over again. After one execution, simply type forward
slash (/) and enter. For each execution, Oracle will ask for values of Ename and
Empno to the user.
This command can be used again and again only till another command is typed at
the SQL prompt.
Example 2:
Example 3:
Commit
Any DML operation (Insert, Update, Delete) performed on a database table will become
permanent only if it is saved using the ‘Commit’ command.
Syntax:
Commit;
Note:
The saving operation is required only for DML commands. It is not applicable to
the DDL commands (Create, Drop, Rename). The DDL commands perform auto
commit along with the object creation.
Rollback
If the effect of an executed DML command is to be revoked, do rollback before
committing. The rollback will not work after executing the ‘Commit’ command.
Thampy Mathew 20
Oracle Complete – A Quick Reference
SQL
Syntax:
Rollback;
Syntax:
Example:
Caution:
1. The ‘Truncate’ command does not give a chance to rollback the deletion it
performed.
User1 can see both new and old records but other users can see only the old committed
records.
Thampy Mathew 21
Oracle Complete – A Quick Reference
SQL
Script Files
Script files are nothing but Notepad files with one or more SQL commands. When the
script file is run, all the commands written in it will get executed serially.
Syntax:
Example:
Type all the required commands in the script file as shown below.
Thampy Mathew 22
Oracle Complete – A Quick Reference
SQL
Caution:
In script files do not use semi-colon as execution sign. Instead, use forward slash
that also in a separate line as shown.
SQL> @C:\My_Script.txt
When the script runs, all commands typed in it will get executed serially.
When database objects and programs are to be transferred from one database to
another in the same or a different machine, scripts can be used.
Spool Files
A Spool file is nothing but a text file created to capture the output of SQL operations.
Note:
After opening a spool file, whatever commands are typed in the SQL prompt
along with its output will be stored in the spool file till then it is closed.
Modification of Structures
Adding a New Column to a Table
Syntax:
Thampy Mathew 23
Oracle Complete – A Quick Reference
SQL
Example:
Example:
Caution:
1. The width of an existing column cannot be decreased if records are present in
that column. This limitation is not applicable for increasing the column width.
2. The data type of an existing column cannot be changed from numeric to
character and vice versa if records are present in that column. However, we
can change the data type from CHAR to VARCHAR2 and vice versa provide
that the width of the new data type specified is equal to or more than the width
of the existing data type.
Duplicating a Table
Major Uses:
1. Changing the structure of an existing table with records. (The existing table is
duplicated. Then delete all records from the existing table. Make the required
modifications in the original table structure. Bring back all records to the
original table and drop the duplicate table.)
2. Dropping certain fields from an existing table. (Duplicate the existing table
only with the required number of columns. Drop the original table and rename
the duplicate table with the original table name.)
3. To change the column names. (Duplicate the existing table with new column
names. Drop the original table and rename the duplicate tab with the original
table name.)
Thampy Mathew 24
Oracle Complete – A Quick Reference
SQL
Duplicating Only the Structure of a Table
Syntax:
Example:
Syntax:
Example:
Caution:
If records are brought back after modifying the data type or width, ensure that the
data matches the new field definitions.
Syntax:
Example:
Thampy Mathew 25
Oracle Complete – A Quick Reference
SQL
Drop Table EMP;
Rename EMP1 To EMP;
Syntax:
Example:
Caution:
1. The column(s) can be renamed without removing the records.
2. The Data Type and Width of both original and duplicate table fields will
remain the same.
3. The number of column(s) mentioned in both duplicate and original tables
must match.
Example:
Thampy Mathew 26
Oracle Complete – A Quick Reference
SQL
Dropping Multiple columns in One command
Caution:
If multiple columns are dropped in one command the ‘column’ key word should
not be used.
Syntax:
Example:
Example:
Thampy Mathew 27
Oracle Complete – A Quick Reference
SQL
DELETE_RULE VARCHAR2(9),
STATUS VARCHAR2(8),
DEFERRABLE VARCHAR2(14),
DEFERRED VARCHAR2(9),
VALIDATED VARCHAR2(13),
GENERATED VARCHAR2(14),
BAND VARCHAR2(3),
RELY VARCHAR2(4),
LAST_CHANGE DATE
Select Constraint_Name,
Constraint_Type,
Search_Condition
From User_Constraints
Where Table_Name = EMP;
Constraints
Constraints are restrictions imposed on the columns of a table to accept values. The
constraints are always validated at the end of he execution and if any value that violates
the defined constraint is found, Oracle rollback that row automatically.
Primary Key
Unique
Not Null
Check
Foreign Key
Rules of Constraints
1. There can be one and only one Primary Key per table.
2. One column cannot have both Primary Key and unique constraints defined for
it.
3. There can be up to 254 Check constraints defined for one column of a table.
4. There can be Primary Key, Not Null and Check constraints on a particular
column.
Thampy Mathew 28
Oracle Complete – A Quick Reference
SQL
6. There can be up to 254 Unique constraints defined for a table.
Caution:
1. If the key word ‘Constraint’ is used, you should specify a constraint
name. If you don’t want to specify a constraint name, don’t use the key
word ‘Constraint’ while defining constraints at column level or table
level.
Thampy Mathew 29
Oracle Complete – A Quick Reference
SQL
Composite Primary Key
Note:
If the user does not specify a constraint name, system will automatically create a
unique name for each constraint. The system generated constraint names with a
prefix SYS_C.
Thampy Mathew 30
Oracle Complete – A Quick Reference
SQL
Ename Varchar2(20),
Sal Number,
Constraint Emno_UN Unique(Empno));
Note:
If the user does not specify a constraint name, system will automatically create a
unique name for each constraint. The system generated constraint names will start
with the characters SYS.
Not possible.
Not possible.
Thampy Mathew 31
Oracle Complete – A Quick Reference
SQL
The Check Constraint
Check Constraint Definition at Column Level
Note:
While defining check constraint, if another column is to be referenced, the
constraint must be defined at the table level. Referencing another column for
defining a constraint at the column level is not permitted.
Thampy Mathew 32
Oracle Complete – A Quick Reference
SQL
Note:
Deptno column of EMP table will not accept a value that is not present in the
Deptno field of DEPT Table. But it will accept NULL.
Thampy Mathew 33
Oracle Complete – A Quick Reference
SQL
On Delete Cascade Clause on Foreign Key Constraint
If the foreign key is having an ‘On Delete Cascade’ defined in it, when the user deletes
records from the Master table, Oracle automatically deletes the corresponding records
from the child table. (Internally the child records are deleted first and then the Master
records are deleted.)
Caution:
1. While referential integrity constraints are defined for a column of a table, the
referenced column must be of the same data type and width. The referenced
and referencing column names may be different.
2. The referenced column must be a Primary Key or Unique.
This clause of the foreign key constraint can be used to disassociate the referenced
records of a child table from the master records when a Master table is to be dropped
without dropping the child table. Using the Cascade Constraint clause, if the master table
is dropped the child table can remain intact and independent with all its records.
Syntax:
Drop Table <Master Table whose records are referenced by child tables> Cascade
Constraint;
Example:
Thampy Mathew 34
Oracle Complete – A Quick Reference
SQL
Table Level & Column Level Constraints Compared
Sl. Column Level Table Level
1. The constraint is defined in The constraint is defined at the end
continuation to the column after all column definitions
definition
2. Only one column can be made into Composite (Combined) Primary Key
a Primary Key can be created by combining a
maximum of 16 columns
3. Only one column can be made into Composite (Combined) Unique
Unique columns can be created by
combining a maximum of 16
columns
4. Check constraint cannot reference Check constraint can reference
another column. another column of the same table
5. Not Null constraint with or without Not Null constraint cannot be
user specified constraint name can defined.
be defined for any column
Child Table
Deptno Dname
10 Null /* Not Acceptable */
10 QC /* Acceptable */
20 FIN /* Acceptable */
Null PROD /* Not Acceptable */
Thampy Mathew 35
Oracle Complete – A Quick Reference
SQL
Child Table Values
Child Table
Deptno Dname
10 Null /* Aceptable */
10 QC /* Aceptable */
20 FIN /* Aceptable */
Null PROD /* Aceptable */
Thampy Mathew 36
Oracle Complete – A Quick Reference
SQL
Thampy Mathew 37
Oracle Complete – A Quick Reference
SQL
The constraints are fired in the following order if all of them present in a table
1. Not Null
2. Check
3. Primary Key
4. Unique
Disabling Constraints
Syntax:
Example:
Note:
The Constraint_Name must be found out from the User_Constraints table.
Enabling Constraints
Syntax:
Example:
Note:
The Constraint_Name must be found out from the User_Constraints table.
Dropping Constraints
Syntax:
Thampy Mathew 38
Oracle Complete – A Quick Reference
SQL
Example:
Note:
The Constraint_Name must be found out from the User_Constraints table.
SQL*Plus
Set sqlprompt ‘Thampy’
Set Feed Off
Set Feed On
Set Head Off
Set Head On
Set Long10000
Set Linesize 100
Set Autotrace On
Set Autotrace Off
Formatting Reports
Break on Deptno
Break on Deptno Skip1 on Report (One blank row at the end of the report)
The values will not be truncated, but if any value exceeds 6 characters they will go to the
next line.
Thampy Mathew 39
Oracle Complete – A Quick Reference
SQL
Titles
Set Pagesize 30
TTitle Off
BTitle Off
Clear Break
Clear Compute
Column format off
The last executed command always remains in the SQL Buffer. For editing that command
you can either open an editor or you can do so from the SQL prompt as follows.
SQL> L1 (The first line of the last executed command will be redisplayed)
SQL> L2 (The second line of the last executed command will be redisplayed)
SQL> C/Empno/Dname
SQL> C/EMP/DEPT
Thampy Mathew 40
Oracle Complete – A Quick Reference
SQL
Running the Command
SQL> R (Run the command. The command will be ‘Select Dname From DEPT’)
SQL> L2
SQL> C/smith/SMITH
SQL> L2
SQL> C/sm/SM
SQL> L1
Removing Word(s)
SQL> L2
Adding Word(s)
SQL> L2
Thampy Mathew 41
Oracle Complete – A Quick Reference
SQL
Operators
Mathematical Operators
+ - Addition
- - Subtraction
* - Multiplication
/ - Division
Examples:
Thampy Mathew 42
Oracle Complete – A Quick Reference
SQL
Output:
Alex
Output:
Alex
Thomas
Output:
Mathew
Output:
Alex
Thomas
Mathew
Select Ename From EMP Where deptno NOT BETWEEN 10 And 20;
Output:
Mathew
Set Operators
Examples:
Output:
10
20
Thampy Mathew 43
Oracle Complete – A Quick Reference
SQL
30
Select Deptno From DEPT UNION ALL (Select Deptno From EMP);
Output:
10
20
30
10
20
Output:
10
20
Output:
10
AND, OR Conditions
AND
It always check whether all the conditions specified in the select statement using AND
are met before fetching records. Any record that fails to meet any one condition will be
skipped.
OR
It always check whether at least one condition specified in the select statement using OR
is met before fetching records. Any record that meets at least one condition will be
fetched.
Functions
Character Functions
CONCATENATE
Select ‘Mr’||’.’||Ename From EMP;
Output: Mr.Alex Mr.Mathew etc.
Thampy Mathew 44
Oracle Complete – A Quick Reference
SQL
INITCAP (String)
Select INITCAP (cONCOURSE) From Dual;
Output: CONCOURSE
LENGTH (String)
Select LENGTH (Ename) From EMP;
Output: 6 (The length of the longest name the EMP Table)
LOWER (String)
Select LOWER (‘ABC’) From EMP;
Output: abc
UPPER (String)
Select UPPER (‘abc’) From EMP;
Output: ABC
SOUNDEX (String)
Select Ename From EMP Where SOUNDEX (Ename) = SOUNDEX (Smyth);
Output: SMITH
Thampy Mathew 45
Oracle Complete – A Quick Reference
SQL
Select INSTR (‘Smith’, ‘t’) From Dual;
Output: 4
ASCII (Value)
Select ASCII (65) From Dual;
Output: A
Select ASCII (‘A’) From Dual;
Output: 65
Select ASCII (‘a’) From Dual;
Output: 97
Select ASCII (‘AMIT’) From Dual;
Output: 65
Select ASCII (‘aMIT’) From Dual;
Output: 97
CHR (Value)
Select CHR (65) From Dual;
Output: A
Select CHR (‘65’) From Dual;
Output: A
USER
Select USER From Dual;
Output: SCOTT
Order of Firing
SUBSTR(‘AMIT’, 2, 3) = MIT
LPAD(‘MIT’, 4, ‘S’) = SMIT
RPAD(‘SMIT’, 5, ‘H’) = SMITH
Number Functions
ABC (Value)
Select ABS (-12) From Dual;
Thampy Mathew 46
Oracle Complete – A Quick Reference
SQL
Output: 12
FLOOR (Value)
Select FLOOR (14.6) From Dual;
Output: 14
Select FLOOR (-14.3) From Dual;
Output: 15
SQRT (Value)
Select SQRT (100) From Dual;
Output: 10
SIGN (Value)
Select SIGN (100) From Dual;
Output: 1
Select SIGN (-100) From Dual;
Output: -1
Select SIGN (0) From Dual;
Output: 0
Thampy Mathew 47
Oracle Complete – A Quick Reference
SQL
used, the Sal of all those employees whose Comm field is null will
not be displayed at all
Group Functions
SUM (Value)
Select SUM (Sal) From EMP;
Output: Total of the Sal Column of EMP table
SUM (Value)
Select SUM (Sal + Comm) From EMP;
Output: Total of the Sal + Comm - Records with null values in Comm
field will be omitted.
MIN (Value)
Select MIN (Sal), MIN(Ename) From EMP;
Output:
MAX (Value)
Select MAX (Sal), MAX(Ename) From EMP;
Output:
AVG (Value)
Select AVG (Sal) From EMP;
Output: Average of the salary
Select AVG (Comm) From EMP;
Output: Average of the Comm column excluding null fields
Select AVG (NVL(Comm, 0)) From EMP;
Output: Average of the Comm column including null fields
COUNT (Value)
Select COUNT (*), COUNT (Comm), COUNT (NVL(Comm, 0)) From EMP;
Output: No. of total records, No. of records in Comm column without Null
and No. of records in Comm column (with and without null)
Thampy Mathew 48
Oracle Complete – A Quick Reference
SQL
Date Functions
The Full Date Format
'DD-MON-YYYY HH:MI:SS'
'DD-MON-YYYY HH12:MI:SS'
'DD-MON-YYYY HH24:MI:SS'
NEXT_DAY (Date, Day) Date of the mentioned day in the next week
Select NEXT_DAY (Sysdate, ‘Friday’) From Dual;
Output: 03-NOV-99 The command is executed on 25-NOV-99
Time Zones
Thampy Mathew 49
Oracle Complete – A Quick Reference
SQL
MST Mountain Standard Time
MDT Mountain Daylight Time
Conversion Functions
TO_NUMBER (From Date, To Date)
Select TO_NUMBER (‘12’) From Dual;
Output: 12 The numeric 12
Thampy Mathew 50
Oracle Complete – A Quick Reference
SQL
Output: Thursday-november-ninteen ninty nine
TO_DATE converts the input value into a date value. ‘Day’ extracts the day value
from the date value and TO_CHAR converts the day value into characters and
displayed.
The below given format strings will not work with TO_DATE
Fm Without fm the Month and Day will be displayed in the same width. With
fm Months and Days are only as long as their count of characters.
Fx Specifies exact format matching for the character argument and the date
format model.
Thampy Mathew 51
Oracle Complete – A Quick Reference
SQL
comes from the number-DD- no fro the case of SP. Works with any
number in a date. YYYY, DD, MM, HH, MI, SS and so on.
Output: July 9
Output: July 4
Output: Sunday 9
Output: Sunday 6
Date in Words
Select TO_CHAR(Sysdate, 'year') From Dual;
Output: two thousand three
Thampy Mathew 52
Oracle Complete – A Quick Reference
SQL
Output: july
Use of TH in TO_CHAR
Use of SP in TO_CHAR
Thampy Mathew 53
Oracle Complete – A Quick Reference
SQL
Output: Twenty-Third-July -Two Thousand Three
Formats
cc, scc - rounds to January 1st of next century
Rounding To Century
Rounding To Year
Thampy Mathew 54
Oracle Complete – A Quick Reference
SQL
Select ROUND(TO_DATE('25/JUL/2050 8:15:00 a.m.'), 'Year') From Dual;
Output: 01-JAN-2051 12:00:00
Rounding To Quarter
Rounding To Month
Thampy Mathew 55
Oracle Complete – A Quick Reference
SQL
Wednesday to Wednesday Week in which the input date falls is
16-JUL-2003 to 23-JUL-2003.
16-JUL-2003 is the Nearer Wednesday of the week for the input date of
19-JUL-2003 and so is the Output.
Rounding To Day
Thampy Mathew 56
Oracle Complete – A Quick Reference
SQL
Output: 12-FEB-2050 12:00:00
Rounding To Hour
Rounding To Minute
Formats
Thampy Mathew 57
Oracle Complete – A Quick Reference
SQL
ww - truncates to the closest Monday
Truncating To Century
Truncating To Year
Truncating To Quarter
Truncating To Month
Thampy Mathew 58
Oracle Complete – A Quick Reference
SQL
Select TRUNC(TO_DATE('22/MAR/2003 15:30:00'), 'Month') From Dual;
Output: 01-MAR-2003 00:00:00
Thampy Mathew 59
Oracle Complete – A Quick Reference
SQL
Truncating to Day
Truncating To Hour
Truncating To Minute
Date Calculations
Select Sysdate + 1 From Dual;
Output: Tomorrow’s date
Thampy Mathew 60
Oracle Complete – A Quick Reference
SQL
Select Sysdate - 1 From Dual;
Output: Yesterday’s date
Transormation Functions
DECODE (Value, If 1, Then 1, If 2. Then 2,……If n, Then n)
Select DECODE (Ename, NULL, ‘No Name’) From EMP;
Thampy Mathew 61
Oracle Complete – A Quick Reference
SQL
Pseudocolumns
ROWID
ROWMUM
LEVEL
NEXTVAL
CURRVAL
ROWID
It is independent of tables. When a record is inserted into a table Oracle will attach a
ROWID to the Data Segment. A ROWID is constituted of 3 segments as follows.
ROWID will be unique for each record irrespective of the Table in which it belongs.
Segment Represents
1 Block (Table) – where the record is physically present
2 Data File Name – where the Data Segment is present
3 Row Number
Example:
AAAFBtAADAABNwAAA
ROWMUM
Rownum is generated only when a select statement starts fetching records. The
ROWNUM values are never saved to the database.
Select Rownum, Ename from EMP where Rownum = 1 - (It will work)
Select Rownum, Ename from EMP where Rownum = 2 - (It will not work)
Select Rownum, Ename from EMP where Rownum < 1 - (It will work)
Select Rownum, Ename from EMP where Rownum > 1 - (It will work)
Thampy Mathew 62
Oracle Complete – A Quick Reference
SQL
LEVEL
NEXTVAL
CURRVAL
Queries
Simple Queries
Thampy Mathew 63
Oracle Complete – A Quick Reference
SQL
Records in DEPT Table
Output:
EMPNOENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------------------- ------- ----- --------- ------- ----- --------- ------------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
Thampy Mathew 64
Oracle Complete – A Quick Reference
SQL
Select Ename From EMP;
Output:
ENAME
-------
SMITH
ALLEN
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
Output:
ENAME SAL
---------- ---------
SMITH 800
ALLEN 1600
JONES 2975
MARTIN 1250
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
TURNER 1500
ADAMS 1100
JAMES 950
FORD 3000
Output:
SAL ENAME
------ ----------
800 SMITH
Thampy Mathew 65
Oracle Complete – A Quick Reference
SQL
1600 ALLEN
2975 JONES
1250 MARTIN
2850 BLAKE
2450 CLARK
3000 SCOTT
5000 KING
1500 TURNER
1100 ADAMS
950 JAMES
3000 FORD
Conditional Output
Output:
no rows selected
Note:
The strings James and JAMES are different for SQL.
Output:
ENAME SAL
---------- ---------
JAMES 950
Output:
no rows selected
Using LIKE
Thampy Mathew 66
Oracle Complete – A Quick Reference
SQL
Where Ename Like 'JA%';
Output:
ENAME SAL
---------- ---------
JAMES 950
Output:
ENAME SAL
---------- ---------
MARTIN 1250
CLARK 2450
Output:
ENAME SAL
---------- ---------
JONES 2975
JAMES 950
Output:
ENAME SAL
---------- ---------
BLAKE 2850
CLARK 2450
Thampy Mathew 67
Oracle Complete – A Quick Reference
SQL
Output:
ENAME SAL
---------- ---------
SMITH 800
ALLEN 1600
JONES 2975
MARTIN 1250
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
TURNER 1500
ADAMS 1100
FORD 3000
Output:
ENAME SAL
---------- ---------
SMITH 800
JONES 2975
SCOTT 3000
KING 5000
TURNER 1500
FORD 3000
Note:
No records selected where Ename having an A in it.
Output:
ENAME SAL
---------- ---------
SMITH 800
ALLEN 1600
Thampy Mathew 68
Oracle Complete – A Quick Reference
SQL
JONES 2975
MARTIN 1250
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
TURNER 1500
ADAMS 1100
FORD 3000
Note:
JAMES is excluded from the output.
Output:
ENAME SAL
---------- ---------
JONES 2975
BLAKE 2850
SCOTT 3000
KING 5000
FORD 3000
Note:
Record with Sal = 2450 is not included.
Output:
ENAME SAL
---------- ---------
JONES 2975
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
FORD 3000
Note:
Record with Sal = 2450 is included.
Thampy Mathew 69
Oracle Complete – A Quick Reference
SQL
Select Ename, Sal
From EMP
Where Sal < 2450;
Output:
ENAME SAL
---------- ---------
SMITH 800
ALLEN 1600
MARTIN 1250
TURNER 1500
ADAMS 1100
JAMES 950
Note:
Record with Sal = 2450 is not included.
Output:
ENAME SAL
---------- ---------
SMITH 800
ALLEN 1600
MARTIN 1250
CLARK 2450
TURNER 1500
ADAMS 1100
JAMES 950
Note:
Record with Sal = 2450 is included.
Using BETWEEN
Output:
ENAME SAL
---------- ---------
ALLEN 1600
MARTIN 1250
Thampy Mathew 70
Oracle Complete – A Quick Reference
SQL
CLARK 2450
TURNER 1500
Note:
Records with Sal = 1250 and 2450 are included.
Output:
ENAME SAL
---------- ---------
SMITH 800
JONES 2975
BLAKE 2850
SCOTT 3000
KING 5000
ADAMS 1100
JAMES 950
FORD 3000
Note:
Records with Sal = 1250 and 2450 are also excluded.
Output:
ENAME SAL
---------- ---------
ALLEN 1600
MARTIN 1250
CLARK 2450
TURNER 1500
Thampy Mathew 71
Oracle Complete – A Quick Reference
SQL
Using Aliases for Column Names
Output:
EMPLOYEE SALARY DOUBLE
---------- --------- ---------
SMITH 800 1600
Note:
Notice that the column names are replaced with the aliases in the output.
Output:
ENAME SAL SIGN_HERE
---------- --------- ------------
SMITH 800 ------------
ALLEN 1600 ------------
JONES 2975 ------------
MARTIN 1250 ------------
BLAKE 2850 ------------
CLARK 2450 ------------
SCOTT 3000 ------------
KING 5000 ------------
TURNER 1500 ------------
ADAMS 1100 ------------
JAMES 950 ------------
FORD 3000 ------------
Caution:
Do not use spaces in Aliases and do not insert coma between the field name and
the alias.
Thampy Mathew 72
Oracle Complete – A Quick Reference
SQL
Where Ename = '&Name';
Output:
Enter value for name: CLARK
old 2: From EMP Where Ename = '&Name'
new 2: From EMP Where Ename = 'CLARK'
Note:
When the query is executed, the system asked
Enter value for name:
The user entered the value CLARK
Then the output is shown.
Output:
ENAME SAL HALF
---------- ------- ---------
SMITH 800 400
Multiple Conditions
Using AND
Output:
no rows selected
Thampy Mathew 73
Oracle Complete – A Quick Reference
SQL
Output:
ENAME SAL
---------- ---------
SMITH 800
Using OR
Output:
ENAME SAL
---------- ---------
SMITH 800
Output:
ENAME SAL
---------- ---------
SMITH 800
CLARK 2450
Using IN
Output:
ENAME HIREDATE
--------- ---------
SMITH 17-DEC-80
JONES 02-APR-81
CLARK 09-JUN-81
Thampy Mathew 74
Oracle Complete – A Quick Reference
SQL
Using NOT IN
Output:
ENAME HIREDATE
---------- ---------
ALLEN 20-FEB-81
MARTIN 28-SEP-81
BLAKE 01-MAY-81
SCOTT 19-APR-87
KING 17-NOV-81
TURNER 08-SEP-81
ADAMS 23-MAY-87
JAMES 03-DEC-81
FORD 03-DEC-81
Note:
SMITH, JONES and CLARK are excluded.
Using ANY
Output:
ENAME HIREDATE
---------- ---------
SMITH 17-DEC-80
JONES 02-APR-81
CLARK 09-JUN-81
Output:
ENAME SAL
---------- ---------
ALLEN 1600
JONES 2975
Thampy Mathew 75
Oracle Complete – A Quick Reference
SQL
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
FORD 3000
Output:
ERROR Missing Expression.
Output:
MGR ENAME
---- -------
7566 FORD
7566 SCOTT
7698 ALLEN
7698 JAMES
7698 MARTIN
7698 TURNER
7788 ADAMS
7839 BLAKE
7839 CLARK
7839 JONES
7902 SMITH
KING
Output:
MGR
-----
7566
7698
7788
7839
7902
Thampy Mathew 76
Oracle Complete – A Quick Reference
SQL
Managing NULLS
Output:
ENAME TOTAL
---------- ---------
SMITH
ALLEN 1900
JONES
MARTIN 2650
BLAKE
CLARK
SCOTT
KING
TURNER 1500
ADAMS
JAMES
FORD
Note:
When NULL is added to any value produces a NULL.
Output:
ENAME TOTAL
---------- ---------
SMITH 800
ALLEN 1900
JONES 2975
MARTIN 2650
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
TURNER 1500
ADAMS 1100
JAMES 950
FORD 3000
Thampy Mathew 77
Oracle Complete – A Quick Reference
SQL
Note:
The NULLs are substituted with 0 and added to Sal.
Formatting Dates
Output:
ENAME HIREDATE FULL_YEAR
---------- --------- -----------
SMITH 17-DEC-80 17-DEC-1980
ALLEN 20-FEB-81 20-FEB-1981
JONES 02-APR-81 02-APR-1981
MARTIN 28-SEP-81 28-SEP-1981
BLAKE 01-MAY-81 01-MAY-1981
CLARK 09-JUN-81 09-JUN-1981
SCOTT 19-APR-87 19-APR-1987
KING 17-NOV-81 17-NOV-1981
TURNER 08-SEP-81 08-SEP-1981
ADAMS 23-MAY-87 23-MAY-1987
JAMES 03-DEC-81 03-DEC-1981
FORD 03-DEC-81 03-DEC-1981
Output:
ENAME HIREDATE DATE_WITH_TIME
---------- --------- --------------------
SMITH 17-DEC-80 17-DEC-1980 12:00:00
ALLEN 20-FEB-81 20-FEB-1981 12:00:00
JONES 02-APR-81 02-APR-1981 12:00:00
MARTIN 28-SEP-81 28-SEP-1981 12:00:00
BLAKE 01-MAY-81 01-MAY-1981 12:00:00
CLARK 09-JUN-81 09-JUN-1981 12:00:00
SCOTT 19-APR-87 19-APR-1987 12:00:00
KING 17-NOV-81 17-NOV-1981 12:00:00
TURNER 08-SEP-81 08-SEP-1981 12:00:00
ADAMS 23-MAY-87 23-MAY-1987 12:00:00
JAMES 03-DEC-81 03-DEC-1981 12:00:00
FORD 03-DEC-81 03-DEC-1981 12:00:00
Thampy Mathew 78
Oracle Complete – A Quick Reference
SQL
Select Ename, Hiredate,
TO_CHAR (Hiredate, 'DD-MON-YYYY HH12:MI:SS') TIME_IN_12HR_FORMAT
From EMP;
Output:
ENAME HIREDATE TIME_IN_12HR_FORMAT
---------- --------- --------------------
SMITH 17-DEC-80 17-DEC-1980 12:00:00
ALLEN 20-FEB-81 20-FEB-1981 12:00:00
JONES 02-APR-81 02-APR-1981 12:00:00
MARTIN 28-SEP-81 28-SEP-1981 12:00:00
BLAKE 01-MAY-81 01-MAY-1981 12:00:00
CLARK 09-JUN-81 09-JUN-1981 12:00:00
SCOTT 19-APR-87 19-APR-1987 12:00:00
KING 17-NOV-81 17-NOV-1981 12:00:00
TURNER 08-SEP-81 08-SEP-1981 12:00:00
ADAMS 23-MAY-87 23-MAY-1987 12:00:00
JAMES 03-DEC-81 03-DEC-1981 12:00:00
FORD 03-DEC-81 03-DEC-1981 12:00:00
Output:
ENAME HIREDATE TIME_IN_24HR_FORMAT
---------- --------- --------------------
SMITH 17-DEC-80 17-DEC-1980 12:00:00
ALLEN 20-FEB-81 20-FEB-1981 12:00:00
JONES 02-APR-81 02-APR-1981 12:00:00
MARTIN 28-SEP-81 28-SEP-1981 12:00:00
BLAKE 01-MAY-81 01-MAY-1981 12:00:00
CLARK 09-JUN-81 09-JUN-1981 12:00:00
SCOTT 19-APR-87 19-APR-1987 12:00:00
KING 17-NOV-81 17-NOV-1981 12:00:00
TURNER 08-SEP-81 08-SEP-1981 12:00:00
ADAMS 23-MAY-87 23-MAY-1987 12:00:00
JAMES 03-DEC-81 03-DEC-1981 12:00:00
FORD 03-DEC-81 03-DEC-1981 12:00:00
Thampy Mathew 79
Oracle Complete – A Quick Reference
SQL
Select Ename, Hiredate,
TO_CHAR (Hiredate, 'DD-MON-YYYY HH24:MI:SS pm')
TIME_IN_24HR_FORMAT
From EMP;
Output:
ENAME HIREDATE TIME_IN_12HR_FORMAT
---------- --------- --------------------
SMITH 17-DEC-80 17-DEC-1980 12:00:00 am
ALLEN 20-FEB-81 20-FEB-1981 12:00:00 am
JONES 02-APR-81 02-APR-1981 12:00:00 am
MARTIN 28-SEP-81 28-SEP-1981 12:00:00 am
BLAKE 01-MAY-81 01-MAY-1981 12:00:00 am
CLARK 09-JUN-81 09-JUN-1981 12:00:00 am
SCOTT 19-APR-87 19-APR-1987 12:00:00 am
KING 17-NOV-81 17-NOV-1981 12:00:00 am
TURNER 08-SEP-81 08-SEP-1981 12:00:00 am
ADAMS 23-MAY-87 23-MAY-1987 12:00:00 am
JAMES 03-DEC-81 03-DEC-1981 12:00:00 am
FORD 03-DEC-81 03-DEC-1981 12:00:00 am
Output:
ENAME HIREDATE TIME_IN_12HR_FORMAT
---------- --------- --------------------
SMITH 17-DEC-80 17-DEC-1980 12:00:00 am
ALLEN 20-FEB-81 20-FEB-1981 12:00:00 am
JONES 02-APR-81 02-APR-1981 12:00:00 am
MARTIN 28-SEP-81 28-SEP-1981 12:00:00 am
BLAKE 01-MAY-81 01-MAY-1981 12:00:00 am
CLARK 09-JUN-81 09-JUN-1981 12:00:00 am
SCOTT 19-APR-87 19-APR-1987 12:00:00 am
KING 17-NOV-81 17-NOV-1981 12:00:00 am
TURNER 08-SEP-81 08-SEP-1981 12:00:00 am
ADAMS 23-MAY-87 23-MAY-1987 12:00:00 am
JAMES 03-DEC-81 03-DEC-1981 12:00:00 am
FORD 03-DEC-81 03-DEC-1981 12:00:00 am
Thampy Mathew 80
Oracle Complete – A Quick Reference
SQL
Note:
Notice that with am and pm the Output is shown as am only because am is the
value present in the database.
Output:
ENAME HIREDATE TIME_IN_12HR_FORMAT
---------- --------- --------------------
SMITH 17-DEC-80 17-DEC-1980 12:00:00 A.M.
ALLEN 20-FEB-81 20-FEB-1981 12:00:00 A.M.
JONES 02-APR-81 02-APR-1981 12:00:00 A.M.
MARTIN 28-SEP-81 28-SEP-1981 12:00:00 A.M.
BLAKE 01-MAY-81 01-MAY-1981 12:00:00 A.M.
CLARK 09-JUN-81 09-JUN-1981 12:00:00 A.M.
SCOTT 19-APR-87 19-APR-1987 12:00:00 A.M.
KING 17-NOV-81 17-NOV-1981 12:00:00 A.M.
TURNER 08-SEP-81 08-SEP-1981 12:00:00 A.M.
ADAMS 23-MAY-87 23-MAY-1987 12:00:00 A.M.
JAMES 03-DEC-81 03-DEC-1981 12:00:00 A.M.
FORD 03-DEC-81 03-DEC-1981 12:00:00 A.M.
Output:
ENAME HIREDATE YEAR_IN_WORDS
---------- --------- --------------
SMITH 17-DEC-80 EIGHTY
ALLEN 20-FEB-81 EIGHTY-ONE
JONES 02-APR-81 EIGHTY-ONE
MARTIN 28-SEP-81 EIGHTY-ONE
BLAKE 01-MAY-81 EIGHTY-ONE
CLARK 09-JUN-81 EIGHTY-ONE
SCOTT 19-APR-87 EIGHTY-SEVEN
KING 17-NOV-81 EIGHTY-ONE
TURNER 08-SEP-81 EIGHTY-ONE
ADAMS 23-MAY-87 EIGHTY-SEVEN
JAMES 03-DEC-81 EIGHTY-ONE
FORD 03-DEC-81 EIGHTY-ONE
Thampy Mathew 81
Oracle Complete – A Quick Reference
SQL
Select Ename, Hiredate,
TO_CHAR (TO_DATE (Hiredate, 'DD-MON-YYYY'), 'Year') Year_In_Words
From EMP;
Output:
ENAME HIREDATE YEAR_IN_WORDS
---------- --------- -------------
SMITH 17-DEC-80 Eighty
ALLEN 20-FEB-81 Eighty-One
JONES 02-APR-81 Eighty-One
MARTIN 28-SEP-81 Eighty-One
BLAKE 01-MAY-81 Eighty-One
CLARK 09-JUN-81 Eighty-One
SCOTT 19-APR-87 Eighty-Seven
KING 17-NOV-81 Eighty-One
TURNER 08-SEP-81 Eighty-One
ADAMS 23-MAY-87 Eighty-Seven
JAMES 03-DEC-81 Eighty-One
FORD 03-DEC-81 Eighty-One
Output:
ENAME HIREDATE MONTH
---------- --------- ---------
SMITH 17-DEC-80 DECEMBER
ALLEN 20-FEB-81 FEBRUARY
JONES 02-APR-81 APRIL
MARTIN 28-SEP-81 SEPTEMBER
BLAKE 01-MAY-81 MAY
CLARK 09-JUN-81 JUNE
SCOTT 19-APR-87 APRIL
KING 17-NOV-81 NOVEMBER
TURNER 08-SEP-81 SEPTEMBER
ADAMS 23-MAY-87 MAY
JAMES 03-DEC-81 DECEMBER
FORD 03-DEC-81 DECEMBER
Thampy Mathew 82
Oracle Complete – A Quick Reference
SQL
Select Ename, Hiredate,
TO_CHAR (TO_DATE (Hiredate, 'DD-MON-YYYY'), 'Month') Month
From EMP;
Output:
ENAME HIREDATE MONTH
---------- --------- ---------
SMITH 17-DEC-80 December
ALLEN 20-FEB-81 February
JONES 02-APR-81 April
MARTIN 28-SEP-81 September
BLAKE 01-MAY-81 May
CLARK 09-JUN-81 June
SCOTT 19-APR-87 April
KING 17-NOV-81 November
TURNER 08-SEP-81 September
ADAMS 23-MAY-87 May
JAMES 03-DEC-81 December
FORD 03-DEC-81 December
Output:
ENAME HIREDATE DAY
---------- --------- ---------
SMITH 17-DEC-80 SUNDAY
ALLEN 20-FEB-81 TUESDAY
JONES 02-APR-81 MONDAY
MARTIN 28-SEP-81 FRIDAY
BLAKE 01-MAY-81 TUESDAY
CLARK 09-JUN-81 SATURDAY
SCOTT 19-APR-87 THURSDAY
KING 17-NOV-81 SATURDAY
TURNER 08-SEP-81 SATURDAY
ADAMS 23-MAY-87 WEDNESDAY
JAMES 03-DEC-81 MONDAY
FORD 03-DEC-81 MONDAY
Thampy Mathew 83
Oracle Complete – A Quick Reference
SQL
Output:
ENAME HIREDATE DAY
---------- --------- ---------
SMITH 17-DEC-80 Sunday
ALLEN 20-FEB-81 Tuesday
JONES 02-APR-81 Monday
MARTIN 28-SEP-81 Friday
BLAKE 01-MAY-81 Tuesday
CLARK 09-JUN-81 Saturday
SCOTT 19-APR-87 Thursday
KING 17-NOV-81 Saturday
TURNER 08-SEP-81 Saturday
ADAMS 23-MAY-87 Wednesday
JAMES 03-DEC-81 Monday
FORD 03-DEC-81 Monday
Output:
ENAME HIREDATE DATE_IN_WORDS
---------- --------- --------------------------------------------
SMITH 17-DEC-80 Seventeenth-December -Nineteen Eighty
ALLEN 20-FEB-81 Twentieth-February -Nineteen Eighty-One
JONES 02-APR-81 Second-April -Nineteen Eighty-One
MARTIN 28-SEP-81 Twenty-Eighth-September-Nineteen Eighty-One
BLAKE 01-MAY-81 First-May -Nineteen Eighty-One
CLARK 09-JUN-81 Ninth-June -Nineteen Eighty-One
SCOTT 19-APR-87 Nineteenth-April -Nineteen Eighty-Seven
KING 17-NOV-81 Seventeenth-November -Nineteen Eighty-One
TURNER 08-SEP-81 Eighth-September-Nineteen Eighty-One
ADAMS 23-MAY-87 Twenty-Third-May -Nineteen Eighty-Seven
JAMES 03-DEC-81 Third-December -Nineteen Eighty-One
FORD 03-DEC-81 Third-December -Nineteen Eighty-One
Note:
There are unwanted spaces between month and year. The query given below will
remove those spaces.
Thampy Mathew 84
Oracle Complete – A Quick Reference
SQL
Select Ename, Hiredate,
TO_CHAR (Hiredate, 'DdSPTH-fmMonth-Year') Date_In_Words
From EMP;
Output:
ENAME HIREDATE DATE_IN_WORDS
---------- --------- --------------------------------------------
SMITH 17-DEC-80 Seventeenth-December-Nineteen Eighty
ALLEN 20-FEB-81 Twentieth-February-Nineteen Eighty-One
JONES 02-APR-81 Second-April-Nineteen Eighty-One
MARTIN 28-SEP-81 Twenty-Eighth-September-Nineteen Eighty-One
BLAKE 01-MAY-81 First-May-Nineteen Eighty-One
CLARK 09-JUN-81 Ninth-June-Nineteen Eighty-One
SCOTT 19-APR-87 Nineteenth-April-Nineteen Eighty-Seven
KING 17-NOV-81 Seventeenth-November-Nineteen Eighty-One
TURNER 08-SEP-81 Eighth-September-Nineteen Eighty-One
ADAMS 23-MAY-87 Twenty-Third-May-Nineteen Eighty-Seven
JAMES 03-DEC-81 Third-December-Nineteen Eighty-One
FORD 03-DEC-81 Third-December-Nineteen Eighty-One
Note:
The unwanted spaces between month and year are removed by using fmMonth in
the query.
Comparing Dates
Output:
ENAME HIREDATE
---------- ---------
SMITH 17-DEC-80
ALLEN 20-FEB-81
MARTIN 28-SEP-81
CLARK 09-JUN-81
SCOTT 19-APR-87
KING 17-NOV-81
TURNER 08-SEP-81
ADAMS 23-MAY-87
Thampy Mathew 85
Oracle Complete – A Quick Reference
SQL
Using DECODE
Output:
ENAME SAL COMM
---------- ------- -----------
SMITH 800 Null
ALLEN 1600 Value Found
JONES 2975 Null
MARTIN 1250 Value Found
BLAKE 2850 Null
CLARK 2450 Null
SCOTT 3000 Null
KING 5000 Null
TURNER 1500 Value Found
ADAMS 1100 Null
JAMES 950 Null
FORD 3000 Null
Output:
ENAME SAL COMM
---------- ------- ---------------
SMITH 800 Value Not Found
ALLEN 1600 Value Found
JONES 2975 Value Not Found
MARTIN 1250 Value Found
BLAKE 2850 Value Not Found
CLARK 2450 Value Not Found
SCOTT 3000 Value Not Found
KING 5000 Value Not Found
TURNER 1500 Value Found
ADAMS 1100 Value Not Found
JAMES 950 Value Not Found
FORD 3000 Value Not Found
Thampy Mathew 86
Oracle Complete – A Quick Reference
SQL
Select Ename, Sal,
DECODE (Comm, Null, 'Value Not Found', 0, 'Value Zero') Comm
From EMP;
Output:
ENAME SAL COMM
---------- ------- ---------------
SMITH 800 Value Not Found
ALLEN 1600
JONES 2975 Value Not Found
MARTIN 1250
BLAKE 2850 Value Not Found
CLARK 2450 Value Not Found
SCOTT 3000 Value Not Found
KING 5000 Value Not Found
TURNER 1500 Value Zero
ADAMS 1100 Value Not Found
JAMES 950 Value Not Found
FORD 3000 Value Not Found
Output:
ENAME SAL COMM
---------- ------- ---------------
SMITH 800 Value Not Found
ALLEN 1600 Positive Value
JONES 2975 Value Not Found
MARTIN 1250 Positive Value
BLAKE 2850 Value Not Found
CLARK 2450 Value Not Found
SCOTT 3000 Value Not Found
KING 5000 Value Not Found
TURNER 1500 Value Zero
ADAMS 1100 Value Not Found
JAMES 950 Value Not Found
FORD 3000 Value Not Found
Thampy Mathew 87
Oracle Complete – A Quick Reference
SQL
Using DECODE with MOD
Output:
ROWNUM LINE HIREDATE SAL
------- ------ -------- ---------
1 17-DEC-80 800
2 20-FEB-81 1600
3 02-APR-81 2975
5 5 01-MAY-81 2850
6 09-JUN-81 2450
9 08-SEP-81 1500
4 28-SEP-81 1250
8 17-NOV-81 5000
11 03-DEC-81 950
12 03-DEC-81 3000
7 19-APR-87 3000
10 10 23-MAY-87 1100
Select Ename,
TRUNC ((Sysdate - HireDate) / 365) Years,
DECODE (TRUNC ((Sysdate - HireDate) / 365), 0, Sal, NULL) As This_Year,
DECODE (TRUNC ((Sysdate - HireDate) / 365), 16, Sal, NULL) As Sixteen_Years,
DECODE (TRUNC ((Sysdate - HireDate) / 365), 21, Sal, NULL) As Twenty1Years,
DECODE (TRUNC ((Sysdate - HireDate) / 365), 22, Sal, NULL) As Twenty2Years
From EMP
Order By TRUNC ((Sysdate - HireDate) / 365);
Output:
ENAME YEARS THIS_YEAR SIXTEEN_YEARS 21YEARS 22YEARS
---------- -------- --------- ------------- ---------- ---------
---
SCOTT 16 3000
ADAMS 16 1100
MARTIN 21 1250
JAMES 21 950
KING 21 5000
TURNER 21 1500
FORD 21 3000
Thampy Mathew 88
Oracle Complete – A Quick Reference
SQL
SMITH 22 800
ALLEN 22 1600
CLARK 22 2450
BLAKE 22 2850
JONES 22 2975
Output:
ENAME SAL SALARY_IN_WORDS
---------- ------ --------------------------------------
SMITH 800 EIGHT HUNDRED
ALLEN 1600 ONE THOUSAND SIX HUNDRED
JONES 2975 TWO THOUSAND NINE HUNDRED SEVENTY-FIVE
MARTIN 1250 ONE THOUSAND TWO HUNDRED FIFTY
BLAKE 2850 TWO THOUSAND EIGHT HUNDRED FIFTY
CLARK 2450 TWO THOUSAND FOUR HUNDRED FIFTY
SCOTT 3000 THREE THOUSAND
KING 5000 FIVE THOUSAND
TURNER 1500 ONE THOUSAND FIVE HUNDRED
ADAMS 1100 ONE THOUSAND ONE HUNDRED
JAMES 950 NINE HUNDRED FIFTY
FORD 3000 THREE THOUSAND
Output:
ENAME SAL SALARY_IN_WORDS
---------- ------ --------------------------------------
SMITH 800 Eight Hundred
ALLEN 1600 One Thousand Six Hundred
JONES 2975 Two Thousand Nine Hundred Seventy-Five
MARTIN 1250 One Thousand Two Hundred Fifty
BLAKE 2850 Two Thousand Eight Hundred Fifty
CLARK 2450 Two Thousand Four Hundred Fifty
SCOTT 3000 Three Thousand
KING 5000 Five Thousand
TURNER 1500 One Thousand Five Hundred
Thampy Mathew 89
Oracle Complete – A Quick Reference
SQL
ADAMS 1100 One Thousand One Hundred
JAMES 950 Nine Hundred Fifty
FORD 3000 Three Thousand
Output:
NAME SALARY SALARY_IN_WORDS
----- ------- --------------------------------------------------
SMITH Rs.800 Rupees Eight Hundred Only
ALLEN Rs.1600 Rupees One Thousand Six Hundred Only
JONES Rs.2975 Rupees Two Thousand Nine Hundred Seventy-Five Only
MARTI Rs.1250 Rupees One Thousand Two Hundred Fifty Only
BLAKE Rs.2850 Rupees Two Thousand Eight Hundred Fifty Only
CLARK Rs.2450 Rupees Two Thousand Four Hundred Fifty Only
SCOTT Rs.3000 Rupees Three Thousand Only
KING Rs.5000 Rupees Five Thousand Only
TURNE Rs.1500 Rupees One Thousand Five Hundred Only
ADAMS Rs.1100 Rupees One Thousand One Hundred Only
JAMES Rs.950 Rupees Nine Hundred Fifty Only
FORD Rs.3000 Rupees Three Thousand Only
Output:
ENAME HIREDATE MGR
---------- --------- ---------
ADAMS 23-MAY-87 7788
ALLEN 20-FEB-81 7698
BLAKE 01-MAY-81 7839
CLARK 09-JUN-81 7839
FORD 03-DEC-81 7566
JAMES 03-DEC-81 7698
JONES 02-APR-81 7839
KING 17-NOV-81
Thampy Mathew 90
Oracle Complete – A Quick Reference
SQL
MARTIN 28-SEP-81 7698
SCOTT 19-APR-87 7566
SMITH 17-DEC-80 7902
TURNER 08-SEP-81 7698
Output:
ENAME HIREDATE MGR
---------- --------- ---------
FORD 03-DEC-81 7566
SCOTT 19-APR-87 7566
ALLEN 20-FEB-81 7698
JAMES 03-DEC-81 7698
MARTIN 28-SEP-81 7698
TURNER 08-SEP-81 7698
ADAMS 23-MAY-87 7788
BLAKE 01-MAY-81 7839
CLARK 09-JUN-81 7839
JONES 02-APR-81 7839
SMITH 17-DEC-80 7902
KING 17-NOV-81
Output:
DEPTNO COUNT(ENAME)
------- ------------
10 2
20 5
30 5
Thampy Mathew 91
Oracle Complete – A Quick Reference
SQL
Output:
DEPTNO COUNT(ENAME)
------ ------------
20 5
30 5
Note:
The HAVING Clause works very much like a WHERE clause except that its logic
is only related to the results of group functions, as opposed to columns or
expressions for individual rows, which can still be selected by a WHERE clause.
Output:
DEPTNO TOT_STAFF TOT_PAY
------ --------- ---------
10 2 7450
20 5 10875
Caution:
If a group function like SUM, COUNT, AVG etc. is used in the SELECT
statement, GROUP BY clause must be added.
Note:
The GROUPING function will return a value of 1 if the column's value is
generated by a ROLLUP. The DECODE function converts this into a value of
'All Depts'.
Thampy Mathew 92
Oracle Complete – A Quick Reference
SQL
Output:
DEPTNO LOC ENAME SAL
----------- ------------- ---------- ---------
10 NEW YORK CLARK 2450
10 NEW YORK KING 5000
20 DALLAS SMITH 800
20 DALLAS SCOTT 3000
20 DALLAS JONES 2975
20 DALLAS ADAMS 1100
20 DALLAS FORD 3000
30 CHICAGO ALLEN 1600
30 CHICAGO MARTIN 1250
30 CHICAGO TURNER 1500
30 CHICAGO JAMES 950
30 CHICAGO BLAKE 2850
Note:
The above query does not show details of department number 40. This is because
deptno 40 is not present in the EMP table. So, If department 40 details with blank
employee details is to be displayed use outer join.
Outer Join
Output:
DEPTNO LOC ENAME SAL
----------- ------------- ---------- ---------
10 NEW YORK CLARK 2450
10 NEW YORK KING 5000
20 DALLAS SMITH 800
20 DALLAS SCOTT 3000
Thampy Mathew 93
Oracle Complete – A Quick Reference
SQL
20 DALLAS JONES 2975
20 DALLAS ADAMS 1100
20 DALLAS FORD 3000
30 CHICAGO ALLEN 1600
30 CHICAGO MARTIN 1250
30 CHICAGO TURNER 1500
30 CHICAGO JAMES 950
30 CHICAGO BLAKE 2850
40 BOSTON
Note:
The (+) inserted after E.Deptno in the Where clause of the query created an outer
join by which Deptno 40 and its Location are displayed with blank values for the
employees.
Self Join
Output:
EMPNO EMPLOYEE EMPNO MANAGER
------ -------- ----- -------
7369 SMITH 7902 FORD
7499 ALLEN 7698 BLAKE
7566 JONES 7839 KING
7654 MARTIN 7698 BLAKE
7698 BLAKE 7839 KING
7782 CLARK 7839 KING
7788 SCOTT 7566 JONES
7844 TURNER 7698 BLAKE
7876 ADAMS 7788 SCOTT
7900 JAMES 7698 BLAKE
7902 FORD 7566 JONES
Correlated Subqueries
Thampy Mathew 94
Oracle Complete – A Quick Reference
SQL
And E.Deptno =
(Select Deptno From Dept
Where Loc = 'NEW YORK');
Output:
NAME LOCATION
---------- ---------
CLARK NEW YORK
KING NEW YORK
Note:
There is no limit o the number of subqueries that can be used in a Query. Whe the
Query is executed last subquery will be executed first and its output will be used i
the second last sbquery and so on.
An Alternate to Subqueries.
Output:
NAME LOCATION
---------- ---------
CLARK NEW YORK
KING NEW YORK
A Possible MISTAKE.
Output:
NAME LOCATION
---------- --------
CLARK BOSTON
CLARK CHICAGO
CLARK DALLAS
CLARK NEW YORK
Thampy Mathew 95
Oracle Complete – A Quick Reference
SQL
KING BOSTON
KING CHICAGO
KING DALLAS
KING NEW YORK
Note:
E.Deptno = D.Deptno condition is removed in the above query due to which the
names are getting repeated with all the available depts. Note that the repetition
could not be stopped by the DISTINCT function used in the query.
Output:
ERROR at line 4:
ORA-01427: single-row subquery returns more than one row
Note:
If the subquery returns more than one value, instead of = use IN as shown in the
following Query
Output:
NAME LOCATION
---------- --------
ADAMS DALLAS
FORD DALLAS
JONES DALLAS
SCOTT DALLAS
SMITH DALLAS
CLARK NEW YORK
Thampy Mathew 96
Oracle Complete – A Quick Reference
SQL
KING NEW YORK
Note:
EXISTS is a test for existence. It is placed the way IN might be placed with a
subquery but differs in two ways:
Output:
DEPTNO DNAME LOC
------ -------------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Note:
The outer query selects record each time when the inner query returns at least one
record. The inner query output is not equated with the outer query.
Output:
DEPTNO DNAME LOC
------ -------------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
Thampy Mathew 97
Oracle Complete – A Quick Reference
SQL
Note:
The department number (D.Deptno) of the outer query is equated with the
department number of the inner query by giving the condition Deptno = D.Deptno
in the inner query.
Output:
DEPTNO DNAME LOC
------ -------------- -------
40 OPERATIONS BOSTON
Find the details of all departments that are present in the EMP table from dept
table.
Output:
DEPTNO DNAME LOC
---- -------- --------
20 RESEARCH DALLAS
30 SALES CHICAGO
20 RESEARCH DALLAS
30 SALES CHICAGO
30 SALES CHICAGO
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
10 ACCOUNTING NEW YORK
30 SALES CHICAGO
20 RESEARCH DALLAS
30 SALES CHICAGO
20 RESEARCH DALLAS
Why the Deptnos are repeating. See the following query for answer.
Thampy Mathew 98
Oracle Complete – A Quick Reference
SQL
Select D.Deptno, D.Dname, D.Loc,
E.Ename
From DEPT D, EMP E
Where E.Deptno = D.Deptno;
Output:
DEPTNO DNAME LOC ENAME
---- -------------- ------------- ------
20 RESEARCH DALLAS SMITH
30 SALES CHICAGO ALLEN
20 RESEARCH DALLAS JONES
30 SALES CHICAGO MARTIN
30 SALES CHICAGO BLAKE
10 ACCOUNTING NEW YORK CLARK
20 RESEARCH DALLAS SCOTT
10 ACCOUNTING NEW YORK KING
30 SALES CHICAGO TURNER
20 RESEARCH DALLAS ADAMS
30 SALES CHICAGO JAMES
20 RESEARCH DALLAS FORD
For each name in EMP it selected one record from DEPT that met the condition
E.Deptno = D.Deptno
Output:
DEPTNO DNAME LOC
---- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
Thampy Mathew 99
Oracle Complete – A Quick Reference
SQL
Output:
DEPTNO
----
10
20
30
40
Note:
UNION avoids repetitions.
Output:
DEPTNO
----
10
20
30
40
20
30
20
30
30
10
20
10
30
20
30
20
Note:
UNION ALL combines all records.
Output:
DEPTNO
----
10
Output:
DEPTNO
----
10
20
30
Note:
INTERSECT fetches only records common in both the tables.
Output:
DEPTNO
----
40
Note:
MINUS subtracts the records fetched by the inner query from the records fetched
by the outer query.
Output:
no rows selected
Queries that use a UNION, INTERSECT or MINUS in there where clause must have the
same number and type of columns. in the select list. But an equivalent IN construction
does not have this limitation.
Select
From
Where
Start With
Connect By
Order By
PRIOR forces reporting to be from the root out toward the leaves (if the PRIOR
column is the parent) or from a leaf toward the root (if the PRIOR column is the
child)
A WHERE clause eliminates individuals from the tree, but not their descendants
(or ancestors, if PRIOR is on the right side of the equal sign)
Select Cow, Bull, LPAD (' ', 6 * (Level – 1), '-') || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'EVE'
Connect By Cow = PRIOR Offspring;
Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
EVE ADAM---------------BETSY F 02-JAN-00
BETSY ADAM---------------------------NOVI F 30-MAR-03
BETSY BANDIT -------------------------GINNY F 04-DEC-03
GINNY DUKE----------------------------------------SUZY F 03-APR-06
SUZY BANDIT -----------------------------------------DELLA F 11-OCT-08
GINY DUKE----------------------------------------RUTH F 25-DEC-06
BETSY BANDIT -------------------------TEDDI F 12-AUG-05
EVE ADAM---------------POCO M 15-JUL-00
EVE BANDIT ------------ GRETA F 12-MAR-01
EVE POCO---------------- MANDY F 22-AUG-02
MANDY BANDIT ------------------------DUKE M 24-DEC-06
MANDY POCO---------------------------- PAULA F 21-DEC-06
EVE POCO---------------CINDY F 09-FEB-03
Select Cow, Bull, LPAD (' ', 6 * (Level - 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'EVE'
Connect By Cow = PRIOR Offspring;
Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
EVE ADAM BETSY F 02-JAN-00
BETSY ADAM NOVI F 30-MAR-03
BETSY BANDIT GINNY F 04-DEC-03
GINNY DUKE SUZY F 03-APR-06
SUZY BANDIT DELLA F 11-OCT-08
GINY DUKE RUTH F 25-DEC-06
BETSY BANDIT TEDDI F 12-AUG-05
EVE ADAM POCO M 15-JUL-00
EVE BANDIT GRETA F 12-MAR-01
EVE POCO MANDY F 22-AUG-02
MANDY BANDIT DUKE M 24-DEC-06
MANDY POCO PAULA F 21-DEC-06
EVE POCO CINDY F 09-FEB-03
Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE ADAM BETSY F 02-JAN-00
BETSY ADAM NOVI F 30-MAR-03
BETSY BANDIT GINNY F 04-DEC-03
GINNY DUKE SUZY F 03-APR-06
SUZY BANDIT DELLA F 11-OCT-08
GINY DUKE RUTH F 25-DEC-06
BETSY BANDIT TEDDI F 12-AUG-05
EVE ADAM POCO M 15-JUL-00
EVE BANDIT GRETA F 12-MAR-01
EVE POCO MANDY F 22-AUG-02
MANDY BANDIT DUKE M 24-DEC-06
MANDY POCO PAULA F 21-DEC-06
EVE POCO CINDY F 09-FEB-03
Excluding Individuals
Select Cow, Bull, LPAD (' ', 6 * (Level - 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Where Offsprng <> 'BETSY'
Start With Offspring = 'EVE'
Connect By Cow = PRIOR Offspring;
Select Cow, Bull, LPAD (' ', 6 * (Level - 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'EVE'
Connect By Cow = PRIOR Offspring
And Offsprng <> 'BETSY';
Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
EVE ADAM POCO M 15-JUL-00
EVE BANDIT GRETA F 13-MAR-01
EVE POCO MANDY F 22-AUG-02
MANDY BANDIT DUKE M 24-JUL-04
MANDT POCO PAULA F 21-DEC-06
EVE POCO CINDY F 09-FEB-03
Select Cow, Bull, LPAD (' ', 6 * (Level - 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'EVE'
Connect By Cow = PRIOR Offspring
Order By Cow, Birthdate;
Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
BETSY ADAM NOVI F
BETSY BANDIT GINNY F
BETSY BANDIT TEDDI F
EVE ADAM BETSY F
EVE ADAM POCO M
EVE BANDIT GRETA F
EVE POCO MANDY F
EVE POCO CINDY F
GINNY DUKE SUZY F
GINNY DUKE RUTH F
MANDY BANDIT DUKE M
MANDY POCO PAULA F
SUZY BANDIT DELLA F
Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
EVE ADAM BETSY F
EVE ADAM POCO M
EVE BANDIT GRETA F
EVE POCO MANDY F
EVE POCO CINDY F
BETSY ADAM NOVI F
BETSY BANDIT GINNY F
MANDY BANDIT DUKE M
BETSY BANDIT TEDDI F
GINNY DUKE SUZY F
MANDY POCO PAULA F
GINNY DUKE RUTH F
SUZY BANDIT DELLA F
Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
SUZY BANDIT DELLA F 11-OCT-08
GINNY DUKE SUZY F 03-APR-06
BETSY BANDIT GINNY F 04-DEC-03
EVE ADAM BETSY F 02-JAN-00
EVE F
Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
EVE ADAM BETSY F 02-JAN-00
BETSY BANDIT GINNY F 04-DEC-03
GINNY DUKE SUZY F 03-APR-03
SUZY BANDIT DELLA F 11-OCT-08
Let Us Correct It
Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
EVE ADAM BETSY F 02-JAN-00
BETSY BANDIT GINNY F 04-DEC-03
GINNY DUKE SUZY F 03-APR-06
SUZY BANDIT DELLA F 11-OCT-08
Now it is OK
Select Cow, Bull, LPAD (' ', 6 * (Level – 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'ADAM'
Connect By PRIOR Offspring = Bull;
Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
ADAM M
EVE ADAM BETSY F 02-JAN-00
EVE ADAM POCO M 15-JUL-00
EVE POCO MANDY F 22-AUG-02
EVE POCO CINDY F 09-FEB-03
MANDY POCO PAULA F 21-DEC-06
BETSY ADAM NOVI F 30-MAR-03
Select Cow, Bull, LPAD (' ', 6 * (Level - 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'BANDIT'
Connect By PRIOR Offspring = Bull;
Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
BANDIT M
EVE BANDIT GRETA F
BETSY BANDIT GINNY F
MANDY BANDIT DUKE M
GINNY DUKE SUZY F
GINNY DUKE RUTH F
BETSY BANDIT TEDDI F
SUZY BANDIT DELLA F
The specific syntax to use when creating a database link depends upon two criteria;
Note:
To create a database link, CREATE DATABASE LINK system privilege. The
account to which you will be connecting in the remote database must have CREATE
SESSION privilege.
When using Net8, you must know the name of the service that ponts to the remote
database. For example, if the name HQ specifies the connection parameters for the
Syntax:
When this link is used, Oracle checks the tnsnames.ora file on the local host to determine
which database to connect to. Whe it attempts to log in to that database, it uses the
current_user’s username and password.
The tnsnames.ora files for a network of databases should be coordinated by the DBAs for
those databases. A typical entry in the tnsnames.ora file (for a network using the TCP/IP
protocol) is shown in the following listing.
HQ = (DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL – TCP)
(HOST = host1)
(PORT = 1521)
)
)
(CONNECT DATA =
(SERVICE_NAME – HQ.host 1)
)
)
In this listing he HQ service name is mapped to a connect description that tells database
which protocol to use (TCP/IP), and which host (host1) and database (HQ) to connect to.
This command will directly log in the user scott to the HQ database.
To overcome the above problem you can use the SQLPLUS Copy command.
set copycommit 1
set arraysize 1000
Explanation:
Except for he last line, each line in the copy command must be terminated with a dash (-),
since this is an sqlplus command.
The copy command can be used within or between databases. Although it allows you to
select which columns to copy it works best when all the columns of a table are being
chosen.
If the current account is to be the destination of the copied data, then the word to plus the
local username, password and connect string are not necessary.
APPEND : Inserts the rows into the destination table. Automatically creates the table
if it does not exist.
INSERT : Inserts the rows into the destination table if it exists; otherwise, returns
an error. When using INSERT, all columns must be specified in the using
subquery.
REPLACE : drops the existing destination table and replace it with a new table
containing the copied data.
Syntax:
Example:
Password Management
SQL>password
Changing password for scott
Old password: <enter>
New password: <enter>
Retype new password: <enter>
The expiration characteristics of our pass word is determined by the profile assigned to
your account. A profile can enforce he following.
The ‘lifetime of your password, which determines how frequently you must
change your password.
The grace period following your password’s ‘expiration date’ during which you
can change your password.
The number of consecutive failed connect attempts allowed before the account is
automatically ‘locked’.
The number of days that must pass before you can reuse a password.
The number of password changes that must pass before you can reuse a password.
Dropping a User
Syntax:
The cascade option drops the user along with all the objects owned by him and
invalidates views, synonyms, procedures, functions or packages that refer to the objects
in the dropped user’s schema. If you don’t use cascade option and there are still objects
owned by the user, the user will not be dropped and instead returns an error message.
Granting Privileges
On sequences:
SELECT
ALTER
The privileges granted must be one of the object privileges (ALL, ALTER, DELETE,
EXECUTE, INDEX, INSERT, READ, REFERENCES, SELECT or UPDATE)
Connect thampy/Mathew;
Connect john/mathew;
Revoking Privileges
Passing Privileges
Connect john/mathew;
ERROR at line1:
ORA-00942: grant option does not exist for thampy.EMP1.
Connect thampy/mathew;
Connect john/mathew;
Grant succeeded
Connect james/thomas;
Creating a Role
Syntax:
Example:
The admin option authorizes thampy to grant the MANAGER role to other users or roles.
Any time a user tries to activate the role MANAGER, the password will be required. If,
however, the role is setup as a default role for the user, then no password will be required
for that role when the user logs in.
Roles can be tied to operating system privileges as well. If this capability is available on
your operating system, then you use the identified externally clause of the alter role
command. When the role is enabled Oracle will check the operating system to verify your
access.
You may also use the all and all except clauses that are available in the alter user
command.
If a role has a password associated with it you must specify the password via the
identified by clause.
Dropping a Role
Security By User
Connect thampy/Mathew;
Create View YOURSAL As
Select Ename, Sal From EMP1
Where SUBSTR (Ename, 1, INSTR (ENAME, ‘ ‘) – 1) = User;
Connect john/Mathew;
Granting Resources
Grant CONNECT To thampy;
Grant CONNECT, RESOURCE To Thampy;
SQL*Loader
Create a Table
Note:
1. No Deptno is entered for 1st and 2nd record that references another table.
2. The Deptno 50 entered for the 7th record is not present in the Master table
(DEPT)
Create a Text File From The csv File With Extension .dat
Open this file with Notepad and Save As "UPLOAD.dat". Do remember to use double
quotes before and after the file name as "UPLOAD.dat"
1001,THAMPY,7500,
1002,MATHEW,8000,
1003,SUJA,5500,10
1004,ANNIE,7000,20
1005,JOHN,7500,30
1001,ALLEN,8000,20
1006,SUMAN,7600,50
LOAD DATA
INFILE 'D:\UPLOAD.dat'
APPEND
INTO TABLE EMP1
FIELDS TERMINATED BY ","
(Empno, Ename, Sal, Deptno, Avtive constant 'Y')
Note:
1. The dat file with path must be enclosed in single quotes.
2. The order of the field names specified in the control file must correspond to
the order of columns in the dat file.
3. You can send constant values to the table in such cases do not include the
field values in the dat file, instead, specify the constant value in the control
file as it is shown for the field ‘Active’. (Active constant ‘Y’). A value of Y
will be inserted to all to all the rows for the field ‘Active’.
Wndows NT
Start --> Run
cmd
Unix
Start --> run
telnet <IP Address>
Invoke SQL*LOADER
Analysis:
When the SQL*Loader runs it will automatically creates the following two files.
A bad file with the same name of the data file with extension .bad
This file will show the uninserted rcords.
A log file with the same name of the control file with extension .log
This fle will write the log of the executon of SQl*Loader
Row 1001,ALLEN,8000,20 was actually violating the primary key constraint on Empno
as the value 1001 is a repeat. It is accepted as the first record with Empno 1001 is
rejected due to some other reason.
Content of UPLOAD.bad
1001,THAMPY,7500,
1002,MATHEW,8000,
1006,SUMAN,7600,50
Content of UPLOAD.log
SQL*Loader: Release 8.0.3.0.0 - Production on Mon Jul 28 19:13:9 2003
Table EMP1:
4 Rows successfully loaded.
LOAD DATA
INFILE 'D:\UPLOAD.dat'
APPEND
INTO TABLE EMP1
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
(Empno, Ename, Sal, Deptno, Active constant 'Y')
Note:
We have added he following two lines in the control file.
OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
Analysis:
UPLOAD.bad
1001,ALLEN,8000,20
1006,SUMAN,7600,50
Note:
The first record is not inserted because it violates the primary key constraint of the
table.
The second record is not inserted because in violates the referential integrity
constraint of the table.
The above given two reasons can be seen in the log file.
UPLOAD.log
SQL*Loader: Release 8.0.3.0.0 - Production on Mon Jul 28 20:0:34 2003
Table EMP1:
5 Rows successfully loaded.
2 Rows not loaded due to data errors.
0 Rows not loaded because all WHEN clauses were failed.
0 Rows not loaded because all fields were null.
INSERT : Use to add rows to an empty table. If the table is not empty, the load will
abort with an error.
REPLACE : Use to empty the table and then add the new rows. The user must have
delete privilege on the table.
TRUNCATE : Delete and commit the table first and then load the rows into it.
LOAD DATA
INFILE 'D:\UPLOAD.dat'
[APPEND] [INSERT] [REPLACE] [TRUNCATE]
INTO TABLE EMP1
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
(Empno, Ename, Sal, Deptno, Active constant 'Y')
Parfile The name of the parameter file that contains additional load
parameter specifications.
Skip_Unusable_Indexes Allows load into tables that have indexes in unusable states.
The default is FALSE.
sqlldr scott/tiger@db1
control = D:\UPLOAD.ctl
log = D:\UPLOAD_LOG.log
bad = D:\UPLOAD_BAD.bad
discard = D:\UPLOAD_DISCARD
skip = 1
2. Copy only the data (with no extra row or column) and Paste Special… Values to a
new file. This is to avoid junk character creations in the table.
3. Save the file as CSV (Coma delimted) with .csv extension. Ensure that the file
name with extension is enclosed in double quotes while saving.
5. Save the notepad file with .dat extension. Ensure that the file name with extension
is enclosed in double quotes while saving.
Transfer the Data and Control Files to the Required Server Directory
7. Open the ftp prompt. (Start Run [ftp <IP Address>] Enter
Connect to the required database for which type the:
8. Change the local machine directory o the directory where the Data and Control
files are currently available. (lcd C:\Upload\EAM)
9. Change the Server directory to the directory in which you want to keep the Data
and Control files. (cd /apps2/oraprdt/uploads/Asset_Group)
10. Change the transfer mode to ASCII. (Simply type ASCII at the ftp prompt)
11. Transfer the Data file from the client machine to the server. (put <File
Name>.dat)
12. Transfer the Control file from the client machine to the server. (put <File
Name>.ctl)
Run SQL*Loader
14. sqlldr [sqlldr80] <username>/<password>@<connect string>
control = <control file name>.ctl
(
PROCESS_FLAG constant 1,
TRANSACTION_TYPE constant 'CREATE',
SET_PROCESS_ID constant 1,
SEGMENT1,
DESCRIPTION,
start_auto_serial_number,
LAST_UPDATED_BY constant 0,
LAST_UPDATE_DATE sysdate,
LAST_UPDATE_LOGIN constant 0,
CREATION_DATE sysdate,
CREATED_BY constant 0
)
Update Customer C
Set C.Person.Address.State = 'KERALA'
Where C.Person.Address.State = 'KR'
Select C.Person.Name,
C.Person.Address.City
From Customer C
Where C.Person.Address.Zip Like '401%'
Output:
PERSON.NAME PERSON.ADDRESS.CITY
------------------- -----------------------------
JOHN Bombay