(SQL) Oracle Stream
(SQL) Oracle Stream
ORACLE SERVER
Database
The latest version of the Oracle server is 10g(for our training). Latest Version
: 12i
Oracle server runs on different platforms. The following are some of the
platforms on which Oracle runs.
Windows NT.
Novel Netware
Unix
Personal Oracle is one of the flavors of Oracle. In this Oracle server and
client both run on the same machine. This is unlike other flavors where
Oracle Server runs on Server and Front-end runs on Client.
Features of Oracle
Data Concurrence
Oracle server is 100% compliant with Entry of the ANSI / ISO standards.
Oracle adheres to industry standards for data access language, network
protocols etc. This makes Oracle an ‘open’ system, which protects the
investment of customer. It is easy to port Oracle applications.
Enforced Integrity
Oracle allows users to define business rules and enforce them. These rules
need not be included at the application level.
Data Security
Oracle provides security in different levels – system level and object level. It
also makes implementation of security easier through Roles.
Oracle allows process to be split between client and server. Oracle server
does all database management whereas Client does user interface. Oracle
server allows code to be stored in the database in the form of procedures
and functions. This allows centralization of the code and reduces network
traffic.
Database Architecture
A database contains any length of information. But for the end user, we
have to show only required information by hiding the unwanted information.
This data hiding can be done using various data abstraction methods.
Physical level
Logical Level
View level
Physical Level
Data Files
Redo log files
Control files
It contains the data of the database. Every table that is stored in the
database is a part of these files. Only Oracle Server can interpret these data
files.
Every database has a set of two or more Redo Log files. The set of redo log
files is known as databases redo log. Redo Log files are used in failure
recovery. All changes made to the database are written to redo log file.
(Filenames redo01.log)
Control Files
Database Name
Names and locations of data files and redo log files.
Path We can use this Oracle\oradata\orcl path in the server to see all the
3 types of files
Tablespaces
Segments
Extents
Blocks
Tablespace
Segments
Extents
The shared pool is used to store the most recently executed SQL
statements and the most recently used data from the data dictionary.
These SQL statements may be submitted by a user process or, in the
case of stored procedures, read from the data dictionary.
The database buffer cache is used to store the most recently used
data. The data is read from, and written to, the data files.
The redo log buffer is used to track changes made to the database by
the server and background processes.
1 Parse
2 Execute 3
3 Fetch
Server
Proces DB
s
1
User
Process
2
Clie
nt
Parsing
During the parse stage, the SQL statement is passed from the user process
to the server process, and a parsed representation of the SQL statement is
loaded into a shared SQL area.
During the parse, the server process performs the following functions:
Searches for an existing copy of the SQL statement in the shared pool
validates the SQL statement by checking its syntax
Performs data dictionary lookups to validate table and column
definitions
Fetch
Fetch: Return rows to user process. With each fetch process, it can fetch 20
records at a time.
The server process records the before image to the rollback block and
updates the data block.
Both of these changes are done in the database buffer cache.
Any changed blocks in the buffer cache are marked as dirty buffers: that is,
buffers that are not the same as the corresponding blocks on the disk.
Because the changes made to the blocks are only recorded in memory
structures and are not written immediately to disk, a computer failure that
causes the loss of the SGA can also lose these changes.
Oracle
Internet
Reliability Common Skill
Sets
Single Dev
Model
Benefits
Scalability from departments to enterprise e-business sites
Reliable, available and secure architecture
One development model, easy development options
Common skill sets including SQL, PL/SQL,JAVA and XML
One Management interface for all applications
9i Products
There are two products. They provide a complete and simple infrastructure
for Internet applications.
IAS Database
9i 9i
Application Server
9i Application server runs all the applications and 9i database stores our
data.
Oracle 9i Application server runs
Portals or web sites
Java Transactional Applications
Provides integration between users, applications and data
Oracle 9i supports
Environment
Oracle uses two types of Environments for executing our SQL statements.
SQL*plus and iSQL*plus.
ISQL*plus is (Available only from Oracle 9i)
An Environment
Oracle proprietary
Keywords can be abbreviated
Runs on a browser
Centrally loaded, does not have to be implemented on each machine
Difference between SQL*Plus and ISQL*plus
SQL*Plus is a CUI and iSQL*Plus runs on a browser
SQL*plus should be loaded in each every client system, where as
iSQL*plus, centrally loaded, doesn’t have to be implemented on each
machine
Character Datatypes
CHAR datatype
Fixed length character data of length size in bytes.( Default size is 1 and
maximum size is 2000).
Padded on right with blanks to full length of size.
VARCHAR2 (size)
NVARCHAR2(size)
NUMBER(size,d)
LONG
Character data of variable size up to 2GB in length. Only one LONG column
is allowed in a table.
Long column cannot be used in sub queries, functions, expressions, where
clause or indexes.
DATE
TIMESTAMP(precision)
Date plus time, where precision is the number of digits in the fractional part
of the seconds field (default is 6).
RAW(size)
Raw binary date, size bytes long. Maximum size is 2000 bytes.
LONG RAW
CLOB
Character Large object, up to 4GB in length.
BLOB
BFILE
Pointer to a binary operating system file.
Introduction to SQL
NOTE: Nonprocedural means what rather than how. For example, SQL
describes what data to retrieve, delete, or insert, rather than how to perform
the operation.
An Overview of SQL
SQL is the standard language used to manipulate and retrieve data from
these relational databases. SQL enables a programmer or database
administrator to do the following:
SQL was originally made an ANSI standard in 1986. The ANSI 1989
standard (often called SQL-89) defines three types of interfacing to SQL
within an application program:
Before the concept of dynamic SQL evolved, embedded SQL was the most
popular way to use SQL within a program. Embedded SQL, which is still
used, uses static SQL—meaning that the SQL statement is compiled into the
application and cannot be changed at runtime. The principle is much the
same as a compiler versus an interpreter. The performance for this type of
SQL is good; however, it is not flexible--and cannot always meet the needs of
today's changing business environments.
Oracle server supports ANSI standard SQL and contains extensions. Using
SQL, you can communicate with the Oracle server. SQL has the following
advantages
Efficient
Easy to learn and use
Functionally complete (With SQL, you can define, retrieve, and
manipulate data in the tables.)
ANALYSIS:
Notice that columns 6 and 8 in the output statement are right justified and that columns 2 and 3 are left
justified. This format follows the alignment convention in which numeric data types are right justified
and character data types are left justified.
The asterisk (*) in select * tells the database to return all the columns associated with the given table
described in the FROM clause. The database determines the order in which to return the columns.
A full table scan is used whenever there is no where clause on a query.
INPUT:
SQL> SELECT empno, ename, sal, job, comm from EMP;
OUTPUT
EMPNO ENAME SAL JOB COMM
---------- ---------- ---------- --------- ----------
7369 SMITH 800 CLERK
7499 ALLEN 1600 SALESMAN 300
7521 WARD 1250 SALESMAN 500
7566 JONES 2975 MANAGER
7654 MARTIN 1250 SALESMAN 1400
7698 BLAKE 2850 MANAGER
7782 CLARK 2450 MANAGER
7788 SCOTT 3000 ANALYST
7839 KING 5000 PRESIDENT
7844 TURNER 1500 SALESMAN 0
7876 ADAMS 1100 CLERK
7900 JAMES 950 CLERK
7902 FORD 3000 ANALYST
7934 MILLER 1300 CLERK
14 rows selected.
Conditions
If you ever want to find a particular item or group of items in your database,
you need one or more conditions. Conditions are contained in the WHERE
clause. In the preceding example, the condition is ENAME = 'KING'
To find everyone in your organization who worked more than 100 hours last
month, your condition would be SAL > 2000
Conditions enable you to make selective queries. In there most common
form, conditions comprise a variable, a constant, and a comparison
operator. In the first example the variable is ENAME, the constant is 'KING',
and the comparison operator is =.
In the second example the variable is SAL, the constant is 100, and the
comparison operator is >. You need to know about two more elements before
you can write conditional queries: the WHERE clause and operators.
SYNTAX:
SELECT <COLUMNS> FROM <TABLE> WHERE <SEARCH
CONDITION>;
SELECT, FROM, and WHERE are the three most frequently used clauses in
SQL. WHERE simply causes your queries to be more selective. Without the
WHERE clause, the most useful thing you could do with a query is display
all records in the selected table(s).
INPUT/OUTPUT:
SQL> SELECT * FROM EMP WHERE ENAME = 'KING';
ANALYSIS:
This simple example shows how you can place a condition on the data that you
want to retrieve.
INPUT
OUTPUT
EMPNO ENAME 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
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 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 09-DEC-82 3000 20
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
ANALYSIS:
Arithmetic Operators
The arithmetic operators are plus (+), minus (-), divide (/), multiply (*).
The first four are self-explanatory. Modulo returns the integer remainder of a
division.
Comparison Operators
SELECT * FROM EMP WHERE SAL >= 3000 AND SAL <= 4000;
SELECT * FROM EMP WHERE SAL NOT BETWEEN 3000 AND 4000;
To understand how you could get an Unknown, you need to know a little
about the concept of NULL. In database terms NULL is the absence of data
in a field. It does not mean a column has a zero or a blank in it. A zero or a
blank is a value. NULL means nothing is in that field. If you make a
comparison like Field = 9 and the only value for Field is NULL, the comparison
will come back Unknown. Because Unknown is an uncomfortable condition,
most flavors of SQL change Unknown to FALSE and provide a special
operator, IS NULL, to test for a NULL condition.
Here's an example of NULL: Suppose an entry in the PRICE table does not
contain a value for WHOLESALE. The results of a query might look like this:
Character Operators
You can use character operators to manipulate the way character strings are
represented, both in the output of data and in the process of placing
conditions on data to be retrieved. This section describes two character
operators: the LIKE operator and the || operator, which conveys the
concept of character concatenation.
LIKE operator
What if you wanted to select parts of a database that fit a pattern but
weren't quite exact matches? You could use the equal sign and run through
all the possible cases, but that process would be time-consuming. Instead,
you could use LIKE.
INPUT:
SELECT * FROM EMP WHERE ENAME LIKE ‘A%’;
ANALYSIS
INPUT:
SELECT * FROM EMP WHERE ENAME NOT LIKE ‘A%’;
ANALYSIS
Displays all the employees whose names not beginning with letter A
ANALYSIS
INPUT:
SELECT * FROM EMP WHERE ENAME LIKE ‘%A%A%’;
ANALYSIS
Displays all the names whose name contains letter A more than one
time
INPUT:
SELECT * FROM EMP WHERE HIREDATE LIKE ‘%DEC%’;
ANALYSIS
INPUT:
SELECT * FROM EMP WHERE HIREDATE LIKE ‘%81’;
ANALYSIS
INPUT:
SELECT * FROM EMP WHERE SAL LIKE ‘4%’;
ANALYSIS
INPUT:
SQL> SELECT EMPNO,ENAME FROM EMP WHERE ENAME LIKE ‘_A
%’;
OUTPUT:
EMPNO ENAME
---------- ----------
7521 WARD
7654 MARTIN
7900 JAMES
ANALYSIS
Displays all the employees whose second letter is A
INPUT:
SQL> SELECT * FROM EMP WHERE ENAME LIKE ‘__A%’;
OUTPUT:
ENAME
----------
BLAKE
CLARK
ADAMS
ANALYSIS
Displays all the employees whose third letter is A
( Two underscores followed by A)
INPUT:
SQL> SELECT * FROM EMP WHERE ENAME LIKE ‘A%\_%’ ESCAPE
‘\’;
OUTPUT:
ENAME
----------
AVINASH_K
ANAND_VARDAN
ADAMS_P
ANALYSIS
Displays all the employees with underscore (_). ‘\’ Escape character
Underscore is used to identify a position in the string. To treat _ as a
character we have to use Escape (\) character,
INPUT
SELECT ENAME || JOB FROM EMP;
OUTPUT
ENAME||JOB
-------------------
SMITHCLERK
ALLENSALESMAN
WARDSALESMAN
JONESMANAGER
MARTINSALESMAN
BLAKEMANAGER
CLARKMANAGER
SCOTTANALYST
KINGPRESIDENT
TURNERSALESMAN
ADAMSCLERK
JAMESCLERK
FORDANALYST
MILLERCLERK
ANALYSIS
Combines both name and designation as a single string.
INPUT
SQL>SELECT ENAME || ‘ , ‘ || JOB FROM EMP;
OUTPUT
ENAME||','||JOB
----------------------
SMITH , CLERK
ALLEN , SALESMAN
WARD , SALESMAN
JONES , MANAGER
MARTIN , SALESMAN
BLAKE , MANAGER
CLARK , MANAGER
SCOTT , ANALYST
KING , PRESIDENT
TURNER , SALESMAN
ADAMS , CLERK
JAMES , CLERK
FORD , ANALYST
MILLER , CLERK
ANALYSIS
Combines both name and designation as a single string separated by,
INPUT:
SELECT ENAME FROM EMP WHERE ENAME LIKE ‘%A%’ and
ENAME NOT LIKE ‘%A%A%’
OUTPUT
ENAME
----------
ALLEN
WARD
MARTIN
BLAKE
CLARK
JAMES
ANALYSIS
Displays all the employees whose names contains letter A exactly one
time.
SELECT * FROM EMP WHERE SAL >= 3000 AND SAL <= 4000;
The two operators IN and BETWEEN provide shorthand for functions you
already know how to do. You could type the following:
The above statement takes more time to parse it, which reduces the
efficiency.
INPUT:
SQL> SELECT * FROM EMP WHERE JOB
IN('CLERK','SALESMAN','MANAGER');
OUTPUT:
ENAME JOB
---------- ---------
SMITH CLERK
ALLEN SALESMAN
WARD SALESMAN
JONES MANAGER
MARTIN SALESMAN
BLAKE MANAGER
CLARK MANAGER
TURNER SALESMAN
ADAMS CLERK
JAMES CLERK
MILLER CLERK
ANALYSIS
Display employees with designations manager, clerk, and salesman,
ANALYSIS
Display designations other than manager, clerk, and salesman
INPUT:
SQL> SELECT ENAME,HIREDATE
FROM EMP
WHERE HIREDATE IN (’01-MAY-1981’,’09-DEC-1982’);
OUTPUT:
ENAME HIREDATE
---------- ---------
BLAKE 01-MAY-81
SCOTT 09-DEC-82
ANALYSIS
Display employees who joined on two different dates.
DISTINCT OPERATOR
INPUT:
SQL> SELECT DISTINCT JOB FROM EMP;
OUTPUT:
JOB
---------
ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
ANALYSIS
Distinct operator displays unique designations.
Distinct operator by default displays the information in ascending order.
Syntax
INPUT
SQL> SELECT ENAME FROM EMP ORDER BY ENAME;
OUTPUT
ENAME
----------
ADAMS
ALLEN
BLAKE
CLARK
FORD
JAMES
JONES
KING
MARTIN
MILLER
SCOTT
SMITH
TURNER
WARD
ANALYSIS
Display employees in ascending order of names.
ANALYSIS
Display employees in ascending order of jobs. With each job it places the
information in ascending order of names.
INPUT
OUTPUT:
Display employees in ascending order by jobs. With each job it places the
information in descending order of names.
INPUT
OUTPUT:
Display employees in descending order by jobs. With each job it places
the information in descending order of names.
SQL> SELECT *
FROM EMP where JOB != ‘CLERK’
ORDER BY JOB;
OUTPUT:
Display employees in ascending order of jobs other than clerks.
ANALYSIS
When we are executing the query, it is divided into two different parts.
1) SELECT *
FROM EMP where JOB != ‘CLERK’
2) ORDER BY JOB;
First part is going to execute first, and selects all the employees whose
designation is other than clerk and places them in a temporary table.
INPUT
ANALYSIS
9. Examine the trace instance chart for employee table. You want to display each employee hiredate
from earliest to latest. Which SQL statement will you use?
(1) SELECT hiredate FROM emp;
10. Which data type should you use for interest rates with varying and unpredictabledecimal places
such as 1.234, 3.4, 5 and 1.23?
(1) LONG.
(2) NUMBER.
(3) NUMBER(p, s)
(4) None
11.Which SQL statement generates the alias Annual Salary for the calculated column SALARY*12?
13. The employee table contains these columns.LAST_NAME VARCHAR2 (25), FIRST_NAME
VARCHAR2(25) DEPT_ID NUMBER(9) You need to display the names of the employees that
are not assigned to the department. Evaluate this SQL statement; SELECT last_name,
first_name FROM employee WHERE dept_id is NULL which change should you make to
achieve the desired result?
(4) You cannot sort query results by a column that is not included in the SELECT list.
Predefined functions
User defined functions
Predefined functions
Aggregate Functions
These functions are also referred to as group functions. They return a value
based on the values in a column.
COUNT
The function COUNT returns the number of rows that satisfy the condition
in the WHERE clause.
INPUT:
SQL> SELECT COUNT(*) FROM EMP;
OUTPUT:
COUNT(*)
--------
14
ANALYSIS
It counts if row presents in the table
INPUT/OUTPUT:
SQL> SELECT COUNT(*) NUM_OF_EMP FROM EMP;
NUM_OF_EMP
-------------------
14
INPUT/OUTPUT:
SQL> SELECT COUNT(COMM)
FROM EMP;
COUNT(*)
--------
4
ANALYSIS
INPUT/OUTPUT:
SQL> SELECT COUNT(*) FROM EMP WHERE JOB = ‘MANAGER’;
COUNT(*)
-------
4
ANALYSIS
It counts only managers
ANALYSIS
It counts only distinct jobs
SUM
SUM does just that. It returns the sum of all values in a
column.
INPUT:
SQL> SELECT SUM(SAL) TOTAL_SALARY FROM EMP;
OUTPUT:
TOTAL_SALARY
-------------
29025
ANALYSIS
Find the total salary drawn by all the employees
INPUT/OUTPUT:
SQL> SELECT SUM(SAL) TOTAL_SALARY, SUM(COMM)
TOTAL_COMM,
FROM EMP;
TOTAL_SALARY TOTAL_COMM
------------- ----------
29025 2200
INPUT/OUTPUT:
SQL> SQL> SELECT SUM(SAL) TOTAL_SALARY, SUM(COMM)
TOTAL_COMM,
FROM EMP WHERE JOB = ‘SALESMAN’;
TOTAL_SALARY TOTAL_COMM
------------- ----------
5600 2200
ANALYSIS
Find the average salary of all the employees
INPUT:
SQL> SELECT AVG(COMM) average_comm FROM EMP;
OUTPUT:
AVERAGE_COMM
------------
550
ANALYSIS
Functions ignores null rows
MAX(SAL)
--------
5000
ANALYSIS
Takes the value from one different rows from one particular column
INPUT:
SQL> SELECT MAX(ENAME) FROM EMP;
OUTPUT:
MAX(ENAME)
--------
WARD
ANALYSIS
Max of name is identified based on ASCII value
INPUT:
SQL> SELECT MAX (hiredate) FROM EMP;
OUTPUT:
MAX(HIREDATE)
-------------
12-JAN-83
INPUT:
SQL> SELECT MIN(SAL) FROM EMP;
OUTPUT:
MIN(SAL)
--------
800
INPUT:
SQL> SELECT MIN(ENAME) FROM EMP;
OUTPUT:
MIN (ENAME)
--------
ADAMS
INPUT
OUTPUT
SUM(SAL) AVG(SAL) MIN(SAL) MAX(SAL) COUNT(*)
-------------- --------------- -------------- -------------- -------------
29025 2073.21429 800 5000 14
ANALYSIS
All the aggregate functions can be used together in a single SQL statement
These functions work on each and every row and return a value to the
calling places.
Arithmetic Functions
Character Functions
Date functions
Miscellaneous Functions
Arithmetic Functions
Many of the uses you have for the data you retrieve involve mathematics.
Most Implementations of SQL provide arithmetic functions similar to that of
operators covered here.
ABS
The ABS function returns the absolute value of the number you point to. For
example:
INPUT:
SQL> SELECT ABS(-10) ABSOLUTE_VALUE FROM dual;
OUTPUT
ABSOLUTE_VALUE
----------------------------
10
ANALYSIS
ABS changes all the negative numbers to positive and leaves positive numbers
alone.
Dual is a system table or dummy table from where we can display system
information (i.e. system date and username etc) or we can make our own
calculations.
CEIL returns the smallest integer greater than or equal to its argument.
FLOOR does just the reverse, returning the largest integer equal to or less
than its argument.
INPUT:
SQL> SELECT CEIL(12.145) FROM DUAL;
OUTPUT:
CEIL(12.145)
-----------------
13
INPUT:
SQL> SELECT CEIL(12.000) FROM DUAL;
OUTPUT:
CEIL(12.000)
-----------------
12
ANALYSIS
Minimum we require one decimal place , to get the next higher integer number
INPUT/OUTPUT:
SQL> SELECT FLOOR(12.678) FLOOR DUAL;
OUTPUT:
FLOOR(12.678)
-----------------
12
INPUT:
SQL> SELECT FLOOR(12.000) FROM DUAL;
OUTPUT:
FLOOR(12.000)
-----------------
12
INPUT
INPUT
INPUT:
SQL> SELECT POWER(5,3) FROM DUAL;
OUTPUT:
125
SIGN
SIGN returns -1 if its argument is less than 0, 0 if its argument is equal to 0,
and 1 if its argument is greater than 0,
INPUT:
SQL> SELECT SIGN(-10), SIGN(10),SIGN(0) FROM DUAL;
OUTPUT:
SIGN(-10) SIGN(10) SIGN(0)
---------- ---------- ----------
-1 1 0
SQRT
The function SQRT returns the square root of an argument. Because the
square root of a negative number is undefined, you cannot use SQRT on
negative numbers.
INPUT/OUTPUT:
SQL> SELECT SQRT(4) FROM DUAL;
CHR
INPUT:
SQL> SELECT CHR(65) FROM DUAL;
OUTPUT:
A
CONCAT
INPUT:
SQL> SELECT CONCAT(‘KRISHNA’, ‘ KANTH’) FROM DUAL;
OUTPUT
KRISHNA KANTH
INPUT:
SQL> SELECT ENAME “BEFORE”,INITCAP(ENAME) “AFTER”FROM EMP;
OUTPUT:
BEFORE AFTER
---------- ----------
SMITH Smith
ALLEN Allen
WARD Ward
JONES Jones
MARTIN Martin
BLAKE Blake
CLARK Clark
SCOTT Scott
KING King
TURNER Turner
ADAMS Adams
JAMES James
FORD Ford
MILLER Miller
The following statement adds five pad characters, assuming that the field
LASTNAME is defined as a 15-character field:
INPUT:
SQL> SELECT LPAD(ENAME,15,’*’) FROM EMP;
OUTPUT:
LPAD(ENAME,15,'
---------------
**********SMITH
**********ALLEN
***********WARD
**********JONES
*********MARTIN
**********BLAKE
**********CLARK
**********SCOTT
***********KING
*********TURNER
**********ADAMS
**********JAMES
***********FORD
*********MILLER
ANALYSIS:
15 locations allocated to display ename, out of that, name is occupying some
space and in the remaining space to the left side of the name pads with *.
INPUT
OUTPUT:
5000******
LTRIM and RTRIM take at least one and at most two arguments. The first
argument, like LPAD and RPAD, is a character string. The optional second
element is either a character or character string or defaults to a blank. If you
use a second argument that is not a blank, these trim functions will trim
that character the same way they trim the blanks in the following examples.
INPUT:
SQL> SELECT ENAME, RTRIM(ENAME,’R’) FROM EMP;
OUTPUT:
ENAME RTRIM(ENAM
---------- ----------
SMITH SMITH
ALLEN ALLEN
WARD WARD
JONES JONES
MARTIN MARTIN
BLAKE BLAKE
CLARK CLARK
SCOTT SCOTT
KING KING
TURNER TURNE
ADAMS ADAMS
JAMES JAMES
FORD FORD
MILLER MILLE
ANALYSIS
Removes the rightmost character
REPLACE does just that. Of its three arguments, the first is the string to be
searched. The second is the search key. The last is the optional replacement
string. If the third argument is left out or NULL, each occurrence of the
search key on the string to be searched is removed and is not replaced with
anything.
SYNTAX :
REPLACE(STRING,SEARCH_STRING,REPLACE_STRING)
INPUT:
OUTPUT
RAVINA
INPUT
SQL> SELECT REPLACE(‘RAMANA’,’MA’) FROM DUAL;
OUTPUT
RANA
ANALYSIS
When the replace string is missing, search string removed from the given
string
INPUT
SQL> SELECT REPLACE (‘RAMANA’,’MA’, NULL) FROM DUAL;
OUTPUT
RANA
The function TRANSLATE takes three arguments: the target string, the
FROM string, and the TO string. Elements of the target string that occur in
the FROM string are translated to the corresponding element in the TO
string.
INPUT:
SQL> SELECT TRANSLATE(‘RAMANA’,’MA’,’CD’) FROM DUAL;
OUTPUT:
RDCDND
ANALYSIS
SUBSTR
This three-argument function enables you to take a piece out of a target
string. The first argument is the target string. The second argument is the
position of the first character to be output. The third argument is the
number of characters to show.
SYNTAX
SUBSTR(STRING,STARTING_POSITION[,NO_OF_CHARACTERS])
INPUT:
SQL> SELECT SUBSTR(‘RAMANA’,1,3) FROM DUAL;
OUTPUT:
RAM
ANALYSIS
It takes first 3 characters from first character
ANALYSIS
It takes 3 characters from third position
INPUT:
SQL> SELECT SUBSTR(‘RAMANA’,-2,2) FROM DUAL;
OUTPUT:
NA
ANALYSIS
You use a negative number as the second argument, the starting point is
determined by counting backwards from the end.
INPUT:
SQL> SELECT SUBSTR(‘RAMANA’,1,2) || SUBSTR(‘RAMANA’,-2,2) FROM
DUAL;
OUTPUT:
RANA
ANALYSIS
First two characters and last two characters are combined together as a
single string
INPUT:
SQL> SELECT SUBSTR(‘RAMANA’,3) FROM DUAL;
OUTPUT:
MANA
ANALYSIS
When third argument is missing, it takes all the character from starting
position
OUTPUT:
RANA
ANALYSIS
Displays all the employees who joined in the current month
SYSDATE is a single row function, which gives the current date.
INPUT:
SQL> SELECT SUBSTR(‘RAMANA’,1,2) || SUBSTR(‘RAMANA’,-2,2) FROM
DUAL;
OUTPUT:
RANA
ANALYSIS
First two characters and Last two characters are combined together as a
single string
INSTR
To find out where in a string a particular pattern occurs, use INSTR. Its first
argument is the target string. The second argument is the pattern to match.
The third and forth are numbers representing where to start looking and
which match to report.
INPUT
OUTPUT
2
ANALYSIS
OUTPUT
4
ANALYSIS
Find the position of the second occurrence of letter A from the beginning
of the string.
Third argument represents from which position, Fourth argument represents,
which occurrence.
OUTPUT
0
ANALYSIS
INPUT
OUTPUT
6
ANALYSIS
Find the position of the second occurrence of letter A from 3rd position of
the string
TO_CHAR
OUTPUT:
SAL TO_CHAR(SAL)
---------- ----------------------------------------
800 800
1600 1600
1250 1250
2975 2975
1250 1250
2850 2850
2450 2450
3000 3000
5000 5000
1500 1500
1100 1100
950 950
3000 3000
1300 1300
ANALYSIS
INPUT:
OUTPUT:
SYSDATE TO_CHAR(SYSDATE,'DD/MM/YYYY')
--------- ------------------------------
24-MAR-07 24/03/2007
ANALYSIS
INPUT:
OUTPUT:
SYSDATE TO_CHAR(SYSDATE,'DD-MON-YY')
--------- ------------------------------
24-MAR-07 24-MAR-07
INPUT:
OUTPUT:
SYSDATE TO_CHAR(SYSDATE,'DY-MON-YY')
--------- ------------------------------
24-MAR-07 SAT-MAR-07
ANALYSIS:
DY displays the first 3 letters from the day name
OUTPUT:
SYSDATE TO_CHAR(SYSDATE,'DAYMONTHYEAR')
--------- ------------------------------
24-MAR-07 SATURDAY MARCH TWO THOUSAND SEVEN
ANALYSIS:
DAY gives the total day name
MONTH gives the total month name
YEAR writes the year number in words
INPUT:
OUTPUT:
SYSDATE TO_CHAR(SYSDATE,'DDSPTHMONTHYEAR')
--------- -------------------------------------------------------------------
24-MAR-07 TWENTY-FOURTH MARCH TWO THOUSAND SEVEN
ANALYSIS:
DD gives the day number
DDSP Writes day number in words
TH is the format. Depends upon the number it gives either ST / RD/ST/ND
format
OUTPUT:
HIREDATE TO_CHAR(HIREDATE,'DDSPTHMONTHYEAR')
--------- -------------------------------------------------------------------
17-DEC-80 SEVENTEENTH DECEMBER NINETEEN EIGHTY
20-FEB-81 TWENTIETH FEBRUARY NINETEEN EIGHTY-ONE
22-FEB-81 TWENTY-SECOND FEBRUARY NINETEEN EIGHTY-ONE
02-APR-81 SECOND APRIL NINETEEN EIGHTY-ONE
28-SEP-81 TWENTY-EIGHTH SEPTEMBER NINETEEN EIGHTY-ONE
01-MAY-81 FIRST MAY NINETEEN EIGHTY-ONE
09-JUN-81 NINTH JUNE NINETEEN EIGHTY-ONE
09-DEC-82 NINTH DECEMBER NINETEEN EIGHTY-TWO
17-NOV-81 SEVENTEENTH NOVEMBER NINETEEN EIGHTY-ONE
08-SEP-81 EIGHTH SEPTEMBER NINETEEN EIGHTY-ONE
12-JAN-83 TWELFTH JANUARY NINETEEN EIGHTY-THREE
03-DEC-81 THIRD DECEMBER NINETEEN EIGHTY-ONE
03-DEC-81 THIRD DECEMBER NINETEEN EIGHTY-ONE
23-JAN-82 TWENTY-THIRD JANUARY NINETEEN EIGHTY-TWO
ANALYSIS:
Converts all hire dates in EMP table into Words
INPUT:
OUTPUT:
SYSDATE TO_CHAR(SYSDATE,’Q’)
--------- ------------------------------
24-MAR-07 1
ANALYSIS:
OUTPUT:
TO_CHAR(TO_DATE('10-SEP-2005'),'Q')
----------------------------------------
3
ANALYSIS:
To_date is data conversion function, which converts given string into date type
INPUT:
OUTPUT:
SYSDATE TO_CHAR(SYSDATE,’W’)
--------- ------------------------------
24-MAR-07 4
ANALYSIS:
Gives the week number in the current month ( In which week given date falls in the
current month)
INPUT:
OUTPUT:
SYSDATE TO_CHAR(SYSDATE)
--------- ----------------------------
24-MAR-07 12
ANALYSIS:
MSAT GE-GDC Internal
Returns no. of weeks worked during the 64
year.
INPUT:
OUTPUT:
TO_CHAR(SYS
-----------
08:40:17 PM
ANALYSIS:
HH returns Hours }
MI returns Minutes } Returns time from current date
SS returns Seconds }
AM returns AM / PM depends on Time
INPUT:
OUTPUT:
TO_CHAR(
--------
20:43:12
ANALYSIS:
OUTPUT:
TO_CHAR(12567,'99,999.99')
-----------------------------
12,567.00
MSAT GE-GDC Internal
ANALYSIS: 65
Converts the given number into comma format with two decimal places
INPUT:
OUTPUT:
TO_CHAR(12567,'L99,999.99')
-----------------------------
$12,567.00
ANALYSIS:
INPUT:
OUTPUT:
TO_CHAR(-12567,'L99,999.99PR')
-----------------------------------
<$12,567.00>
ANALYSIS:
For example:
INPUT:
OUTPUT:
SAL TO_NUMBER(TO_CHAR(SAL))
---------- -----------------------
800 800
1600 1600
1250 1250
2975 2975
1250 1250
2850 2850
2450 2450
3000 3000
5000 5000
1500 1500
1100 1100
950 950
3000 3000
1300 1300
ANALYSIS
ADD_MONTHS
This function adds a number of months to a specified date.
For example, say a customer deposited some amount on a particular date for a
period of 6 months. To find the maturity date of the deposit
INPUT:
SQL> SELECT ADD_MONTHS (SYSDATE, 6) MATURITY_DATE FROM
DUAL;
OUTPUT:
MATURITY_DATE
--------------------
24-SEP-07
ANALYSIS
It adds 6 months to the system date
INPUT:
SQL> SELECT HIREDATE, ADD_MONTHS(HIREDATE,33*12)
RETIRE_DATE FROM EMP;
OUTPUT:
HIREDATE RETIRE_DATE
--------- ---------------
17-DEC-80 17-DEC-13
20-FEB-81 20-FEB-14
22-FEB-81 22-FEB-14
02-APR-81 02-APR-14
28-SEP-81 28-SEP-14
01-MAY-81 01-MAY-14
09-JUN-81 09-JUN-14
09-DEC-82 09-DEC-15
17-NOV-81 17-NOV-14
08-SEP-81 08-SEP-14
12-JAN-83 12-JAN-16
03-DEC-81 03-DEC-14
03-DEC-81 03-DEC-14
23-JAN-82 23-JAN-15
ANALYSIS
Find the retirement date of an employee
MSATAssume, 33 years of service from date of join is retirement date
GE-GDC Internal
68
INPUT:
SQL> SELECT HIREDATE,
TO_CHAR(ADD_MONTHS(HIREDATE,33*12),’DD/MM/YYYY’)
RETIRE_DATE FROM EMP;
OUTPUT:
HIREDATE RETIRE_DATE
--------- ---------------
17-DEC-80 17/12/2013
20-FEB-81 20/02/2014
22-FEB-81 22/02/2014
02-APR-81 02/04/2014
28-SEP-81 28/09/2014
01-MAY-81 01/05/2014
09-JUN-81 09/06/2014
09-DEC-82 09/12/2015
17-NOV-81 17/11/2014
08-SEP-81 08/09/2014
12-JAN-83 12/01/2016
03-DEC-81 03/12/2014
03-DEC-81 03/12/2014
23-JAN-82 23/01/2015
ANALYSIS
Displaying the retirement date with century.
LAST_DAY
MONTHS_BETWEEN
Used to find the number of months between two given months
INPUT:
SQL> SELECT LAST_DAY(SYSDATE) FROM DUAL;
OUTPUT:
LAST_DAY(SYSDATE)
-------------------------
31-MAR-07
ANALYSIS
Find the last date of the month
ANALYSIS
Finds number of months between sysdate and hiredate . Result is divided
with 12 to get the experience
LOCALTIMESTAMP
Returns Local timestamp in the active time zone, with no time zone information
shown
INPUT
OUTPUT
LOCALTIMESTAMP
------------------------------------
25-MAR-07 06.21.02.312000 PM
This function is used to adjust the time according to the time zone you are in.
Here are the time zones you can use with this function:
INPUT
SQL> select
TO_CHAR(new_time(LOCALTIMESTAMP,'EsT','PDT'),'DD/MM/YYYY HH :
MI :SS PM') from DUAL;
OUTPUT
TO_CHAR(NEW_TIME(LOCALTIM
-------------------------
25/03/2007 04 : 32 :55 PM
ANALYSIS
Like magic, all the times are in the new time zone and the dates are
adjusted.
NEXT_DAY finds the name of the first day of the week that is equal to or later than
another specified date.
INPUT:
SQL> SELECT NEXT_DAY(SYSDATE,’MONDAY’) FROM DUAL;
OUTPUT:
NEXT_DAY(
---------
26-MAR-07
ANALYSIS
If the sysdate is Saturday, March 24, 2007, It display the date of the next
coming Monday.
EXTRACT
We can use Extract function in the place of to_char function from Oracle 9i.
OUTPUT
+000000003-10
Analysis
Returns the difference. No of years and months between both the dates.
Example
OUTPUT
+000000009 11:04:07
Analysis
Find the difference with days and time. For sysdate it takes 0.00 hrs as starting
time
Note :- We can also change the default format for a given session using the ALTER
SESSION command
If the Current year is in the first half of the century ( years 0 through 49), then:
If you enter a date in the first half of the century (i.e. from 0 through 49), RR
returns the current century.
If you enter a date in the latter half of the century (i.e. from 50
through 99), RR returns the previous century.
For example
OUTPUT
When we reach the year 2050, RR will interpret the same dates
differently
NUMTOYMINTERVAL (10.5,'YEAR')
---------------------------------------------------------------------------
+000000010-06
NUMTOYMINTERVAL (10.3,'YEAR')
---------------------------------------------------------------------------
+000000010-03
NUMTODSINTERVAL
Example
OUTPUT
+01 00:00.00.000000
ANALYSIS
Oracle automatically taken care of normalizing the input value of
1440 minutes to an interval value of 1 day.
INPUT:
SQL> SELECT GREATEST(10,1,83,2,9,67) FROM DUAL;
OUTPUT:
GREATEST
---------
83
ANALYSIS
INPUT:
SQL> SELECT NAME,SUB1,SUB2,SUB3, SUB4,
GREATEST(SUB1,SUB2,SUB3,SUB4) GREATEST_MARK,
LEAST(SUB1,SUB2,SUB3,SUB4) LEAST_MARK FROM STUDENT
OUTPUT:
ROLLNO NAME SUB1 SUB2 SUB3 SUB4 GREATEST LEAST
MARK MARK
1 RAVI 55 22 86 45 86 22
2 KRIS 78 55 65 12 78 12
3 BABU 55 22 44 77 77 22
4 ANU 44 55 66 88 88 44
USER returns the character name of the current user of the database.
INPUT:
SQL> SELECT USER FROM DUAL;
OUTPUT:
USER
--------
SCOTT
ANALYSIS
Displays the current sessions user name
We can also display username using environment command
SQL> SHOW USER
SYNTAX:
DECODE (column1, value1, output1, value2, output2, output3)
If column1 has a value of value1, then display output1 instead of the column's
current value.
If column1 has a value of value2, then display output2 instead of the column's
current value.
If column1 has a value of anything other than value1 or value2, then display
output3 instead of the column's current value.
OUTPUT
ENAME JOB PROMOTION
---------- --------- ---------
SMITH CLERK EXEC
ALLEN SALESMAN S.OFFICER
WARD SALESMAN S.OFFICER
JONES MANAGER VP
MARTIN SALESMAN S.OFFICER
BLAKE MANAGER VP
CLARK MANAGER VP
SCOTT ANALYST PM
KING PRESIDENT PRESIDENT
TURNER SALESMAN S.OFFICER
ADAMS CLERK EXEC
JAMES CLERK EXEC
FORD ANALYST PM
MILLER CLERK EXEC
ANALYSIS
When JOB has a value CLERK , then display EXEC instead of CLERK
When JOB has a value SALESMAN , then display S.OFFICER instead of SALESMAN
When JOB has a value ANALYST , then display PM instead of ANALYST
When JOB has a value MANAGER , then display VP instead of MANAGER
OTHERWISE DISPLAY SAME JOB
INPUT
SQL> SELECT ENAME,SEX,DECODE(SEX,’MALE’,’MR.’||ENAME,
‘MS.’||ENAME) FROM EMP;
ANALYSIS
Adding Mr.’ or ‘Ms.’ before the name based on their Gender
As of Oracle 9i, you can use the CASE function in place of DECODE. The CASE
function uses the keywords when, then, else, and end to indicate the logic path
followed, which may make the resulting code easier to follow than an equivalent
DECODE.
Example
JOB CASEJOBWH
--------- ---------
CLERK EXEC
SALESMAN S.OFFICER
SALESMAN S.OFFICER
MANAGER VP
SALESMAN S.OFFICER
MANAGER VP
MANAGER VP
ANALYST ANALYST
PRESIDENT PRESIDENT
SALESMAN S.OFFICER
CLERK EXEC
CLERK EXEC
ANALYST ANALYST
CLERK EXEC
ANALYSIS
Works similar to that of DECODE
If the value is NULL, this function is equal to substitute. If the value is not NULL,
this function is equal to value. Substitute can be a literal number, another column,
or a computation.
NVL is not restricted to numbers, it can be used with CHAR, VARCHAR2, DATE,
and other data types, but the value and substitute must be the same data type.
INPUT
OUTPUT
EMPNO SAL COMM TOTAL
---------- ---------- ---------- ----------
7369 800
7499 1600 300 1900
7521 1250 500 1750
7566 2975
7654 1250 1400 2650
7698 2850
7782 2450
7788 3000
7839 5000
7844 1500 0 1500
7876 1100
7900 950
7902 3000
7934 1300
ANALYSIS
Arithmetic operation is possible only when value is there in both columns
OUTPUT
EMPNO SAL COMM TOTAL
---------- ---------- ---------- ----------
7369 800 800
7499 1600 300 1900
7521 1250 500 1750
7566 2975 2975
7654 1250 1400 2650
7698 2850 2850
7782 2450 2450
7788 3000 3000
7839 5000 5000
7844 1500 0 1500
7876 1100 1100
7900 950 950
7902 3000 3000
7934 1300 1300
ANALYSIS
Using NVL, we are substituting 0 if COMM is NULL.
INPUT
SQL>SELECT DEPTNO,SUM(SAL),RATIO_TO_REPORT(SUM(SAL))
OVER() FROM EMP GROUP BY DEPTNO;
OUTPUT
DEPTNO SUM(SAL) RATIO_TO_REPORT(SUM(SAL))OVER()
---------- ---------- -------------------------------
10 8750 .301464255
20 10875 .374677003
30 9400 .323858742
ANALYSIS
RATIO_TO_REPORT FUNCTION FINDS THE SALARY RATIO OF THAT DEPARTMENT
OVER THE TOTAL SALARY OF ALL THE EMPLOYEES.
ASCII
Finds the ASCII value of the given character
CAST
Converts one type of information into another type
Exercise
Group by statement groups all the rows with the same column value.
Use to generate summary output from the available data.
Whenever we use a group function in the SQL statement, we have to use a group
by clause.
INPUT
SQL> SELECT JOB, COUNT (*) FROM EMP GROUP BY JOB;
OUTPUT
JOB COUNT(*)
--------- ----------
ANALYST 2
CLERK 4
MANAGER 3
PRESIDENT 1
SALESMAN 4
ANALYSIS
Counts number of employees under each and every job.
When we are grouping on job, initially jobs are placed in ascending
order in a temporary segment.
On the temporary segment, group by clause is applied, so that on each
similar job count function applied.
INPUT
SQL> SELECT JOB, SUM (SAL) FROM EMP GROUP BY JOB;
OUTPUT
JOB SUM(SAL)
--------- ----------
ANALYST 6000
CLERK 4150
MANAGER 8275
PRESIDENT 5000
SALESMAN 5600
ANALYSIS
Note :
INPUT
OUTPUT
SELECT JOB, COUNT (*) FROM EMP
*
ERROR at line 1:
ORA-00937: not a single-group group function
ANALYSIS
This result occurs because the group functions, such as SUM and
COUNT, are designated to tell you something about a group or rows,
not the individual rows of the table. This error is avoided by using
JOB in the group by clause, which forces the COUNT to count all the
rows grouped within each job.
INPUT
OUTPUT
ANALYSIS
In the above query, JOB is only the grouped column where as ENAME
column is not a grouped column.
What ever the columns we are grouping, the same column is allowed to
display.
OUTPUT
JOB MIN(SAL) MAX(SAL)
--------- ---------- ----------
ANALYST 3000 3000
CLERK 800 1300
MANAGER 2450 2975
PRESIDENT 5000 5000
SALESMAN 1250 1600
ANALYSIS
With each job, it finds the MINIMUM AND MAXIMUM SALARY
INPUT
SQL> SELECT JOB, SUM(SAL),AVG(SAL),MIN(SAL),MAX(SAL) ,COUNT(*)
FROM EMP GROUP BY JOB;
OUTPUT
JOB SUM(SAL) AVG(SAL) MIN(SAL) MAX(SAL) COUNT(*)
--------- ---------- ---------- ---------- ---------- ----------
ANALYST 6000 3000 3000 3000 2
CLERK 4150 1037.5 800 1300 4
MANAGER 8275 2758.33333 2450 2975 3
PRESIDENT 5000 5000 5000 5000 1
SALESMAN 5600 1400 1250 1600 4
ANALYSIS
INPUT
OUTPUT
ANALYSIS
When we apply group by, initially all the designations are placed in ascending order of
designations.
Then group by clause groups similar designations, then DECODE function (Single
row function) applies on each and every row of that group and checks the DEPTNO. If
DEPTNO=10, it passes corresponding salary as an argument to SUM() .
INPUT
OUTPUT
DEPTNO JOB COUNT(*)
---------- --------- ----------
10 CLERK 1
10 MANAGER 1
10 PRESIDENT 1
20 CLERK 2
20 ANALYST 2
20 MANAGER 1
30 CLERK 1
30 MANAGER 1
30 SALESMAN 4
ANALYSIS
INPUT
OUTPUT
DEPTNO JOB COUNT(*)
---------- --------- ----------
10 CLERK 1
MANAGER 1
PRESIDENT 1
20 CLERK 2
ANALYST 2
MANAGER 1
30 CLERK 1
MANAGER 1
SALESMAN 4
ANALYSIS
The ROLLUP and CUBE operators are available only in Oracle8i and later releases.
Syntax
We can use CUBE function to generate subtotals for all combinations of the values
in the group by clause.( CUBE and ROLLUP are available only from 9i)
INPUT
SQL> SELECT DEPTNO,JOB,COUNT(*) FROM EMP GROUP BY
CUBE(DEPTNO,JOB);
OUTPUT
DEPTNO JOB COUNT(*)
---------- --------- ----------
14
CLERK 4
ANALYST 2
MANAGER 3
SALESMAN 4
PRESIDENT 1
10 3
10 CLERK 1
10 MANAGER 1
10 PRESIDENT 1
20 5
20 CLERK 2
20 ANALYST 2
20 MANAGER 1
30 6
30 CLERK 1
30 MANAGER 1
ANALYSIS
Cube displays the out with all the permutation and combination of all the columns
given a CUBE function.
INPUT
SQL> SELECT DEPTNO,JOB,COUNT(*) FROM EMP GROUP BY
ROLLUP(DEPTNO,JOB)
OUTPUT
DEPTNO JOB COUNT(*)
---------- --------- ----------
10 CLERK 1
10 MANAGER 1
10 PRESIDENT 1
10 3
20 CLERK 2
20 ANALYST 2
20 MANAGER 1
20 5
30 CLERK 1
30 MANAGER 1
30 SALESMAN 4
30 6
14
HAVING CLAUSE
Whenever we are using a group function in the condition, we have to use having
clause. Having clause is used along with group by clause.
JOB SUM(SAL)
--------- ----------
ANALYST 6000
CLERK 4150
MANAGER 8275
PRESIDENT 5000
SALESMAN 5600
INPUT
SQL> SELECT JOB,SUM(SAL) FROM EMP WHERE SUM(SAL) > 5000
GROUP BY JOB;
OUTPUT
SELECT JOB,SUM(SAL) FROM EMP WHERE SUM(SAL) > 5000 GROUP BY JOB
*
ERROR at line 1:
ORA-00934: group function is not allowed here
ANALYSIS
INPUT
SQL> SELECT JOB,SUM(SAL) FROM EMP GROUP BY JOB HAVING
SUM(SAL) > 5000;
OUTPUT
JOB SUM(SAL)
--------- ----------
ANALYST 6000
MANAGER 8275
SALESMAN 5600
ANALYSIS
Displays all the designations whose total salary is more than 5000.
OUTPUT
JOB COUNT(*)
--------- ----------
CLERK 4
MANAGER 3
SALESMAN 4
ANALYSIS
Displays all the designations whose number where employees between 3 and 5
INPUT
SQL> SELECT SAL FROM EMP GROUP BY SAL HAVING COUNT(SAL) > 1;
OUTPUT
SAL
----------
1250
3000
ANALYSIS
Displays all the salaries, which are appearing more than one time in the table.
ORDER OF EXECUTION
Here are the rules ORCALE uses to execute different clauses given in SELECT
command
Example
INPUT
SQL> SELECT JOB,SUM (SAL) FROM EMP WHERE JOB != ‘CLERK’
GROUP BY JOB HAVING SUM(SAL) > 5000 ORDER BY JOB DESC;
EXERCISE
ANNEXURE – A QUERY 2
Nesting is the act of embedding a sub query within another sub query.
SYNTAX
For example,
OUTPUT
ENAME SAL
------------ ----------
KING 5000
ANALYSIS
Right side query is called as child query and left side query is called parent
query. In nested queries, child query executes first before executing parent
query.
INPUT
SQL> SELECT ENAME, HIREDATE FROM EMP WHERE HIREDATE =
( SELECT MAX(HIREDATE) FROM EMP);
OUTPUT
ENAME HIREDATE
---------- ---------
ADAMS 12-JAN-83
ANALYSIS
Display the least experienced employee
OUTPUT
ENAME SAL
---------- ----------
SMITH 800
ALLEN 1600
WARD 1250
JONES 2975
MARTIN 1250
BLAKE 2850
CLARK 2450
SCOTT 3000
TURNER 1500
ADAMS 1100
JAMES 950
FORD 3000
MILLER 1300
ANALYSIS
Query
To display all the employees whose salary lines between minimum and maximum
salaries
INPUT
Query
Display all the employees from department 30 whose salary is less than maximum
salary of department 20.
INPUT
SQL>SELECT ENAME,SAL FROM EMP WHERE SAL IN(SELECT
SAL FROM EMP GROUP BY SAL HAVING COUNT(*)> 1);
OUTPUT
ENAME SAL
---------- - ---------
WARD 1250
MARTIN 1250
SCOTT 3000
FORD 3000
ANALYSIS
Displays all the employees who are drawing similar salaries
When child query returns more than one value, we have to use IN operator for
comparison.
OUTPUT
EMPNO ENAME DEPTNO SAL
---------- ---------- ---------- ----------
7839 KING 10 5000
7788 SCOTT 20 3000
7902 FORD 20 3000
7698 BLAKE 30 2850
ANALYSIS
Display all the employees who are drawing maximum salaries in each department
To modify the salary of an employee who is drawing minimum salary with the
salary of the employee who is drawing maximum salary
INPUT
SQL> UPDATE EMP SET SAL = (SELECT MAX(SAL) FROM EMP) WHERE
EMPNO = (SELECT EMPNO FROM EMP WHERE SAL =
(SELECT MIN (SAL) FROM EMP));
ANALYSIS
Identify the employee who is drawing minimum salary and update with the
maximum salary of all the employees.
INPUT
SQL> INSERT INTO EMP1
SELECT * FROM EMP ;
ANALYSIS
EMP1 is an existing table. Inserts all the selected rows into EMP1 table.
A correlated sub query is a sub query that receives a value from the main query
and then sends a value back to main query.
For example
Display all the employees whose salary is less than maximum salary of each
department
SQL> SELECT EMPNO,ENAME,DEPTNO,SAL FROM EMP X WHERE SAL < (SELECT MAX(SAL)
FROM EMP WHERE DEPTNO = X.DEPTNO);
ANALYSIS
Find department wise maximum salaries and display the employees whose salary
is less than that value for each department
OUTPUT
ANALYSIS
It selects each row from emp table from parent query and finds the distinct count for
each salary whose salary >= the salary returned by main query.
Table joins should be written first before any condition of WHERE clause. And
the conditions which filter out the maximum records should be placed at the end
after the joins as the parsing is done from BOTTOM to TOP.
Both are used for comparing one value against a set of values.
SYNTAX
INPUT
SQL> SELECT EMPNO,ENAME,SAL FROM EMP WHERE SAL > ANY(SELECT SAL FROM EMP);
OUTPUT
SQL> SELECT EMPNO,ENAME,SAL FROM EMP WHERE SAL < ANY (SELECT SAL FROM
EMP);
OUTPUT
ANALYSIS
INPUT
SQL> SELECT EMPNO,ENAME,SAL FROM EMP WHERE SAL >ALL(SELECT SAL FROM
EMP);
OUTPUT
no rows selected
ANALYSIS
INPUT
OUTPUT
ANALYSIS
Greater than maximum of List
OUTPUT
ANALYSIS
Less than minimum of List
These two operators are exclusively used in correlated sub query. EXISTS checks
whether any row is existing in the sub query, and NOT EXISTS does the opposite.
EXISTS is different from other operators like IN , ANY etc, because it doesn’t
compare values of columns, instead. It checks any row is retrieved from sub query
or not. If any row is retrieved from sub query the EXISTS returns true otherwise it
returns False.
INPUT
SQL> SELECT EMPNO,ENAME,SAL,MGR FROM EMP X WHERE EXISTS(SELECT MGR FROM EMP
WHERE X.MGR = EMPNO);
OUTPUT
EMPNO ENAME SAL MGR
---------- ---------- ---------- ----------
7369 SMITH 800 7902
7499 ALLEN 1600 7698
7521 WARD 1250 7698
7566 JONES 2975 7839
7654 MARTIN 1250 7698
7698 BLAKE 2850 7839
7782 CLARK 2450 7839
7788 SCOTT 3000 7566
7844 TURNER 1500 7698
7876 ADAMS 1100 7788
7900 JAMES 950 7698
7902 FORD 3000 7566
7934 MILLER 1300 7782
Remember
The following important points to be remembered while dealing with sub queries
Sub query can not use ORDER BY clause. Because ORDER BY clause must be
the last clause of SELECT
BETWEEN … AND operator can not be used with Sub queries
Exercise
Display all the employees whose salary is within ±1000 from the average
salary of all the employees.
Display all the employees whose salary is less than the minimum salary of
MANAGERS.
Display the details of students who have paid the highest amount so far in
their course.
Display the details of subjects that have been taken by more than two
students
Constraints are used to implement standard rules such as uniqueness in the key
filed and business rule such as AGE column should contain a value between 15
and 60 etc.
Oracle server makes sure that the constraints are not violated whenever a row is
inserted, deleted or updated. If constraint is not satisfied the operation will fail.
Constraints are normally defined at the time of creating table. But it is also
possible to define constraints after the table is created.
Constraint Guidelines
Table Constraints
Column Constraints
PRIMARY KEY
UNIQUE
NOT NULL
CHECK
PRIMARY KEY It is used to uniquely identify rows in a table. There can be only
one primary key in a table. It may consist of more than one column, if so, it is
called as composite primary key. ( It maintains uniqueness in the data and null
values are not acceptable).
Example : EmailID
NOT NULL Uniqueness not maintained and null values are not acceptable.
Note: The NOT NULL constraint can be specified only at the column level, not at
the table level.
Note: - Pseudocolumns are not actual columns in a table but they behave like
columns. For example, you can select values from pseudocolumns. However, you
cannot insert into, update, or delete from a pseudocolumn.
Create Table
Syntax :-
Column Def :
<Name> Data type [Default Value] [constraint <name> constraint type]
Rules: -
1. A table or a column name must never start a number but they can contain
numbers in them
2. They can’t consist of any special characters other than “$”, “#”, “-“
i.e. $,# are used mainly for system tables.
Example :
Note :
Constraint name is useful for manipulating the given constraint
When the constraint name is not given at the time of defining constraints,
system creates a constraint with the name SYS_Cn.
OUTPUT
CONSTRAINT_NAME CONSTRAINTTYPE SEARCH_CONDITION
------------------------------ - ------------------------------------------------------------------------------
SYS_C003018 C "ENAME" IS NOT NULL
PK_EMPL47473_EMPNO P
SYS_C003022
SQL> DESCRIBE U
USER_CONS_COLUMNS
SQL> SELECT CONSTRAINT_NAME,COLUMN_NAME FROM
ANALYSIS
USER_CONS_COLUMNS WHERE TABLE_NAME =
'EMPL47473';
Describe displays structure of the data dictionary table.
Select statement is used to view the constraints defined on the table
OUTPUT
CONSTRAINT_NAME COLUMN_NAME
------------------------------ - --------------------------------
CHK_EMPL47473_GENDER GENDER
PK_EMPL47473_EMPNO EMPNO
SYS_C003018 ENAME
SYS_C003020 SALARY
SYS_C003022 EMAIL_ID
ANALYSIS
MSAT GE-GDC Internal
113
Describe displays structure of the data dictionary table.
Select statement is used to view the constraints defined on the column
MSAT GE-GDC Internal
114
ALTER TABLE
Used to modify the structure of a table
SYNTAX
ALTER TABLE <TABLENAME> [ ADD | MODIFY | DROP |
RENAME] ( COLUMN(S));
INPUT
SQL> ALTER TABLE EMPL47473 DROP PRIMARY KEY;
ANALYSIS
To remove the primary key from table. Other constraints are removed
only by referring constraint name.
INPUT
SQL>ALTER TABLE EMPL47473 ADD PRIMARY KEY(EMPNO);
ANALYSIS
To add primary key in the table with out constraint name. It creates
constraint name with SYS_Cn.
ANALYSIS
To add primary key in the table with constraint name
DATA MANIPULATION
INSERTING ROWS
SYNTAX
INSERT INTO TABLENAME [ COLUMNNAME,COLUMNNAME,
….]
VALUES(VALUE1,VALUE2,VALUE3, …..);
ANALYSIS
We can’t skip primary key and NOT NULL columns
SQL>COMMIT;
ANALYSIS
Information from shadow page flushed back to the table and shadow
page gets destroyed automatically.
SQL>ROLLBACK;
ANALYSIS
SAVEPOINT
We can use save points to roll back portions of your current set of transactions
For example
SQL> SAVEPOINT A
SQL> SAVEPOINT B
The output shows the three new records we’ve added . Now roll back just the last
insert:
SQL> ROLLBACK TO B;
IMPLICIT COMMIT
The actions that will force a commit to occur, even without your instructing it to, or
quit, exit (the equivalent to exit), any DDL command forces a commit.
AUTO ROLLBACK
If you’ve completed a series of inserts, updates or deletes, but not yet explicitly or
implicitly committed them, and you experience serious difficulties, such as a
computer failure, Oracle automatically roll back any uncommitted work. If the
machine or database goes down, it does this as cleanup work the next time the
database is brought back up.
Note :
SYNTAX
CREATE TABLE <TABLENAME> AS SELECT <COLUMNS> FROM
<EXISTING TABLE> [WHERE <CONDITION>];
Example
SQL> CREATE TABLE EMP47473 AS SELECT EMPNO,ENAME,SAL,JOB
FROM EMP;
UPDATING ROWS
SYNTAX
TRUNCATING A TABLE
SYNTAX
Note : Removes all the rows from table. Deleting specified rows is
Not possible. Once the table is truncated, it automatically
commits. It is a DDL statement
Droping a table
SYNTAX
You can add comments up to 2000 bytes about a column, table, view by
using the COMMENT statement. The comment is stored in the data
dictionary and can be viewed in one of the following data dictionary views in
the COMMENTS column:
ALL_COL_COMMENTS
USER_COL_COMMENTS
ALL_TAB_COMMENTS
USER_TAB_COMMENTS
Syntax
Foreign Key
References
On delete cascade
On Delete Set NULL
Foreign Key: Defines the column in the child table at the table constraint level
On delete cascade Deletes the dependent rows in the child table when a row in
the parent table is deleted.
Example
Solution
SQL>Create table itemtran (trnno number (3), itemno number (3) references
itemmaster (itemno), trndate date, trntype char (1) check (upper (trntype) in
(‘R’,’I’)), quantity number (3) check (stock > 0), primary key (trnno, itemno));
Itemmaster
Itemno itemname stock
Itemtran
Trnno itemno trndate trntype quantity
ANALYSIS
Removing the primary key along with Reference key
Exercise
Objectives
Join will enable you to gather and manipulate data across several tables. By
One of the most powerful features of SQL is its capability to gather and
manipulate data from across several tables. Without this feature you would
have to store all the data elements necessary for each application in one
table. Without common tables you would need to store the same data in
several tables.
Objectives
Types of Joins
The Oracle 9i database offers join syntax that is SQL: 1999 compliant. Prior
to 9i release, the join syntax was different from the ANSI standards. The new
SQL: 1999 compliant join syntax does not offer any performance benefits
over the Oracle proprietary join syntax that existed in prior releases.
FROM table1,table2
Guidelines
When writing a SELECT statement that joins tables, precede the common
column name with the table name for clarify and to enhance database
access.
If the same column name appears in more than one table, the column name
must be prefixed with the table name.
To join n tables together, you need a minimum of n-1 join conditions. This rule
many not apply if your table has a concatenated primary key, in which case
more than one column is required to uniquely identify each row.
Departments Employees
Extracting the information from more than one table by comparing ( = ) the
common information.
Note : Equi Joins are also called as simple joins or Inner Joins
ANALYSIS
Efficiency is more when we compare the information from lower data
table(master table) to Higher data table( child table).
ANALYSIS
Non-Equi joins
Getting the information from more than one table without using comparison
(=) operator.
INPUT
SQL> select empno,ename,sal,grade,losal,hisal from salgrade g,emp e
where e.sal between g.losal and g.hisal
/
ANALYSIS
Displays all the employees whose salary lies between any pair of low and high salary ranges.
INPUT
SQL> SELECT * FROM DEPT WHERE DEPTNO NOT IN
(SELECT DISTINCT DEPTNO FROM EMP);
OUTPUT
DEPTNO DNAME LOC
---------- -------------- -------------
40 OPERATIONS BOSTON
ANALYSIS
Displays the details of the department where there are no employees
It is a join, which forcibly joins multiple tables even without having the
common information. It is represented by +.
OUTPUT
EMPNO ENAME JOB SAL DNAME
---------- ---------- --------- ---------- --------------
7782 CLARK MANAGER 2450 ACCOUNTING
7839 KING PRESIDENT 5000 ACCOUNTING
7934 MILLER CLERK 1300 ACCOUNTING
7369 SMITH CLERK 800 RESEARCH
7876 ADAMS CLERK 1100 RESEARCH
7902 FORD ANALYST 3000 RESEARCH
7788 SCOTT ANALYST 3000 RESEARCH
7566 JONES MANAGER 2975 RESEARCH
7499 ALLEN SALESMAN 1600 SALES
7698 BLAKE MANAGER 2850 SALES
7654 MARTIN SALESMAN 1250 SALES
7900 JAMES CLERK 950 SALES
7844 TURNER SALESMAN 1500 SALES
7521 WARD SALESMAN 1250 SALES
OPERATIONS
ANALYSIS
Gets the common information, and forcibly joins from left side table to right side
table.
OUTPUT
EMPNO ENAME JOB DEPTNO DNAME
---------- ---------- --------- ---------- --------------
7369 SMITH CLERK 20 RESEARCH
7499 ALLEN SALESMAN 30 SALES
7521 WARD SALESMAN 30 SALES
7566 JONES MANAGER 20 RESEARCH
7654 MARTIN SALESMAN 30 SALES
7698 BLAKE MANAGER 30 SALES
7782 CLARK MANAGER 10 ACCOUNTING
7788 SCOTT ANALYST 20 RESEARCH
7839 KING PRESIDENT 10 ACCOUNTING
7844 TURNER SALESMAN 30 SALES
7876 ADAMS CLERK 20 RESEARCH
7900 JAMES CLERK 30 SALES
7902 FORD ANALYST 20 RESEARCH
7934 MILLER CLERK 10 ACCOUNTING
40 OPERATIONS
MSAT GE-GDC Internal
ANALYSIS 135
Gets the common information from both tables, then forcibly joins from dept table to
emp table.
SQL> SELECT EMPNO, ENAME, JOB, DEPT.DEPTNO, DNAME FROM DEPT
RIGHT OUTER JOIN EMP ON DEPT.DEPTNO = EMP.DEPTNO;
OUTPUT
EMPNO ENAME JOB DEPTNO DNAME
---------- ---------- --------- ---------- --------------
7369 SMITH CLERK 20 RESEARCH
7499 ALLEN SALESMAN 30 SALES
7521 WARD SALESMAN 30 SALES
7566 JONES MANAGER 20 RESEARCH
7654 MARTIN SALESMAN 30 SALES
7698 BLAKE MANAGER 30 SALES
7782 CLARK MANAGER 10 ACCOUNTING
7788 SCOTT ANALYST 20 RESEARCH
7839 KING PRESIDENT 10 ACCOUNTING
7844 TURNER SALESMAN 30 SALES
7876 ADAMS CLERK 20 RESEARCH
7900 JAMES CLERK 30 SALES
7902 FORD ANALYST 20 RESEARCH
7934 MILLER CLERK 10 ACCOUNTING
ANALYSIS
Gets the common information from both tables, and then forcibly joins from dept table
to emp table.
OUTPUT
EMPNO ENAME JOB DEPTNO DNAME
---------- ---------- --------- ---------- --------------
7369 SMITH CLERK 20 RESEARCH
7499 ALLEN SALESMAN 30 SALES
7521 WARD SALESMAN 30 SALES
7566 JONES MANAGER 20 RESEARCH
7654 MARTIN SALESMAN 30 SALES
7698 BLAKE MANAGER 30 SALES
7782 CLARK MANAGER 10 ACCOUNTING
7788 SCOTT ANALYST 20 RESEARCH
7839 KING PRESIDENT 10 ACCOUNTING
7844 TURNER SALESMAN 30 SALES
7876 ADAMS CLERK 20 RESEARCH
7900 JAMES CLERK 30 SALES
7902 FORD ANALYST 20 RESEARCH
7934 MILLER CLERK 10 ACCOUNTING
40 OPERATIONS
ANALYSIS
Gets the common information from both tables, then forcibly joins from dept table to
emp table.
For ex;
SELF JOIN
WORKER.ENAME||'ISWORKINGUNDER'||MANAGE
--------------------------------------
SCOTT IS WORKING UNDER JONES
FORD IS WORKING UNDER JONES
ALLEN IS WORKING UNDER BLAKE
WARD IS WORKING UNDER BLAKE
JAMES IS WORKING UNDER BLAKE
TURNER IS WORKING UNDER BLAKE
MARTIN IS WORKING UNDER BLAKE
MILLER IS WORKING UNDER CLARK
ADAMS IS WORKING UNDER SCOTT
JONES IS WORKING UNDER KING
CLARK IS WORKING UNDER KING
BLAKE IS WORKING UNDER KING
SMITH IS WORKING UNDER FORD
ANALYSIS
It displays who is working under whom.
MGR number appearing against employee is the employee number of
manager
NATURAL AND INNER JOINS (Introduced in 9i)
The Natural join clause is based on all columns in the two tables
that have the same name,
It selects rows from the two tables that have equal values in all
matched columns.
If the columns having the same names have different data types,
an error is returned.
OUTPUT
■ If several columns have the same names but the data types do
not match, the NATURAL JOIN clause can be modified with
USING clause to specify the columns that should be used for an
equijoin.
■use the USING clause to match only one column when more than
one column matches.
Support for INNER join syntax was introduced in Oracle9i, inner joins are
the default – they return the rows the two tables have in common, and are
the alternative to outer joins. Note that they support ON clause, so that you
can specify join criteria.
INPUT
ANALYSIS
It multiplies the rows from both tables and displays the output
i.e. 14 rows (emp table) X 4 rows(dept table) = 56 rows.
EXERCISE
SEQUENCE OBJECT
SYNTAX
START WITH n specifies the first sequence number to be generated (If this
clause is
omitted, the sequence starts with 1.)
VIEWS
SIMPLE view is a view, which is created using only one base table.
COMPLEX view is a view, which is created using more than one table or
using group functions
INLINE view is a view, which is created using sub query (it is not a schema
object. • It is a named sub query in the FROM clause of the main query. Generally
used in TOP N Analysis.
SYNTAX
The following are the rules that are to be satisfied to update base table
through view.
Example
ANALYSIS
View becomes a read only view
This option is used to prevent any changes to base table through view.
Insertion and updation is not allowed into base table through view.
We can also create a view using group functions. Such views are called as
INLINE views. They are by default read only.
To remove a view
The concept indexing in Oracle is same as a book index. Just like how book
index is sorted in the ascending order of topics, an index in Oracle is a list of
values of a column in the ascending order. Page number in book index is
similar to ROWID if Oracle index.
SYNTAX
CREATE [UNIQUE] INDEX index_name ON table(column1,column2,…);
Oracle index is completely automatic. I.e., you never have to open or close
an index. Oracle server decides whether to use an index or not.
The following are the cases in which Oracle does NOT use index.
Having many indexes may have negative impact on the performance because
whenever there is a change in the table, immediately index is to reflect that
change. A new row’s insertion will effect index and Oracle server implicitly
updates index. So this will put more burden on the machine if more number
of indexes are created on a table.
FUNCTIONAL INDEX
Dropping an Index
SYNTAX
Example
ROWID
ROWNUM
SYADATE
NEXTVAL
CURRVAL
NULL
LEVEL
Exercise
6)Find out how many columns are there in a given table(Use the
data dictionary table USER_TAB_COLUMNS)
ANALYTICAL QUERIES
Analytical functions are used mainly for the analysis of data as required by
decision-making managers.
Oracle has embedded analytical functions in SQL statement to cater to most
of the requirements of data mining.
SQL> SELECT RANK() OVER(ORDER BY SAL DESC) DEFAULT_RANK, SAL FROM EMP;
DEFAULT_RANK SAL
------------ ----------
1 855945.6
1 855945.6
1 855945.6
4 641959.2
5 196867.32
6 184563.24
7 153802.68
7 153802.68
9 129461.88
10 111807.6
11 66870.77
12 10000
13 6810.91
SQL> SELECT DENSE_RANK() OVER(ORDER BY SAL DESC) DEFAULT_RANK, SAL FROM EMP;
DEFAULT_RANK SAL
------------ ----------
1 855945.6
1 855945.6
1 855945.6
2 641959.2
3 196867.32
4 184563.24
5 153802.68
5 153802.68
6 129461.88
7 111807.6
8 66870.77
9 10000
10 6810.91
ROW_NUMBER
The function row number assigns unique rank to each row even if they are
having the same value of order by expression. The rows will get the same
rank if their order by expression has the same value.
INPUT
OUTPUT
This function produces NULL value if the expression has a specified value.
It produces NULL value if the expression has a specified value. This is like a
complement of the NVL function.
INPUT
OUTPUT
ANALYSIS
It is just opposite to NVL(). NVL() substitute value, if its is NULL.
Where as NULLIF produces NULL, if value matches.
NVL2 Function
Syntax
NVL2(expr1,expr2,expr3)
The expr1 can have any data type. The arguments expr2 and expr3 can have
any datatype except LONG.
INPUT
OUTPUT
COMM NVL2(COMM,COMM,0)
---------- -----------------
0
300 300
500 500
0
1400 1400
0
0
0
0
0 0
0
0
0
0
SQL> SELECT ENAME, COMM, SAL, DEPTNO, MGR, COALESCE (COMM, SAL, DEPTNO, MGR)
COAL FROM EMP;
Oracle 9i provides enhanced facility of loading data in the table using select
statement.
This statement enables to you insert data in multiple tables using a single
insert statement.
Example1(pname,title,salary)
Example2(pname,course,cost)
Insert all
Into example1 values(pname,title,salary)
Into example2 values(pname,course,cost)
Select p.pname,title,course,cost,salary from programmer p,software s,
studies st
Where p.pname = s.pname and s.pname = st.pname;
It inserts the data into the table only when condition is satisfied.
Assume there are three tables with structure (table1,table2,table3)
Empno.ename,job,sal,deptno
We can load the data conditionally into three tables by using following
statement
Insert first
When deptno = 10 then
Insert into table1 values(empno,ename,job,sal,deptno);
When deptno = 20 then
Insert into table2 values(empno,ename,job,sal,deptno);
When deptno = 30 then
Insert into table3 values(empno,ename,job,sal,deptno);
Select empno,ename,sal,deptno from emp;
The difference between Insert First and Insert All is that in the formar at the
most one row is inserted into the table while latter rows may be inserted into
multiple tables.
DML locks - used to protect data. Can be either table or row level.
Dictionary locks – used to protect the database structure
With this SELECT we lock all the rows in the result set for later update. The
FOR UPDATE tells Oracle to lock each row as it processes it.
The NOWAIT keyword specifies that we don’t want the statement to wait
until, and current locks on the table are removed.
In the Scott user there is one table with the name EMP.
Scott has given some privileges on EMP table to X user.
Now from SCOTT user , if he tries to the lock the table, which is already
locked by X
It results an error
What is a privilege
Privileges are classified into two categories depending upon what type of
right they give to the user.
Object Privileges
System privileges
Object privilege
System privilege
Object Privileges
User owns the object that he/she creates. Unless otherwise specified, only
the owner and DBA can access the object.
But, if user wants to share his object with other users, he has to grant
privileges on the object to other users.
SYNTAX
GRANT <PRIVILEGES> | ALL [(COLUMN1,COLUMN2)] ON <OBJECT>
TO (USER | PUBLIC | ROLE) [ WITH GRANT OPTION];
Example
Note :- X is a user
Now from X user, he can select as well as update the information in EMP
table.
So, X user can modify only sal value in the EMP table.
Using Synonyms
Private Synonyms
Now we can access EMP table which is there in SCOTT user using synonym
EMPL as
Public Synonym
SQL*Loader is Oracle’s utility program for loading data into an Oracle table.
Most often, SQL*Loader takes two input files – a control file and a data file – and loads the
data into a single Oracle table. The data file contains data, and the control file contains
information about the data -- where to load it, what to do if something goes wrong, etc.
SQL*Loader has lots and lots of options which can be used to handle various types of data
and levels of complexity. SQL*Loader is fully described in the Oracle Server Utilities
User’s Guide. This document is just about getting started. SQL*Loader runs on Unix,
mainframes, and PC’s. This document is just about running it from a Windows PC.
If you need to transfer quite a lot of data from your machine to an Oracle database table, you
might want to use SQL*Loader. If you already have the data in some other format, it may
be worthwhile to use SQL*Loader. If you need to transfer local data to a remote database on
some recurring basis, it may be preferable to use SQL*Loader rather than something like
FTP. At the end of this document, there is a brief comparison of FTP versus SQL*Loader.
(Is 50 rows of data really sufficient to justify this exercise? That’s debatable, but let’s say
you’ve thought it over and you DO want to SQL*load your data into a 4-column Oracle table
at UW-Stevens Point. The remote table is called sp.mystates.)
1) Create your data file. This is easy. Save your Excel spreadsheet data AS a Comma-
Separated-Variable (*.csv) file. This will automatically put commas between each of the
four data elements. In addition, if any of the data elements already contain a comma, the
Save AS *.csv step will optionally and automatically enclose that data in double quotes.
So, after your Save AS command, you might have a file named C:\MyStates.csv that
contains data like this:
Because the first three items are of character datatype, it was not necessary to further
describe them – character is the default. The fourth column is numeric data – it totals the
number of state residents who drink bottled water. The INTEGER EXTERNAL describes
the datatype in the C:\mystates.csv input file.
Notice there is some missing data in the data file -- Colorado has no state slogan. The
TRAILING NULLCOLS statement handles the missing data; it tells SQL*Loader to load any
missing data as NULL values. There are, as we said earlier, lots of available options
described in the Utilities User’s Guide.
3) Create a table with the name referred in ctl file with required columns
4) Run SQL*Loader.
Prerequisites:
You must have SQL*Loader and SQL*Net installed on your machine. The
SQL*Loader program may have a version number included as part of its name,
something like sqlldr73.exe or sqlldr80.exe. Or maybe it will be just
sqlldr.exe. You can look for it in your ORAWIN95 or ORANT \BIN directory. If
it's not installed, you can get the Oracle Client Software installation CD and install
"UTILITIES".
You must have the target database (say, it’s called ‘ELTP’) configured as SQL*Net
service in your local tnsnames.ora file. This is pretty standard stuff; it’s probably
already there.
At an MS-DOS prompt (or the Start, Run menu) , execute SQL*Loader as follows:
sqlldr scott/tiger@ELTP control=C:\mystates.ctl
When the load completes, look in the file C:\mystates.log. This log file will
contain information about how many rows were loaded, how many rows -- if
any -- were NOT loaded, and other information that may be useful to reassure
or debug.
Note For the address example in this article, the Excel worksheet contains the following address
information:
A B
1 ravi
2 kris
3 babu
Note In Excel 2007, click the Microsoft Office Button, and then click Save As.
2. In the Save As dialog box:
a. In the Save as type box, click CSV (Comma delimited) (*.csv).
b. In the File name box, type a name for your CSV file (for example, Address.csv), and then click
Save.
c. Click OK when you receive the following message:
The selected file type does not support workbooks that contain multiple sheets.
• To keep this format, which leaves out any incompatible features, click Yes.
• To preserve the features, click No. Then save a copy in the latest Excel format.
• To see what might be lost, click Help.
3. On the File menu, click Close, and then exit Microsoft Excel.
Note In Excel 2007, click the Microsoft Office Button, click Close, and then click Exit Excel.
Note You may be prompted to save the file again. When you are prompted, you can click Yes, repeat
steps c and d, and then exit Excel.
Note In Word 2007, click the Microsoft Office Button, and then click Open.
3. In the Files of type box, click All Files (*.*).
4. Click the CSV file that you saved in step 4 of the "Edit the Excel Worksheet" section, and then click
Open.
5. On the Tools menu, click Options.
Table : Studies
TABLE : SOFTWARE
Find out the selling cost average for packages developed in pascal.
Display the names and ages of all the programmers
Display the names of those who have done the DAP course
What is the highest number of copies sold by a package
Display the names and date of birth of all programmers born in
January
Display the lowest course fee
How many programmers have done the PGDCA course
How much revenue has been earned through sale of packages
developed in C
Display the software’s developed by Ramesh
How many programmers studied at Sabhari?
Display the details of the packages whose sales crossed 2000 mark.
Find out the number of copies which should be sold in order to
recover the development cost of each package.
Display the details of packages for which development cost have been
recovered.
What is the price of the costliest software developed in BASIC
How many packages were developed in DBASE?
How many programmers studied at Pragathi?
How many programmers paid 5000 to 10000 for their course?
What is the average course fee?
Display the details of programmers knowing C
How many programmers know either COBOL or PASCAL?
How many programmers don’t know PASCAL and C?
How old is the oldest male programmer?
What is the average age of female programmers?
Calculate the experience in years for each programmer and display
along with the names, in descending order.
Who are the programmers who celebrate their birthday’s during the
current month?
How many female programmers are there?
What are the languages known by the male programmers
What is the average salary
How many people draw 2000 to 4000?
Display the details of those who don’t know Clipper, COBOL or Pascal
Display the details of those who will be completing 2 years of services
this year?
QUERY – II
QUERY – III
Write a query to display the last name, department number, and salary of any employee
whose department number and salary both match the department number and salary of any
employee who earns a commission.
Display the last name, department name, and salary of any employee whose salary and
commission match the salary and commission of any employee located in location ID
1700.
Create a query to display the last name, hire date, and salary for all employees who have the
same salary and commission as Kochhar.
Note: Do not display Kochhar in the result set.
Create a query to display the employees who earn a salary that is higher than the salary of all
of the sales managers (JOB_ID = 'SA_MAN'). Sort the results on salary from highest to
lowest.
Write a query to display the last names of the employees who earn less than the average
salary in their departments.
Write a query to display the last names of the employees who have one or more coworkers in
their departments with later hire dates but higher salaries.
Write a query to display the department names of those departments whose total salary cost is
above one eighth (1/8) of the total salary cost of the whole company
Write a query to display the last name, department number, and department name for all
employees
Create a unique listing of all jobs that are in department 80. Include the location of the
department in the output.
Write a query to display the employee last name, department name, location ID, and city of
all employees who earn a commission.
Display the employee last name and department name for all employees who have an a
(lowercase) in their last names
Write a query to display the last name, job, department number, and department name for all
employees who work in Toronto.
Create a query that displays employee last names, department numbers, and all the
employees who work in the same department as a given employee. Give each column an
appropriate label.
Show the structure of the JOB_GRADES table. Create a query that displays the name, job,
department name, salary, and grade for all employees.
Create a query to display the name and hire date of any employee hired after employee
Davies.
Write a query to display the following for those employees whose manager ID is less than
120:
• Manager ID
• Job ID and total salary for every job ID for employees who report to
the same manager
• Total salary of those managers
• Total salary of those managers, irrespective of the job IDs
Question: 1
Which SELECT statement should you use if you want to display unique
combinations of the POSITION and MANAGER values from the EMPLOYEE
table?
Question: 2
You need to produce a report for mailing labels for all customers. The
mailing label must have only the customer name and address. The
CUSTOMERS table has these columns:
Question: 3
Question: 4
Question: 5
You use this statement to retrieve data from a data table for __________.
1. Updating
2. Viewing
3. Deleting
4. Inserting
5. Truncating
Question: 6
Question: 7
Which statement finds the rows in the CUSTOMERS table that do not have a
postal code?
Question: 8
Question: 9
Question: 10
1.
EMP_id EMPLOYEE SALARY Mgr_id Manager
------- ---------- --------- ------------- --------------
110 Bob 8000 Bob
120 Ravi 6500 110 Ravi
108 Jennifer 6500 110 Jennifer
103 Chris 4200 120 Chris
105 Diana 5000 108 Diana
2.
EMP_id EMPLOYEE SALARY Mgr_id Manager
------- ---------- --------- ------------- --------------
120 Ravi 6500 110 Bob
108 Jennifer 6500 110 Bob
103 Chris 4200 120 Ravi
105 Diana 500 108 Jennifer
3.
EMP_id EMPLOYEE SALARY Mgr_id Manager
------- ---------- --------- ------------- --------------
110 Bob 800
120 Ravi 6500 110 Bob
108 Jennifer 6500 110 Bob
103 Chris 4200 120 Ravi
105 Diana 5000 108 Jennifer
D
EMP_id EMPLOYEE SALARY Mgr_id Manager
------- ---------- --------- ------------- --------------
110 Bob 8000 110 Bob
120 Ravi 6500 120 Ravi
108 Jennifer 6500 108 Jennifer
103 Chris 4200 103 Chris
Question: 11
Question: 12
Question: 13
You want to use a function in you column clause of a SQL statement. The
NVL function
accomplishes which of the following tasks?
Question: 14
You want to use SQL*Plus to connect to the oracle database. Which of the
following choices
does not indicate a component you must specify when logging into the
oracle?
Question: 15
Question: 17
Question: 18
You need to display the last names of those employees who have the letter
“A” as the second
character in their names.
Which SQL statement displays the required results?
1. SELECT last_name FROM EMP WHERE last_name LIKE ‘_A%’;
2. SELECT last_name FROM EMP WHERE last name =’*A%’
3. SELECT last_name FROM EMP WHERE last name =’_A%’;
4. SELECT last_name FROM EMP WHERE last name LIKE ‘*A%’
Question: 19
Question: 20
Evaluate this SQL statement:
SELECT c.customer_id, o.order_id, o.order_date, p.product_name
FROM customer c, curr_order o, product p
WHERE customer.customer_id = curr_order.customer_id AND o.product_id
= p.product_id
ORDER BY o.order_amount;
This statement fails when executed. Which change will correct the problem?
1. Include the ORDER_AMOUNT column in the SELECT list.
2. Use the table name in the ORDER BY clause.
3. Remove the table aliases from the WHERE clause.
Question: 21
You want to display the titles of books that meet these criteria:
1. Purchased before January 21, 2001
2. Price is less then $500 or greater than $900
You want to sort the results by their data of purchase, starting with the
most recently bought
book.
Which statement should you use?
1. SELECT book_title
FROM books
WHERE price between 500 and 900 AND purchase_date < ’21-JAN-2001’
ORDER BY purchase_date;
2. SELECT book_title
FROM books
WHERE price IN (500,900) AND purchase_date < ’21-JAN-2001’
ORDER BY purchase date ASC;
3. SELECT book_title
FROM books
WHERE price < 500 or > 900 AND purchase_date < ’21-JAN-2001’
ORDER BY purchase date DESC;
4. SELECT book_title
FROM books
WHERE (price < 500 OR price > 900) AND purchase_date < ’21-JAN-2001’
ORDER BY purchase date DESC;
Question: 22
For which task would you use the WHERE clause in a SELECT statement?
1. to designate the ORDER table location
2. to compare PRODUCT_ID values to 7382
3. to display only unique PRODUCT_ID values
4. to restrict the rows returned by a GROUP BY clause
Question: 23
Question: 24
Question: 25
Examine the structure of the PRODUCT table.
PRODUCT Table
PRODUCT _ID NUMBER Primary Key
PRODUCT_NAME VARCHAR2(25)
SUPPLIER_ID NUMBER references SUPPLIER(SUPPLIER_ID)
CATERORY_ID NUMBER
QTY_PER_UNIT NUMBER
LIST_RRICE NUMBER (5,2)
COST NUMBER (5,2)
You want to display all product identification numbers of products for which
there are 500 or more
available for immediate sale. You want the product numbers displayed
alphabetically by supplier,
then by product number from lowest to highest. Which statement should
you use to achieve the
required results?
1. SELECT product_id
FROM product
WHERE qty_per_unit >= 500
ORDER BY supplier_id, product_id;
2. SELECT product_id
FROM product
WHERE qty_per_unit >= 500
SORT BY supplier_id, product_id;
3. SELECT product_id
FROM product
WHERE qty_per_unit >= 500
ORDER BY supplier_id, product_id DESC;
4. SELECT product_id
FROM product
WHERE qty_per_unit > 500
SORT BY supplier_id, product_id;
Question: 26
Examine the data in TEACHER table.
ID LAST_NAME FIRST_NAME SUBJECT_ID
88 Tsu Ming HST_AMER
70 Smith Ellen HST_INDIA
56 Jones Karen HST_REVOL
Which query should you use to return the following values from the
TEACHER table?
Name Subject
------------------------------------- -------------------
Jones, Karen HST_REVOL
Hopewell, Mary Elizabeth HST_RELIG
Question: 27
1. 100
2. 260
3. 400
4. 600
Question: 28
Examine the structure of the STUDENTS table:
STUDENT_ID NUMBER Primary Key
STUDENT_NAME VARCHAR2(30)
COURSE_ID VARCHAR2(10) NOT NULL
MARKS NUMBER
START_DATE DATE
Question: 29
Examine the structure of the LINE_ITEM table.
LINE_ITEM_ID NUMBER(9),
ORDER_ID NUMBER(9) NOT NULL,
PRODUCT_ID NUMBER(9) NOT_NULL,
QUANTITY NUMBER(9),
Constraint primary key (LINE_ITEM_ID, ORDER_ID),
Constraint foreign key ORDER_ID REFERENCES
CURR_ORDER(ORDER_ID),
Constraint foreign key PRODUCT_ID REFERENCES
PRODUCT(PRODUCT_ID));
Question: 30
The ITEM table contains these columns:
ITEM_ID NUMBER(9)
COST NUMBER(7,2)
RETAIL NUMBER(7,2)
You need to create a report that displays the cost, the retail price, and the
profit for item number
783920. To calculate the profit, subtract the cost of the item from its retail
price, and then deduct
an administrative fee of 25 percent of this derived value.
2. SELECT cost, retail, (retail - cost) - retail - (cost * .25) "Profit" FROM item
WHERE item_id = 783920;
3. SELECT cost, retail, (retail - cost - retail - cost) * .25 "Profit" FROM item
WHERE item_id = 783920;
4. SELECT cost, retail, retail - cost - retail - cost * .25 "Profit" FROM item
WHERE item_id = 783920;
Question: 31
Question: 32
The EMP table contains these columns:
LAST NAME VARCHAR2(25)
SALARY NUMBER(6,2)
DEPARTMENT_ID NUMBER(6)
You need to display the employees who have not been assigned to any
department.
You write the SELECT statement:
SELECT LAST_NAME, SALARY, DEPARTMENT_ID FROM EMP
WHERE DEPARTMENT_ID = NULL;
Question: 33
Which two statements are true about WHERE and HAVING clauses?
1. A WHERE clause can be used to restrict both rows and groups.
2. A WHERE clause can be used to restrict rows only.
3. A HAVING clause can be used to restrict both rows and groups.
4. A HAVING clause can be used to restrict groups only.
5. A WHERE clause CANNOT be used in a query of the query uses a HAVING
clause.
6. A HAVING clause CANNOT be used in subqueries.
Question: 34
You are sorting data in a table in you SELECT statement in descending
order. The column you
are sorting on contains NULL records, where will the NULL record appears?
1. At the beginning of the list.
2. At the end of the list.
3. In the middle of the list.
4. At the same location they are listed in the unordered table.
Question: 35
You need to display the account number, finance charge, and current
balance for accounts 1500
through 2000 with a current balance greater than the account's credit limit.
The finance charge is .9 percent (.009) of the previous balance. Adding the
previous balance
value, new purchases value, and finance charge value, and then subtracting
the payments value yields the current balance value.
Question: 36
Question: 37
Question: 38
Question: 39
Question: 40
Question: 41
Evaluate the SQL statement:
SELECT ROUND(TRUNC(MOD(1600,10),-1),2)
FROM dual;
What will be displayed?
1. 0
2. 1
3. 0.00
4. An error statement
Question: 42
Examine the description of the MARKS table:
STD_ID NUMBER(4)
STUDENT_NAME VARCHAR2(30)
SUBJ1 NUMBER(3)
SUBJ2 NUMBER(3)
SUBJ1 and SUBJ2 indicate the marks obtained by a student in two
subjects.
Examine this SELECT statement based on the MARKS table:
SELECT subj1+subj2 total_marks, std_id
FROM marks
WHERE subj1 > AVG(subj1) AND subj2 > AVG(subj2)
ORDER BY total marks;
1. The statement executes successfully and returns the student ID and sum
of all marks for
each student who obtained more than the average mark in each subject.
2. The statement returns an error at the SELECT clause.
3. The statement returns an error at the WHERE clause.
4. The statement returns an error at the ORDER BY clause.
Question: 43
Question: 44
Which statement shows the department ID, minimum salary, and maximum
salary paid in that
department, only of the minimum salary is less then 5000 and the
maximum salary is more than
15000?
1. SELECT dept_id, MIN(salary(, MAX(salary)
FROM employees
WHERE MIN(salary) < 5000 AND MAX(salary) > 15000;
Question: 45
Question: 46
Question: 47
PHYSICIAN Table
PHYSICIAN _ID NUMBER Primary Key
LAST_NAME VARCHAR2 (30) NOT NULL
FIRST_NAME VARCHAR2 (25) NOT NULL
LICENSE_NO NUMBER (7) NOT NULL
ADMISSION Table
PATIENT_ID NUMBER NOT NULL, Primary Key, References PATIENT_ID
column of
the PATIENT table
PHYSICIAN_ID NUMBER NOT NULL, Primary Key, References
PHYSICIAN_ID column
of the PHYSICIA table
ADMIT_DATE DATE
DISCHG_DATE DATE
ROOM_ID NUMBER Foreign key to ROOM_ID of the ROOM table
Which SQL statement will produce a list of all patients who have more than
one physician?
Question: 48
Question: 49
Question: 50
Which two are character manipulation functions?
1. TRIM
2. REPLACE
3. TRUNC
4. TO_DATE
5. MOD
6. CASE