Sunday 5 August 2012

SQL Functions


SQL functions are built into Oracle and are available for use in various appropriate SQL statements. You can also create your own function using PL/SQL.

Single-Row Functions

Single-row functions return a single result row for every row of a queried table or view. These functions can appear in select lists, WHERE clauses, START WITH and CONNECT BY clauses, and HAVING clauses.

Number Functions

Number functions accept numeric input and return numeric values. Most of these functions return values that are accurate to 38 decimal digits.
The number functions available in Oracle are:
ABS  ACOS ASIN ATAN ATAN2 BITAND CEIL COS COSH EXP FLOOR LN LOG
MOD POWER ROUND (number) SIGN SIN SINH SQRT TAN TANH TRUNC (number)
 

ABS

ABS returns the absolute value of n.
The following example returns the absolute value of -87:
SELECT ABS(-87) "Absolute" FROM DUAL;
 Absolute
----------
        87

ACOS

ACOS returns the arc cosine of n. Inputs are in the range of -1 to 1, and outputs are in the range of 0 to pi and are expressed in radians.
The following example returns the arc cosine of .3:
SELECT ACOS(.3)"Arc_Cosine" FROM DUAL;
Arc_Cosine
----------
1.26610367
Similar to ACOS, you have ASIN (Arc Sine), ATAN (Arc Tangent) functions.

CIEL

Returns the lowest integer above the given number.
Example:
The following function return the lowest integer above 3.456;
select ciel(3.456) “Ciel” from dual;
Ciel
---------
        4

FLOOR         

Returns the highest integer below the given number.
Example:
The following function return the highest integer below 3.456;
select floor(3.456) “Floor” from dual;
Floor
------------
        3

COS

Returns the cosine of an angle (in radians).
Example:
The following example returns the COSINE angle of 60 radians.
select  cos(60) “Cosine” from dual;

SIN

Returns the Sine of an angle (in radians).
Example:
The following example returns the SINE angle of 60 radians.
select  SIN(60) “Sine” from dual;

 

TAN

Returns the Tangent of an angle (in radians).
Example:
The following example returns the tangent angle of 60 radians.
select  Tan(60) “Tangent” from dual;
Similar to SIN, COS, TAN  functions hyperbolic functions  SINH, COSH, TANH are also available in oracle.

MOD

Returns the remainder after dividing m with n.
Example
The following example returns the remainder after dividing 30 by 4.
Select mod(30,4) “MOD” from dual;
MOD
---------
        2

POWER

Returns the power of m, raised to n.
Example
The following example returns the 2 raised to the power of 3.
select  power(2,3) “Power” from dual;
POWER
---------
        8

EXP

Returns the e raised to the power of n.
Example
The following example returns the e raised to power of 2.
select exp(2) “e raised to 2” from dual;
E RAISED TO 2
-------------
       

LN

Returns natural logarithm of n.
Example
The following example returns the natural logarithm of 2.
select ln(2) from dual;
LN
------------

LOG

Returns the logarithm, base m, of n.

Example
The following example returns the log of 100.
select log(10,100) from dual;
LOG
---------
        2

ROUND

Returns a decimal number rounded of to a given decimal positions.
Example
The following example returns the no. 3.4573 rounded to 2 decimals.

select round(3.4573,2) “Round” from dual;
Round
------------
        3.46

TRUNC


Returns a decimal number Truncated to a given decimal positions.
Example
The following example returns the no. 3.4573 truncated to 2 decimals.
select round(3.4573,2) “Round” from dual;
Round
------------
        3.45

SQRT

Returns  the square root of a given number.
Example
The following example returns the square root of  16.
select  sqrt(16) from dual;
SQRT
---------
        4

Character Functions

Character functions operate on values of dataype  CHAR or VARCHAR.

LOWER

Returns a given string in lower case.
select LOWER(‘SAMI’) from dual;
LOWER
-------------
sami

UPPER

Returns a given string in UPPER case.
select UPPER(‘Sami’) from dual;
UPPER
------------------
SAMI
                    

INITCAP

Returns a given string with Initial letter in capital.
select INITCAP(‘mohammed sami’) from dual;
INITCAP
------------------
Mohammed Sami

LENGTH

Returns the length of a given string.
select length(‘mohammed sami’) from dual;
LENGTH
------------
        13

SUBSTR

Returns a substring from a given string. Starting from position p to n characters.
For example the following query returns “sam” from the string “mohammed sami”.
select substr('mohammed sami',10,3) from dual;
Substr
--------
sam

INSTR

Tests whether a given character occurs in the given string or not. If the character occurs in the string then returns the first position of its occurrence otherwise returns 0.
Example
The following query tests whether the character “a” occurs in string “mohammed sami”
select instr('mohammed sami','a') from dual;
INSTR
--------
4

REPLACE

Replaces a given set of characters in a string with another set of characters.
Example
The following query replaces “mohd” with “mohammed” .
select replace('ali mohd khan','mohd','mohammed') from dual;
REPLACE
---------
ali mohammed khan

 

TRANSLATE

This function is used to encrypt characters. For example you can use this function to replace characters in a given string with your coded characters.
Example
The following query replaces characters A with B, B with C, C with D, D with E,...Z with A, and a with b,b with c,c with d, d with e ....z with a.
select translate('interface','ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz','BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza') “Encrypt” from dual;

SOUNDEX

This function is used to check pronounciation rather than exact characters. For example many people write names as “smith” or “smyth” or “smythe” but they are pronounced as smith only.
Example
The following example compare those names which are spelled differently but are pronouced as “smith”.
Select ename from emp where soundex(ename)=soundex('smith');
ENAME
---------
Smith
Smyth
Smythe

RPAD

Right pads a given string with a given character to n number of characters.
Example
The following query rights pad ename with '*'  until it becomes 10 characters.
select rpad(ename,'*',10) from emp;
Ename
----------
Smith*****
John******
Mohammed**
Sami******

LPAD

Left pads a given string with a given character upto n number of characters.
Example
The following query left pads ename with '*'  until it becomes 10 characters.
select lpad(ename,'*',10) from emp;
Ename
----------
*****Smith
******John
**Mohammed
******Sami

LTRIM

Trims blank spaces from a given string from left.
Example
The following query returns string “       Interface        “ left trimmed.
select ltrim('       Interface       ') from dual;
Ltrim
--------------
Interface 

RTRIM

Trims blank spaces from a given string from Right.
Example
The following query returns string “       Interface        “ right trimmed.
select rtrim('       Interface       ') from dual;
Rtrim
------------
   Interface 

TRIM

Trims a given character from left or right or both from a given string.
Example
The following query removes zero from left and right of a given string.
Select trim(0 from '00003443500') from dual;
Trim
----------
34435

CONCAT

Combines a given string with another string.
Example
The following Query combines ename with literal string “ is a “ and jobid.
Select concat(concat(ename,' is a '),job) from emp;
Concat
----------------
Smith is a clerk
John is a Manager
Sami is a G.Manager

 

Miscellaneous Single Row Functions

 

COALESCE

 Coalesce function returns the first not null value in the expression list.
 Example.
 The following query returns salary+commision, if commission is null then returns salary, if salary is also null then returns 1000.

select empno,ename,salary,comm,coalesce(salary+comm,salary,1000) “Net Sal” from emp;

ENAME     SALARY    COMM NET SAL
-----     ------    ---- -------
SMITH     1000      100  1100
SAMI      3000          3000
SCOTT                   1000
RAVI               200  1000

DECODE

            DECODE(expr, searchvalue1, result1,searchvalue2,result2,..., defaultvalue)
Decode functions compares an expr with search value one by one. If the expr does not match any of the search value then returns the default value. If the default value is omitted then returns null.
Example
The following query returns the department names according the deptno. If the deptno does not match any of the search value then returns “Unknown Department”
select decode(deptno,10,'Sales',20,'Accounts,30,'Production,
          40,'R&D','Unknown Dept') As DeptName from emp;
DEPTNAME
----------
Sales
Accounts
Unknown Dept.
Accounts
Production
Sales
R&D
Unknown Dept.

 

GREATEST

            GREATEST(expr1, expr2, expr3,expr4...)
Returns the greatest expr from a expr list.
Example
select greatest(10,20,50,20,30) from dual;
GREATEST
--------
50

select greatest('SAMI','SCOTT','RAVI','SMITH','TANYA') from dual;

GREATEST
--------
TANYA

 

LEAST

            LEAST(expr1, expr2, expr3,expr4...)
It is simillar to greatest. It returns the least expr from the expression list.
select least(10,20,50,20,30) from dual;
LEAST
--------
10
select least('SAMI','SCOTT','RAVI','SMITH','TANYA') from dual;
LEAST
--------
RAVI

NVL

                        NVL2(expr1,expr2)
This function is oftenly used to check null values. It  returns  expr2 if the  expr1 is null, otherwise returns expr1.
Example
The following query returns commission if commission is null then returns 'Not Applicable'.
Select ename,nvl(comm,'Not Applicable') “Comm” from dual;
ENAME     COMM
------    ----
Scott     300
Tiger     450
Sami      Not Applicable
Ravi      300
Tanya     Not Applicable

NVL2

            NVL2(expr1,expr2,expr3)
NVL2 returns  expr2 if expr1 is not null, otherwise return expr3.
Example
The following query returns salary+comm if comm is not null, otherwise just returns salary.
select salary,comm,nvl2(comm,salary+comm,salary) “Income” from emp;
SALARY    COMM      INCOME
------    ----      ------
1000      100       1100
2000               2000
2300      200       2500
3400               3400

 

NULLIF

            NULLIF(expr1, expr2)
Nullif compares expr1 with expr2. If they are equal then returns null, otherwise return expr1.
Example.
The following query shows old jobs of those employees  who have changed their jobs in the company by comparing the current job with old job in oldemp table.
Select ename,nullif(e.job,o.job) “Old Job” from emp e, oldemp o where e.empno=o.empno;
ENAME         OLD JOB
-----         -------
SMITH         CLERK
SAMI                   
SCOTT         MANAGER

UID

Returns the current session ID of user logged on.
Example
select uid from dual;
UID
----
20

USER

Returns the username of the current user logged on.
select user from dual;
USER
---------
SCOTT

SYS_CONTEXT

SYS_CONTEXT returns the value of parameter associated with the context namespace. You can use this function in both SQL and PL/SQL statements.
EXAMPLE
The following query returns the username of the current user.
Select sys_context('USERENV','SESSION_USER') “Username” from dual;
USERNAME
---------
SCOTT

Similar to SESSION_USER parameter for namespace USERENV the other important parameters are
ISDBA            :To check whether the current user is having DBA privileges or not.
HOST              :Returns the name of  host machine from which the client is connected.
INSTANCE    :The instance identification number of the current instance
IP_ADDRESS: IP address of the machine from which the client is connected.
DB_NAME    :Name of the database as specified in the DB_NAME initialization parameter

VSIZE

                        VSIZE(expr)
Returns the internal representation of expr in bytes.
Example
The following query return the representation of  ename in bytes.
select ename,vsize(ename) as Bytes from emp;
ENAME     BYTES
------    ------
SCOTT     5
SAMI      4
RAVI      4
KIRAN     5

Aggregate Functions

 Aggregate functions return a single value based on groups of rows, rather than single value for each row. You can use Aggregate functions in select lists and in ORDER BY and HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle divides the rows of a queried table or view into groups.
The important Aggregate functions are :
Avg     Sum     Max     Min      Count     Stddev     Variance

AVG

            AVG( ALL /DISTINCT        expr)
Returns the average value of expr.
Example
The following query returns the average salary of all employees.
select avg(sal) “Average Salary” from emp;
Average Salary
------------------------
2400.40

SUM

                        SUM(ALL/DISTINCT           expr)
Returns the sum value of expr.
Example

The following query returns the sum salary of all employees.
select sum(sal) “Total Salary” from emp;
Total Salary
------------------------
26500
  

MAX

                        MAX(ALL/DISTINCT          expr)
Returns maximum value of expr.

Example

The following query returns the max salary from the employees.

select max(sal) “Max Salary” from emp;

Maximum Salary
------------------------
4500

MIN

                        MIN(ALL/DISTINCT           expr)

Returns minimum value of expr.
Example
The following query returns the minimum salary from the employees.
select min(sal) “Min Salary” from emp;
Minimum Salary
------------------------
1200

COUNT

                        COUNT(*)      OR      COUNT(ALL/DISTINCT     expr)

Returns the number of rows in the query. If you specify expr then count ignore nulls. If you specify the asterisk (*), this function returns all rows, including duplicates and nulls. COUNT never returns null.
Example
The following query returns the number of  employees.
Select count(*) from emp;
COUNT
------
14

The following query counts the number of employees whose salary is not null.
Select count(sal) from emp;
COUNT
------
12

STDDEV

            STDDEV(ALL/DISTINCT   expr)
STDDEV returns sample standard deviation of expr, a set of numbers.
Example
The following query returns the standard deviation of salaries.
select stddev(sal) from emp;
Stddev
-------  
1430

VARIANCE

            VARIANCE(ALL/DISTINCT          expr)
Variance returns the variance of expr.
Example
The following query returns the variance of salaries.
select variance(sal) from emp;
Variance
-------  
1430

Date Functions and Operators.

To see the system date and time use the following functions :
CURRENT_DATE    :returns the current date in the session time zone, in a value in the Gregorian calendar of datatype DATE
SYSDATE                  :Returns the current date and time.
SYSTIMESTAMP      :The SYSTIMESTAMP function returns the system date, including fractional seconds and time zone of the database. The return type is TIMESTAMP WITH TIME ZONE.

SYSDATE Example


To see the current system date and time give the following query.

select sysdate from dual;

SYSDATE
-------
8-AUG-03

The format in which the date is displayed depends on NLS_DATE_FORMAT parameter.

For example set the NLS_DATE_FORMAT to the following format

Alter session set NLS_DATE_FORMAT=’DD-MON-YYYY HH:MIpm’;

Then give the give the following statement

select sysdate from dual;

SYSDATE
------------------
8-AUG-2003 03:05pm

The default setting of NLS_DATE_FORMAT is DD-MON-YY



CURRENT_DATE Example


To see the current system date and time with  time zone use CURRENT_DATE function

ALTER SESSION SET TIME_ZONE = '-4:0';
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';
SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL;
 
SESSIONTIMEZONE CURRENT_DATE
--------------- --------------------
-04:00          22-APR-2003 14:15:03
 
ALTER SESSION SET TIME_ZONE = '-7:0';
SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL;
 
SESSIONTIMEZONE CURRENT_DATE
--------------- --------------------
-07:00          22-APR-2003 09:15:33


SYSTIMESTAMP Example


To see the current system date and time with fractional seconds with time zone give the following statement

Select systimestamp from dual;

SYSTIMESTAMP
-------------------------------
22-APR-03 08.38.55.538741 AM -07:00

DATE FORMAT MODELS


To translate the date into a different format string  you can use TO_CHAR function with date format. For example to see the current day you can give the following query

To translate a character value, which is in format other than the default date format, into a date value you can use TO_DATE function with date format to date


Select to_char(sysdate,’DAY’)”Today” FROM DUAL;

TODAY
-------
THURSDAY

Like this “DAY” format model there are many other date format models available in Oracle. The following table list date format models.

FORMAT
MEANING
D
Day of the week
DD
Day of the month
DDD
Day of the year
DAY
Full day for ex. ‘Monday’, ’Tuesday’, ’Wednesday’
DY
Day in three letters for ex. ‘MON’, ‘TUE’,’FRI’
W
Week of the month
WW
Week of the year
MM
Month in two digits  (1-Jan, 2-Feb,…12-Dec)
MON
Month in three characters like “Jan”, ”Feb”, ”Apr”
MONTH
Full Month like “January”, ”February”, ”April”
RM
Month in Roman Characters (I-XII, I-Jan, II-Feb,…XII-Dec)
Q
Quarter of the Month
YY
Last two digits of the year.
YYYY
Full year
YEAR
Year in words like “Nineteen Ninety Nine”
HH
Hours in 12 hour format
HH12
Hours in 12 hour format
HH24
Hours in 24 hour format
MI
Minutes
SS
Seconds
FF
Fractional Seconds
SSSSS
Milliseconds
J
Julian Day i.e Days since 1st-Jan-4712BC to till-date
RR
If the year is less than 50 Assumes the year as 21ST Century. If the year is greater than 50 then assumes the year in 20th Century.


suffixes
TH
Returns th, st, rd or nd according to the leading number like 1st , 2nd 3rd 4th
SP
Spells out the leading number
AM or PM
Returns AM or PM according to the time
SPTH
Returns Spelled Ordinal number. For. Example First, Fourth

For example to see the today’s date in the following format

Friday, 8th August, 2003 

Give the following statement
select to_char(sysdate,’Day, ddth Month, yyyy’)”Today” from dual;

TODAY
------------------------
Friday, 8th August, 2003 



For example you want to see hire dates of all employee in the following format

Friday, 8th August, 2003 

Then give the following query.

select to_char(hire_date,’Day, ddth Month, yyyy’) from emp;

TO_DATE Example


To_Date function is used to convert strings into date values. For example you want to see what was the day on 15-aug-1947. The use the to_date function to first convert the string into date value and then pass on this value to to_char function to extract day.

select to_char(to_date(’15-aug-1947’,’dd-mon-yyyy’),’Day’)
                                         from dual;

TO_CHAR(
--------
Friday


To see how many days have passed since 15-aug-1947 then give the following query

Select sysdate-to_date(’15-aug-1947’,’dd-mon-yyyy’)
from dual;


Now we want to see which date will occur after 45 days from now

Select sysdate+45 from dual;

SYSDATE
-------
06-JUN-2003



ADD_MONTHS


To see which date will occur after 6 months from now, we can use ADD_MONTHS function

Select ADD_MONTHS(SYSDATE,6) from dual;

ADD_MONTHS
----------
22-OCT-2003


MONTHS_BETWEEN


To see how many months have passed since 15-aug-1947, use the MONTHS_BETWEEN function.

Select months_between(sysdate,to_date(’15-aug-1947’))
                             from dual;

Months
------
616.553

To eliminate the decimal value use truncate function

LAST_DAY


To see the last date of the month of a given date, Use LAST_DAY function.

select LAST_DAY(sysdate) from dual;

LAST_DAY
--------
31-AUG-2003

NEXT_DAY


To see when the next Saturday is coming, use the NEXT_DAY function.

select next_day(sysdate) from dual;

NEXT_DAY
-----------
09-AUG-2003

EXTRACT (Oracle 9i, 10g only)


An EXTRACT datetime function extracts and returns the value of a specified datetime field from a datetime or interval value expression. When you extract a TIMEZONE_REGION or TIMEZONE_ABBR (abbreviation), the value returned is a string containing the appropriate time zone name or abbreviation

The syntax of EXTRACT function is

EXTRACT ( YEAR / MONTH / WEEK / DAY / HOUR / MINUTE / TIMEZONE  FROM DATE)
 
Example
 
The following demonstrate the usage of EXTRACT function to extract year from current date.
Select extract(year from sysdate) from dual;
 
EXTRACT
-------
2003

SUBQUERIES

A query nested within a query is known as subquery.
For example, you want to see all the employees whose salary is above average salary. For this you have to first compute the average salary using AVG function and then compare employees salaries with this computed salary. This is possible using subquery. Here the sub query will first compute the average salary and then main query will execute.
Select * from emp where sal > (select avg(sal) from emp);
Similarly we want to see the name and empno of that employee whose salary is maximum.
Select * from emp where sal = (select max(sal) from emp);
To see second maximum salary
Select max(sal) from emp where
       sal < (select max(sal) from emp);
Similarly to see the Third highest salary.
Select max(sal) from emp where
        sal < (select max(sal) from emp Where
               sal < (select max(sal) from emp));
We want to see how many employees are there whose salary is above average.
Select count(*) from emp where
      sal > (select max(sal) from emp);
We want to see those employees who are working in Hyderabad. Remember emp and dept are joined on deptno and city column is in the dept table. Assuming that wherever the department is located the employee is working in that city.
Select * from emp where deptno
      in (select deptno from dept where city=’HYD’);
You can also use subquery in FROM clause of SELECT statement.
For example the following query returns the top 5 salaries from employees table.
Select sal from (select sal from emp order sal desc)
             where rownum <= 5;
To see the sum salary deptwise you can give the following query.
Select sum(sal) from emp group by deptno;
Now to see the average total salary deptwise you can give a sub query in FROM clause.
select  avg(depttotal) from (select sum(sal) as depttotal from emp group by deptno);

WITH

The above average total salary department wise can also be achieved in 9i using WITH clause given below
WITH
  DEPTOT AS (select sum(sal) as dsal from emp
                group by deptno)
  select avg(dsal) from deptot;

GROUP BY QUERIES

You can group query results on some column values. When you give a SELECT statement without group by clause then all the resultant rows are treated as a single group.
For Example, we want to see the sum salary of all employees dept wise. Then the following query will achieved the result
Select deptno,sum(sal) from emp group by deptno;
Similarly we want to see the average salary dept wise
Select deptno,avg(sal) from emp group by deptno;
Similarly we want to see the maximum salary in each department.
Select deptno,max(sal) from emp group by deptno;
Similarly the minimum salary.
Select deptno,min(sal) from emp group by deptno;
Now we want to see the number of employees working in each department.
Select deptno,count(*) from emp group by deptno;
Now we want to see total salary department wise where the dept wise total salary is above 5000.
For this you have to use HAVING clause. Remember HAVING clause is used to filter groups and WHERE clause is used to filter rows. You cannot use WHERE clause to filter groups.
select deptno,sum(sal) from emp group by deptno
                  having sum(sal) >= 5000;
We want to see those departments  and the number of employees working in them where the number of employees is more than 2.
Select deptno, count(*) from emp group by deptno
                        Having count(*) >=2;
Instead of displaying deptno you can also display deptnames  by using join conditions.
For example we want to see deptname and average salary of them.
Select dname,avg(sal) from emp,dept
           where emp.deptno=dept.deptno group by dname;
Similarly to see sum of sal.
Select dname,sum(sal) from emp,dept
   where emp.deptno=dept.deptno group by dname;
Now we want to see the cities name and the no of employees working in each city. Remember emp and dept are joined on deptno and city column is in the dept table. Assuming that wherever the department is located the employee is working in that city.
Select dept.city,count(empno) from emp,dept
       where emp.deptno=dept.deptno
             Group by dept.city;

ROLLUP

The ROLLUP operation in the simple_grouping_clause groups the selected rows based on the values of the first n, n-1, n-2, ... 0 expressions in the GROUP BY specification, and returns a single row of summary for each group. You can use the ROLLUP operation to produce subtotal values by using it with the SUM function. When used with SUM, ROLLUP generates subtotals from the most detailed level to the grand total. Aggregate functions such as COUNT can be used to produce other kinds of superaggregates.
For example, given three expressions (n=3) in the ROLLUP clause of the simple_grouping_clause, the operation results in n+1 = 3+1 = 4 groupings.
Rows grouped on the values of the first 'n' expressions are called regular rows, and the others are called superaggregate rows.
The following query uses rollup operation to show sales amount product wise and year wise. To see the structure of the sales table refer to appendices.
Select prod,year,sum(amt) from sales
     group by rollup(prod,year);

CUBE

The CUBE operation in the simple_grouping_clause groups the selected rows based on the values of all possible combinations of expressions in the specification, and returns a single row of summary information for each group. You can use the CUBE operation to produce cross-tabulation values.
For example, given three expressions (n=3) in the CUBE clause of the simple_grouping_clause, the operation results in 2n = 23 = 8 groupings. Rows grouped on the values of 'n' expressions are called regular rows, and the rest are called superaggregate rows.
The following query uses CUBE operation to show sales amount product wise and year wise. To see the structure of the sales table refer to appendices.
Select prod,year,sum(amt) from sales
     group by CUBE(prod,year);

CASE EXPRESSION

CASE expressions let you use IF ... THEN ... ELSE logic in SQL statements without having to invoke procedures.
For example the following query uses CASE expression to display Department Names based on deptno.
Select empno,ename,sal,CASE deptno when 10 then ‘Accounts’
                    When 20 then ‘Sales’
                    When 30 then ‘R&D’
                    Else “Unknown’ end
            From emp;
The following statement finds the average salary of the employees in the employees table using $2000 as the lowest salary possible:
SELECT AVG(CASE WHEN e.sal > 2000 THEN e.sal
   ELSE 2000 END) "Average Salary" from emp e;

Introduction to Databases.

DATABASE

A database is a collection of Data (Information).  Examples of databases, which we use in our daily life, is  an Attendance Register, Telephone Directory, Muster Rule.
Database Management System(DBMS): A database management system is a collection of programs written to manage a database. That is, it acts as a interface between user and database.

RDBMS

A Database Management System based on Relational Data Model is known as Relational Database Management System (RDBMS).
The father of Relational Data Model was Dr. E.F. CODD. He developed the relational data model by taking the concept from Relational Algebra in  June-1970.
Relational Data Model is nothing but 12 Rules which are named after Codd as Codd Rules. According to Codd a package can be called as RDBMS only if it satisfies the Codd Rules.

ORACLE

Oracle is an Object-Relational Database Management System. It is the leading RDBMS vendor worldwide. Nearly half of RDBMS  worldwide market is owned by Oracle. 

ORACLE DATABASE

Every Oracle Database Contains Logical and Physical Structures. Logical Structures are tablespaces, Schema objects, extents and segments. Physical Structures are Datafiles, Redo Log Files, Control File.
A database is divided into logical storage units called tablespaces, which group related logical structures together. Each Tablespace in turn consists of one are more datafiles.
All the tables and other objects are stored in tablespace logically, but physically they are stored in the datafiles associated with the tablespace.
Every Oracle database has a set of two or more redo log files. The set of redo log files for a database is collectively known as the database's redo log. A redo log is made up of redo entries (also called redo records).
The primary function of the redo log is to record all changes made to data. If a failure prevents modified data from being permanently written to the datafiles, the changes can be obtained from the redo log so work is never lost.
Every Oracle database has a control file. A control file contains the database name and locations of all datafiles and redo log files.
Every Oracle database also has a Parameter File. Parameter file contains the name of the Database, Memory Settings and Location of Control file.

CODD’S RULES

1                    Information Rule: All information in a relational database including table names, column names are represented by values in tables. This simple view of data speeds design and learning. User productivity is improved since knowledge of only one language is necessary to access all data such as description of the table and attribute definitions, integrity constraints. Action can be taken when the constraints are violated. Access to data can be restricted. All these information are also stored in tables.
2                    Guaranteed Access Rule: Every piece of data in a relational database, can be accessed by using combination of a table name, a primary key value that identifies the row and column name which identified a cell. User productivity is improved since there is no need to resort to using physical pointers addresses. Provides data independence. Possible to retrieve each individual piece of data stored in a relational database by specifying the name of the table in which it is stored, the column and primary key which identified the cell in which it is stored.
3                    Systematic Treatment of Nulls Rule: The RDBMS handles records that have unknown or inapplicable values in a pre-defined fashion. Also, the RDBMS distinguishes between zeros, blanks and nulls in the records hand handles such values in a consistent manner that produces correct answers, comparisons and calculations. Through the set of rules for handling nulls, users can distinguish results of the queries that involve nulls, zeros and blanks. Even though the rule doesn’t specify what should be done in the case of nulls it specifies that there should be a consistent policy in the treatment of nulls.
4                    Active On-line catalog based on the relational model: The description of a database and in its contents are database tables and therefore can be queried on-line via the data manipulation language. The database administrator’s productivity is improved since the changes and additions to the catalog can be done with the same commands that are used to access any other table. All queries and reports can also be done as any other table.
5                    Comprehensive Data Sub-language Rule: A RDBMS may support several languages. But at least one of them should allow user to do all of the following: define tables and views, query and update the data, set integrity constraints, set authorizations and define transactions. User productivity is improved since there is just one approach that can be used for all database operations. In a multi-user environment the user does not have to worry about the data integrity an such things, which will be taken care by the system. Also, only users with proper authorization will be able to access data.
6                    View Updating Rule: Any view that is theoretically updateable can be updated using the RDBMS. Data consistency is ensured since the changes made in the view are transmitted to the base table and vice-versa.
7                    High-Level Insert, Update and Delete: The RDBMS supports insertions, updation and deletion at a table level. The performance is improved since the commands act on a set of records rather than one record at a time.
8                    Physical Data Independence: The execution of adhoc requests and application programs is not affected by changes in the physical data access and storage methods. Database  administrators can make changes to the physical access and storage method which improve performance and do not require changes in the application programs or requests. Here the user specified what he wants an need not worry about how the data is obtained.
9                    Logical Data Independence: Logical changes in tables and views such adding/deleting columns or changing fields lengths need not necessitate modifications in the programs or in the format of adhoc requests. The database can change and grow to reflect changes in reality without requiring the user intervention or changes in the applications. For example, adding attribute or column to the base table should not disrupt the programs or the interactive command that have no use for the new attribute.
10                Integrity Independence: Like table/view definition, integrity constraints are stored in the on-line catalog and can therefore be changed without necessitating changes in the application programs. Integrity constraints specific to a particular RDB must be definable in the relational data sub-language and storable in the catalog. At least the Entity integrity and referential integrity must be supported.
11                Distribution Independence: Application programs and adhoc requests are not affected by change in the distribution of physical data. Improved systems  reliability since application programs will work even if the programs and data are moved in different sites.
12                No subversion Rule: If the RDBMS has a language that accesses the information of a record at a time, this language should not be used to bypass the integrity constraints. This is necessary for data integrity.
According to Dr. Edgar. F. Codd, a relational database management system must be able to manage the database entirely through its relational capabilities.

Oracle Datatypes and Creating Tables Example

Datatypes and Creating Tables

A table is the data structure that holds data in a relational database. A table is composed of rows and columns.
A table in Oracle Ver. 7.3 can have maximum 255 Columns and in Oracle Ver. 8 and above a table can have maximum 1000 columns. Number of rows in a table is unlimited in all the versions.
A table can represent a single entity that you want to track within your system. This type of a table could represent a list of the employees within your organization, or the orders placed for your company's products.
A table can also represent a relationship between two entities. This type of a table could portray the association between employees and their job skills, or the relationship of products to orders. Within the tables, foreign keys are used to represent relationships.
Although some well designed tables could represent both an entity and describe the relationship between that entity and another entity, most tables should represent either an entity or a relationship.
The following sessions explain how to create, alter, and drop tables. Some simple guidelines to follow when managing tables in your database are included.

Designing Tables

Consider the following guidelines when designing your tables:
·Use descriptive names for tables, columns, indexes, and clusters.
·Be consistent in abbreviations and in the use of singular and plural forms of table names and columns.
·Document the meaning of each table and its columns with the COMMENT command.
·Normalize each table.
·Select the appropriate datatype for each column.
·Define columns that allow nulls last, to conserve storage space.
·Cluster tables whenever appropriate, to conserve storage space and optimize performance of SQL statements.
Before creating a table, you should also determine whether to use integrity constraints. Integrity constraints can be defined on the columns of a table to enforce the business rules of your database automatically.
Before creating a Table you have to decide what type of data each column can contain. This is known as datatype.  Lets Discuss what datatypes are available in Oracle.

Datatypes

A datatype associates a fixed set of properties with the values that can be used in a column of a table or in an argument of a procedure or function. These properties cause Oracle to treat values of one datatype differently from values of another datatype. For example, Oracle can add values of NUMBER datatype, but not values of RAW datatype.
Oracle supplies the following built-in datatypes:
·Character datatypes
oCHAR
oNCHAR
oVARCHAR2 and VARCHAR
oNVARCHAR2
oCLOB
oNCLOB
oLONG
·NUMBER datatype
·Time and date datatypes:
oDATE
oINTERVAL DAY TO SECOND
oINTERVAL YEAR TO MONTH
oTIMESTAMP
oTIMESTAMP WITH TIME ZONE
oTIMESTAMP WITH LOCAL TIME ZONE
·Binary datatypes
oBLOB
oBFILE
oRAW
oLONG RAW
Another datatype, ROWID, is used for values in the ROWID pseudocolumn, which represents the unique address of each row in a table.
The following table summarizes the information about each Oracle built-in datatype.
Datatype 
Description 
Column Length and Default  
CHAR (size [BYTE | CHAR]) 
Fixed-length character data of length size bytes or characters. 
Fixed for every row in the table (with trailing blanks); maximum size is 2000 bytes per row, default size is 1 byte per row. Consider the character set (single-byte or multibyte) before setting size. 
VARCHAR2 (size [BYTE | CHAR]) 
Variable-length character data, with maximum length size bytes or characters. 
Variable for each row, up to 4000 bytes per row. Consider the character set (single-byte or multibyte) before setting size. A maximum size must be specified. 
NCHAR (size) 
Fixed-length Unicode character data of length size characters. 
Fixed for every row in the table (with trailing blanks). Column size is the number of characters. (The number of bytes is 2 times this number for the AL16UTF16 encoding and 3 times this number for the UTF8 encoding.) The upper limit is 2000 bytes per row. Default is 1 character.  
NVARCHAR2 (size) 
Variable-length Unicode character data of length size characters. A maximum size must be specified. 
Variable for each row. Column size is the number of characters. (The number of bytes may be up to 2 times this number for a the AL16UTF16 encoding and 3 times this number for the UTF8 encoding.) The upper limit is 4000 bytes per row. Default is 1 character.  
CLOB  
Single-byte character data 
Up to 232 - 1 bytes, or 4 gigabytes. 
NCLOB  
Unicode national character set (NCHAR) data. 
Up to 232 - 1 bytes, or 4 gigabytes.  
LONG 
Variable-length character data. 
Variable for each row in the table, up to 232 - 1 bytes, or 2 gigabytes, per row. Provided for backward compatibility.  
NUMBER (p, s)  
Variable-length numeric data. Maximum precision p and/or scale s is 38. 
Variable for each row. The maximum space required for a given column is 21 bytes per row. 
DATE 
Fixed-length date and time data, ranging from Jan. 1, 4712 B.C.E. to Dec. 31, 4712 C.E. 
Fixed at 7 bytes for each row in the table. Default format is a string (such as DD-MON-RR) specified by the NLS_DATE_FORMAT parameter.  
INTERVAL YEAR (precision) TO MONTH 
A period of time, represented as years and months. The precision value specifies the number of digits in the YEAR field of the date. The precision can be from 0 to 9, and defaults to 2 for years. 
Fixed at 5 bytes. 
INTERVAL DAY (precision) TO SECOND (precision)

A period of time, represented as days, hours, minutes, and seconds. The precision values specify the number of digits in the DAY and the fractional SECOND fields of the date. The precision can be from 0 to 9, and defaults to 2 for days and 6 for seconds. 
Fixed at 11 bytes. 
TIMESTAMP (precision) 
A value representing a date and time, including fractional seconds. (The exact resolution depends on the operating system clock.)
The precision value specifies the number of digits in the fractional second part of the SECOND date field. The precision can be from 0 to 9, and defaults to 6 
Varies from 7 to 11 bytes, depending on the precision. The default is determined by the NLS_TIMESTAMP_FORMAT initialization parameter. 
TIMESTAMP (precision) WITH TIME ZONE 
A value representing a date and time, plus an associated time zone setting. The time zone can be an offset from UTC, such as '-5:0', or a region name, such as 'US/Pacific'
Fixed at 13 bytes. The default is determined by the NLS_TIMESTAMP_TZ_FORMAT initialization parameter. 


TIMESTAMP (precision) WITH LOCAL TIME ZONE 
Similar to TIMESTAMP WITH TIME ZONE, except that the data is normalized to the database time zone when stored, and adjusted to match the client's time zone when retrieved. 
Varies from 7 to 11 bytes, depending on the precision. The default is determined by the NLS_TIMESTAMP_FORMAT initialization parameter. 
BLOB  
Unstructured binary data  
Up to 232 - 1 bytes, or 4 gigabytes. 
BFILE  
Binary data stored in an external file  
Up to 232 - 1 bytes, or 4 gigabytes. 
RAW (size) 
Variable-length raw binary data  
Variable for each row in the table, up to 2000 bytes per row. A maximum size must be specified. Provided for backward compatibility.  
LONG RAW 
Variable-length raw binary data 


Variable for each row in the table, up to 231 - 1 bytes, or 2 gigabytes, per row. Provided for backward compatibility.  

ROWID 
Binary data representing row addresses 
Fixed at 10 bytes (extended ROWID) or 6 bytes (restricted ROWID) for each row in the table.  

Representing Character Data

Use the character datatypes to store alphanumeric data:
·CHAR and NCHAR datatypes store fixed-length character strings.
·VARCHAR2 and NVARCHAR2 datatypes store variable-length character strings. (The VARCHAR datatype is synonymous with the VARCHAR2 datatype.)
·NCHAR and NVARCHAR2 datatypes store Unicode character data only.
·CLOB and NCLOB datatypes store single-byte and multibyte character strings of up to four gigabytes.
·The LONG datatype stores variable-length character strings containing up to two gigabytes, but with many restrictions.
·This datatype is provided for backward compatibility with existing applications; in general, new applications should use CLOB and NCLOB datatypes to store large amounts of character data, and BLOB and BFILE to store large amounts of binary data.

When deciding which datatype to use for a column that will store alphanumeric data in a table, consider the following points of distinction:
·To store data more efficiently, use the VARCHAR2 datatype. The CHAR datatype blank-pads and stores trailing blanks up to a fixed column length for all column values, while the VARCHAR2 datatype does not add any extra blanks.
For example if you define  empname as char(20) then if you store names like “Sami” then name will occupy 20 bytes( 4 bytes for characters “Sami” and 16 blank spaces)
And if you define  empname as varchar2(20) then if you store names like “Sami” then oracle will take 4 bytes only.
·Use the CHAR datatype when you require ANSI compatibility in comparison semantics (when trailing blanks are not important in string comparisons). Use the VARCHAR2 when trailing blanks are important in string comparisons.
·The CHAR and VARCHAR2 datatypes are and will always be fully supported. At this time, the VARCHAR datatype automatically corresponds to the VARCHAR2 datatype and is reserved for future use.

Representing Numeric Data

Use the NUMBER datatype to store real numbers in a fixed-point or floating-point format. Numbers using this datatype are guaranteed to be portable among different Oracle platforms, and offer up to 38 decimal digits of precision. You can store positive and negative numbers of magnitude 1 x 10-130 through 9.99 x10125, as well as zero, in a NUMBER column.
You can specify that a column contains a floating-point number, for example:
distance NUMBER
Or, you can specify a precision (total number of digits) and scale (number of digits to right of decimal point):
price NUMBER (8, 2)
Although not required, specifying precision and scale helps to identify bad input values. If a precision is not specified, the column stores values as given. The following table shows examples of how data different scale factors affect storage.
Input Data 
Specified As 
Stored As 
4,751,132.79  
NUMBER 
4751132.79 
4,751,132.79  
NUMBER (9) 
4751133
4,751,132.79  
NUMBER (9,2) 
4751132.79 
4,751,132.79 
NUMBER (9,1) 
4751132.7 
4,751,132.79 
NUMBER (6) 
(not accepted, exceeds precision) 
4,751,132.79 
NUMBER (7, -2) 
4,751100 

Representing Date and Time Data

Use the DATE datatype to store point-in-time values (dates and times) in a table. The DATE datatype stores the century, year, month, day, hours, minutes, and seconds.
Use the TIMESTAMP datatype to store precise values, down to fractional seconds. For example, an application that must decide which of two events occurred first might use TIMESTAMP. An application that needs to specify the time for a job to execute might use DATE.

Date Format

For input and output of dates, the standard Oracle default date format is DD-MON-RR. For example:
'13-NOV-1992'
To change this default date format on an instance-wide basis, use the NLS_DATE_FORMAT parameter. To change the format during a session, use the ALTER SESSION statement. To enter dates that are not in the current default date format, use the TO_DATE function with a format mask. For example:
TO_DATE ('November 13, 1992', 'MONTH DD, YYYY')
Be careful using a date format like DD-MON-YY. The YY indicates the year in the current century. For example, 31-DEC-92 is December 31, 2092, not 1992 as you might expect. If you want to indicate years in any century other than the current one, use a different format mask, such as the default RR.

Time Format

Time is stored in 24-hour format, HH24:MI:SS. By default, the time in a date field is 12:00:00 A.M. (midnight) if no time portion is entered. In a time-only entry, the date portion defaults to the first day of the current month. To enter the time portion of a date, use the TO_DATE function with a format mask indicating the time portion, as in:
INSERT INTO Birthdays_tab (bname, bday) VALUES
    ('ANNIE',TO_DATE('13-NOV-92 10:56 A.M.','DD-MON-YY HH:MI A.M.'));

Creating Tables in Oracle

Once you have designed the table and decided about datatypes use the following SQL command to create a table.
For example, the following statement creates a table named Emp.
CREATE TABLE Emp (
   Empno      NUMBER(5),
   Ename      VARCHAR2(15),
   Hiredate   DATE,
   Sal        NUMBER(7,2)
                      );
To insert rows in the table you can use SQL  INSERT command.
For example the following statement creates a row in the above table.
SQL>insert into emp values (101,’Sami’,3400);
To insert rows continuously in SQL Plus you can give the following command.
SQL>insert into emp values (&empno,’&name’,&sal);
These &Empno, &name and &sal  are known as substitution variables. That is SQLPlus will prompt you for these values and then rewrites the statement with supplied values.
To see the rows you have inserted give the following command.
SQL> Select * from emp; 
To see the structure of the table i.e. column names and their datatypes and widths. Give the following command.
SQL>desc  emp
To see how many tables are in your schema give the following command.
SQL> select * from cat;
or
SQL>select * from tab;

SQL Queries, SELECT Statement

Use a SELECT statement or subquery to retrieve data from one or more tables, object tables, views, object views, or materialized views
For example to retrieve all rows from emp table.
SQL> select  empno, ename, sal  from emp;

          Or (if you want to see all the columns values
You can also give * which means all columns)

SQL> select * from emp;

Suppose you want to see only employee names and their salaries then you can type the following statement

SQL> select name, sal from emp;

Filtering Information using Where Conditions


            You can filter information using where conditions like suppose you want to see only those employees whose salary is above 5000 then you can type the following query with where condition

SQL>select * from emp where sal > 5000;
To see those employees whose salary is less than 5000 then the query will be
SQL> select * from emp where sal < 5000;

Logical Conditions

A logical condition combines the results of two component conditions to produce a single result based on them or to invert the result of a single condition. Table below lists logical conditions.
Condition 
Operation 
Example 
NOT

Returns TRUE if the following condition is FALSE. Returns FALSE if it is TRUE. If it is UNKNOWN, it remains UNKNOWN
SELECT *
  FROM emp
  WHERE NOT (sal IS NULL);
SELECT *
  FROM emp
  WHERE NOT
  (salary BETWEEN  1000 AND 2000);

AND

Returns TRUE if both component conditions are TRUE. Returns FALSE if either is FALSE. Otherwise returns UNKNOWN
SELECT *
  FROM employees
  WHERE ename ='SAMI'
  AND sal=3000;

OR

Returns TRUE if either component condition is TRUE. Returns FALSE if both are FALSE. Otherwise returns UNKNOWN
SELECT *
  FROM emp
  WHERE ename = 'SAMI'
  OR sal >= 1000;

 Membership Conditions
A membership condition tests for membership in a list or subquery
The following table lists the membership conditions.
Condition 
Operation 
Example 
IN

"Equal to any member of" test. Equivalent to "= ANY". 
SELECT * FROM emp
  WHERE deptno IN
  (10,20);
SELECT * FROM emp
  WHERE deptno IN (SELECT deptno FROM dept WHERE city=’HYD’)

NOT IN


Equivalent to "!=ALL". Evaluates to FALSE if any member of the set is NULL
SELECT * FROM emp
  WHERE ename NOT IN  ('SCOTT', 'SMITH');

 

Null Conditions

A NULL condition tests for nulls.
What is null?
If a column is empty or no value has been inserted in it then it is called null. Remember 0 is not null and blank string ‘ ’ is also not null.
The following example lists the null conditions.

Condition 
Operation 
Example 
IS [NOT]
NULL

Tests for nulls. This is the only condition that you should use to test for nulls.


SELECT ename
  FROM emp
  WHERE deptno
  IS NULL;

SELECT * FROM emp WHERE ename IS NOT NULL;

EXISTS Conditions

An EXISTS condition tests for existence of rows in a subquery.
The following example shows the EXISTS condition.
Condition 
Operation 
Example 
EXISTS

TRUE if a subquery returns at least one row. 
SELECT deptno
  FROM dept d
  WHERE EXISTS
  (SELECT * FROM emp e
    WHERE d.deptno
    = e.deptno);
  

 

LIKE Conditions

The LIKE conditions specify a test involving pattern matching. Whereas the equality operator (=) exactly matches one character value to another, the LIKE conditions match a portion of one character value to another by searching the first value for the pattern specified by the second. LIKE calculates strings using characters as defined by the input character set.
For example you want to see all employees whose name starts with S char. Then you can use LIKE condition as follows
SQL> select * from emp where ename like ‘S%’ ;
Similarly you want to see all employees whose name ends with “d”
SQL>select * from emp where ename like ‘%d’;
You want to see all employees whose name starts with ‘A’ and ends with ‘d’ like ‘Abid’, ’Adward’, ’Arnold’.
SQL>select * from emp where ename like ‘A%d’;
You want to see those employees whose name contains character ‘a’ anywhere in the string.
SQL> select * from emp where ename like ‘%a%’;
To see those employees whose name contains ‘a’ in second position.
SQL>select * from emp where ename like ‘_a%’;
To see those employees whose name contains ‘a’ as last second character.
SQL>select * from emp where ename like ‘%a_’;
To see those employees whose name contain ‘%’ sign.  i.e. ‘%’ sign has to be used as literal not as wild char.
SQL> select * from emp where ename like ‘%\%%’ escape ‘\’;

The UNION [ALL], INTERSECT, MINUS Operators

 
You can combine multiple queries using the set operators UNION, UNION ALL, INTERSECT, and MINUS. All set operators have equal precedence. If a SQL statement contains multiple set operators, Oracle evaluates them from the left to right if no parentheses explicitly specify another order.

UNION Example

The following statement combines the results with the UNION operator, which eliminates duplicate selected rows. This statement shows that you must match datatype (using the TO_CHAR function) when columns do not exist in one or the other table:
select empno, ename, sal, to_char(null) as “Transfer Date” from emp
  UNION
select empno,ename,to_char(null) as “Sal”,tdate from oldemp;
EMPNO     ENAME     SAL       Transfer Date
-----     -----     ------    -------------
101       Sami      5000     
102       Smith              11-jul-2000
201       Tamim              10-AUG-2000
209       Ravi      2400     

UNION ALL Example

The UNION operator returns only distinct rows that appear in either result, while the UNION ALL operator returns all rows. The UNION ALL operator does not eliminate duplicate selected rows:
select empno,ename from emp
union all
select empno,ename from oldemp;

INTERSECT Example

The following statement combines the results with the INTERSECT operator, which returns only those rows returned by both queries:
SELECT empno FROM emp
INTERSECT
SELECT empno FROM oldemp;

MINUS Example

The following statement combines results with the MINUS operator, which returns only rows returned by the first query but not by the second:
SELECT empno FROM emp
MINUS
SELECT empno FROM oldemp;

SORTING QUERY RESULTS

 
To sort query result you can use ORDER BY clause in SELECT statement. 

Sorting Examples.
The following query sorts the employees according to ascending order of salaries.
 
select * from emp order by sal;
 
The following query sorts the employees according to descending order of salaries.
 
select * from emp order by sal desc;
 
The following query sorts the employees according to ascending order of names.
 
select * from emp order by ename;
 
The following query first sorts the employees according to ascending order of names. If names are equal then sorts employees on descending order of salaries.
 
select * from emp order by ename, sal desc;
 
You can also specify the positions instead of column names. Like in the following query, which shows employees according to ascending order of their names.
 
select * from emp order by 2;
 
The following query first sorts the employees according to ascending order of salaries. If salaries are equal then sorts employees on ascending order of names
 
select * from emp order by 3, 2;

Data Definition Language (DDL) Statements

Data definition language (DDL) statements enable you to perform these tasks:
  • Create, alter, and drop schema objects
  • Grant and revoke privileges and roles
  • Analyze information on a table, index, or cluster
  • Establish auditing options
  • Add comments to the data dictionary
The CREATE, ALTER, and DROP commands require exclusive access to the specified object. For example, an ALTER TABLE statement fails if another user has an open transaction on the specified table.
The GRANT, REVOKE, ANALYZE, AUDIT, and COMMENT commands do not require exclusive access to the specified object. For example, you can analyze a table while other users are updating the table.
Oracle implicitly commits the current transaction before and after every DDL statement.
Many DDL statements may cause Oracle to recompile or reauthorize schema objects.
DDL Statements are

CREATE        :Use to create objects like CREATE TABLE, CREATE FUNCTION,
                        CREATE SYNONYM, CREATE VIEW. Etc.
ALTER           :Use to Alter Objects like ALTER TABLE, ALTER USER, ALTER
                         TABLESPACE, ALTER DATABASE. Etc.
DROP             :Use to Drop Objects like DROP TABLE, DROP USER, DROP
                        TABLESPACE, DROP FUNCTION. Etc.
REPLACE      :Use to Rename table names.

TRUNCATE   :Use to truncate (delete all rows) a table.

Create


To create tables, views, synonyms, sequences, functions, procedures, packages etc.

Example

To create a table, you can give the following statement



create table emp (empno number(5) primary key,
                   name varchar2(20),
                   sal number(10,2),
                   job varchar2(20),
                   mgr  number(5),
                   Hiredate  date,
                   comm number(10,2));

Now Suppose you have emp table now you want to create a TAX table with the following structure and also insert rows of those employees whose salary is above 5000.

Tax
Empno
Tax
Number(5)
Number(10,2)

To do this we can first create TAX table by defining column names and datatypes and then use INSERT into EMP SELECT …. statement to insert rows from emp table. like given below.

create table tax (empno number(5), tax number(10,2));

insert into tax select empno,(sal-5000)*0.40
                     from emp where sal > 5000;

Instead of executing the above two statements the same result can be achieved by giving a single CREATE TABLE AS statement.

create table tax as select empno,(sal-5000)*0.4
   as tax from emp where sal>5000

You can also use CREATE TABLE AS statement to create copies of tables. Like to create a copy EMP table as EMP2 you can give the following statement.

create table emp2 as select * from emp;

To copy tables without rows i.e. to just copy the structure give the following statement

create table emp2 as select * from emp where 1=2;

Alter


Use the ALTER TABLE statement to alter the structure of a table.

Examples:

To add  new columns addr, city, pin, ph, fax to employee table you can give the following statement

alter table emp add (addr varchar2(20), city varchar2(20),
      pin varchar2(10),ph varchar2(20));

To modify the datatype and width of a column. For example we you want to increase the length of the column ename from varchar2(20) to varchar2(30) then give the following command.

alter table emp modify (ename varchar2(30))

To decrease the width of a column the column can be decreased up to largest value it holds.

alter table emp modify (ename varchar2(15));

The above is possible only if you are using Oracle ver 8i and above. In Oracle 8.0 and 7.3 you cannot decrease the column width directly unless the column is empty.

To change the datatype the column must be empty in All Oracle Versions.

 

To drop columns.


From Oracle Ver. 8i you can drop columns directly it was not possible in previous versions.

For example to drop PIN, CITY  columns from emp table.

alter table emp drop column (pin, city);

Remember you cannot drop the column if the table is having only one column.
If the column you want to drop is having primary key constraint on it then you have to give cascade constraint clause.

alter table emp2 drop column (empno) cascade constraints;

To drop columns in previous versions of Oracle8.0 and 7.3. and to change the column name in all Oracle versions do the following.

For example we want to drop pin and city columns and to change SAL column name to SALARY.

Step     1: Create a temporary table with desired columns using subquery.

create table temp as select empno, ename,
 sal AS salary, addr, ph from emp;

Step     2: Drop the original table.

drop table emp;

Step     3: Rename the temporary table to the original table.

rename temp to emp;


Rename

Use the RENAME statement to rename a table, view, sequence, or private synonym for a table, view, or sequence.
·         Oracle automatically transfers integrity constraints, indexes, and grants on the old object to the new object.
·         Oracle invalidates all objects that depend on the renamed object, such as views, synonyms, and stored procedures and functions that refer to a renamed table.
Example

To rename table emp2 to employee2 you can give the following command.

rename emp2 to employee2

 

Drop


Use the drop statement to drop tables, functions, procedures, packages, views, synonym, sequences, tablespaces etc.

Example

The following command drops table emp2

drop table emp2;

If emp2 table is having primary key constraint, to which other tables refer to, then you have to first drop referential integrity constraint and then drop the table. Or if you want to drop table by dropping the referential constraints then give the following command

drop table emp2 cascade constraints;

 

Truncate


Use the Truncate statement to delete all the rows from table permanently . It is same as “DELETE FROM <table_name>” except
·         Truncate does not generate any rollback data hence, it cannot be roll backed.
·         If any delete triggers are defined on the table. Then the triggers are not fired
·         It deallocates free extents from the table. So that the free space can be use by other tables.

Example

truncate table emp;

If you do not want free space and keep it with the table. Then specify the REUSE storage clause like this

truncate table emp reuse storage;

Data Manipulation Language (DML) Statements
Data manipulation language (DML) statements query and manipulate data in existing schema objects. These statements do not implicitly commit the current transaction.
The following are the DML statements available in Oracle.

·         INSERT          :Use to Add Rows to existing table.
·         UPDATE        :Use to Edit Existing Rows in tables.
·         DELETE         :Use to Delete Rows from tables.
·         MERGE          :Use to Update or Insert Rows depending on condition.

Insert


Use the Insert Statement to Add records to existing Tables.

Examples.

To add a new row to an emp table.

Insert into emp values (101,’Sami’,’G.Manager’,
             ’8-aug-1998’,2000);

If you want to add a new row by supplying values for some columns not all the columns then you have to mention the name of the columns in insert statements. For example the following statement inserts row in emp table by supplying values for empno, ename, and sal columns only. The Job and Hiredate columns will be null.

Insert into emp (empno,ename,sal) values (102,’Ashi’,5000);

Suppose you want to add rows from one table to another i.e. suppose we have Old_Emp table and emp table with the following structure
Old_emp
Column Name
Datatype & Width
Empno
Ename
Sal
Tdate
Number(5)
Varchar2(20)
Number(10,2)
Date

Emp
Column Name
Datatype & Width
Empno
Ename
Sal
Hiredate
Job
Number(5)
Varchar2(20)
Number(10,2)
Date
Varchar2(20)

Now we want to add rows from old_emp table to emp table. Then you can give the following insert statement

Insert into emp (empno, ename, sal)
      select empno, ename, sal from old_emp;

Multitable Insert


Suppose we have sales table with the following structure.

Sales
Prodid
Prodname
Mon_Amt
Tue_Amt
Wed_Amt
Thu_Amt
Fri_Amt
Sat_Amt
101
102
AIWA
AKAI
2000
1900
2500
2100
2230
2130
2900
3100
3000
2800
2100
2120

Now we want to add the rows from SALES table  Weekly_Sales Table in the following Structure.

Prodid

Prodname

WeekDay

Amount
101
101
101
101
101
101
102
102
102
102
102
102
AIWA
AIWA
AIWA
AIWA
AIWA
AIWA
AKAI
AKAI
AKAI
AKAI
AKAI
AKAI
Mon
Tue
Wed
Thu
Fri
Sat
Mon
Tue
Wed
Thu
Fri
Sat
2000
2500
2230
2900
3000
2100
1900
2100
2130
3100
2800
2120

To achieve the above we can give a multi table INSERT statement given below

Insert all
     Into week_sales(prodid,prodname,weekday,amount)
     Values (prodid,prodname,’Mon’,mon_amt)
     Into week_sales(prodid,prodname,weekday,amount)
     Values (prodid,prodname,’Tue’,tue_amt)
     Into week_sales(prodid,prodname,weekday,amount)
     Values (prodid,prodname,’Wed’,wed_amt)
     Into week_sales(prodid,prodname,weekday,amount)
     Values (prodid,prodname,’Thu’,thu_amt)
     Into week_sales(prodid,prodname,weekday,amount)
     Values (prodid,prodname,’Fri’,fri_amt)
     Into week_sales(prodid,prodname,weekday,amount)
     Values (prodid,prodname,’Sat’,sat_amt)
  Select prodid,prodname,mon_amt,tue_amt,wed_amt,thu_amt
          Fri_amt,sat_amt from sales;

Update


Update statement is used to  update rows in existing tables which is in your own schema or if you have update privilege on them.

For example to raise the salary by Rs.500 of employee number 104. You can give the following statement.

update emp set sal=sal+500 where empno = 104;

In the above statement if we did not give the where condition then all employees salary will be raised by Rs. 500. That’s why always specify proper WHERE condition if don’t want to update all employees.


For example We want to change the name of employee no 102 from ‘Sami’ to ‘Mohd Sami’ and to raise the salary by 10%. Then the statement will be.

update emp set name=’Mohd Sami’,
  sal=sal+(sal*10/100) where empno=102;

Now we want to raise the salary of all employees by 5%.

update emp set sal=sal+(sal*5/100);

Now to change the names of all employees to uppercase.

update emp set name=upper(name);

Suppose We have a student table with the following structure.

Rollno

Name

Maths

Phy

Chem

Total

Average

101
102
103
Sami
Scott
Smith
99
34
45
90
77
82
89
56
43







Now to compute total which is sum of Maths,Phy and Chem and average.

update student set total=maths+phy+chem,
    average=(maths+phy+chem)/3;


Using Sub Query in the Update Set Clause.

Suppose we added the city column in the employee table and now we want to set this column with corresponding city column in department table which is join to employee table on deptno.

update emp set city=(select city from dept
                          where deptno= emp.deptno);


Delete


Use the DELETE statement to delete the rows from existing tables which are in your schema or if you have DELETE privilege on them.

For example to delete the employee whose empno is 102.

delete from emp where empno=102;

If you don’t mention the WHERE condition then all rows will be deleted.

Suppose we want to delete all employees whose salary is above 2000. Then give the following DELETE statement.

delete from emp where salary > 2000;
The following statement has the same effect as the preceding example, but uses a subquery:
DELETE FROM (SELECT * FROM emp)
    WHERE sal > 2000;

To delete all rows from emp table.

delete from emp;



Merge

Use the MERGE statement to select rows from one table for update or insertion into another table. The decision whether to update or insert into the target table is based on a condition in the ON clause. It is a new feature of Oracle Ver. 9i. It is also known as UPSERT i.e. combination of UPDATE and INSERT.
For example suppose we are having sales and sales_history table with the following structure.

  SALES
Prod
Month
Amount
SONY
SONY
SONY
SONY
SONY
SONY
JAN
FEB
MAR
APR
MAY
JUN
2200
3000
2500
3200
3100
5000

SALES HISTORY
Prod
Month
Amount
SONY
SONY
SONY
AKAI
JAN
MAR
APR
JAN
2000
2500
3000
3200


Now we want to update sales_history table from sales table i.e. those rows which are already present in sales_history, their amount should be updated and those rows which are not present in sales_history table should be inserted.

merge into sales_history sh
   using sales s
   on (s.prod=sh.prod and s.month=sh.month)
when matched then update set sh.amount=s.amount
when not matched then insert values (prod,month,amount);

After the statement is executed sales_history table will look like this.

 SALES_HISTORY
Prod
Month
Amount
SONY
SONY
SONY
SONY
AKAI
SONY
SONY
JAN
FEB
MAR
APR
JAN
MAY
JUN
2200
3000
2500
3200
3200
3100
5000









Transaction Control Language (TCL)

Transaction control statements manage changes made by DML statements.
What is a Transaction?
A transaction is a set of SQL statements which Oracle treats as a Single Unit. i.e. all the statements should execute successfully or none of the statements should execute.
To control transactions Oracle does not made permanent any DML statements unless you commit it. If you don’t commit the transaction and power goes off or system crashes then the transaction is roll backed.
TCL Statements available in Oracle are
COMMIT       :Make changes done in  transaction permanent.
ROLLBACK  :Rollbacks the state of database to the last commit point.
SAVEPOINT :Use to specify a point in transaction to which later you can rollback.

COMMIT

To make the changes done in a transaction permanent issue the COMMIT statement.
The syntax of COMMIT Statement is
COMMIT  [WORK]  [COMMENT ‘your comment’];
WORK is optional.
COMMENT is also optional, specify this if you want to identify this transaction in data dictionary DBA_2PC_PENDING.
Example
insert into emp (empno,ename,sal) values (101,’Abid’,2300);
commit;

ROLLBACK


To rollback the changes done in a transaction give rollback statement. Rollback restore the state of the database to the last commit point.


Example :
delete from emp;
rollback;          /* undo the changes */


SAVEPOINT


Specify a point in a transaction to which later you can roll back.

Example

insert into emp (empno,ename,sal) values (109,’Sami’,3000);
savepoint a;
insert into dept values (10,’Sales’,’Hyd’);
savepoint b;
insert into salgrade values (‘III’,9000,12000);

Now if you give

rollback to a;

Then  row from salgrade table and dept will be roll backed. Now you can commit the row inserted into emp table or rollback the transaction.

If you give

rollback to b;

Then row inserted into salgrade table will be roll backed. Now you can commit the row inserted into dept table and emp table or rollback to savepoint a or completely roll backed the transaction.

If you give

rollback;

Then the whole transactions is roll backed.

If you give

commit;

Then the whole transaction is committed and all savepoints are removed.

Data Control Language (DCL) Statements


Data Control Language Statements are used to grant privileges on tables, views, sequences, synonyms, procedures to other users or roles.

The DCL statements are

GRANT          :Use to grant privileges to other users or roles.
REVOKE       :Use to take back privileges granted to other users and roles.

Privileges are of two types :

·         System Privileges
·         Object privileges

System Privileges are normally granted by a DBA to users. Examples of system privileges are CREATE SESSION, CREATE TABLE, CREATE USER etc.

Object privileges means privileges on objects such as tables, views, synonyms, procedure. These are granted by owner of the object.

Object Privileges are

ALTER  
Change the table definition with the ALTER TABLE statement.  
DELETE  
Remove rows from the table with the DELETE statement.
Note: You must grant the SELECT privilege on the table along with the DELETE privilege. 
INDEX  
Create an index on the table with the CREATE INDEX statement.  
INSERT  
Add new rows to the table with the INSERT statement.  
REFERENCES  
Create a constraint that refers to the table. You cannot grant this privilege to a role.  
SELECT  
Query the table with the SELECT statement.  
UPDATE  
Change data in the table with the UPDATE statement.  

Note: You must grant the SELECT privilege on the table along with the UPDATE privilege. 

Grant

Grant is use to grant privileges on tables, view, procedure to other users or roles


Examples

Suppose you own emp table. Now you want to grant select,update,insert privilege on this table to other user “SAMI”.

grant select, update, insert on emp to sami;

Suppose you want to grant all privileges on emp table to sami. Then

grant  all on emp to sami;

Suppose you want to grant select privilege on emp to all other users of the database. Then

grant select on emp to public;

Suppose you want to grant update and insert privilege on only certain columns not on all the columns then include the column names in grant statement. For example you want to grant update privilege on ename column only and insert privilege on empno and ename columns only. Then give the following statement

grant update (ename),insert (empno, ename)  on emp to sami;


To grant select statement on emp table to sami and to make sami be able further pass on this privilege you have to give WITH GRANT OPTION clause in GRANT statement like this.

grant select on emp to sami with grant option;

REVOKE


Use to revoke privileges already granted to other users.

For example to revoke select, update, insert privilege you have granted to Sami then give the following statement.

revoke select, update, insert on emp from sami;

To revoke select statement on emp granted to public give the following command.

revoke select on emp from public;

To revoke update privilege on ename column and insert privilege on empno and ename columns give the following revoke statement.

revoke update, insert on emp from sami;

Note :You cannot take back column level privileges. Suppose you just want to take back  insert privilege on ename column then you have to first take back the whole insert privilege and then grant privilege on empno column.

ROLES


A role is a group of Privileges. A role is very handy in managing privileges, Particularly in such situation when number of users should have the same set of privileges.


For example you have four users :Sami, Scott, Ashi, Tanya in the database. To these users you want to grant select ,update privilege on emp table, select,delete privilege on dept table. To do this first create a role by giving the following statement

create role clerks

Then grant privileges to this role.

grant select,update on emp to clerks;
grant select,delete on dept to clerks;

Now grant this clerks role to users like this

grant clerks to sami, scott, ashi, tanya ;

Now Sami, Scott, Ashi and Tanya have all the privileges granted on clerks role.

Suppose after one month you want grant delete on privilege on emp table all these users then just grant this privilege to clerks role and automatically all the users will have the privilege.

grant delete on emp to clerks;

If you want to take back update privilege on emp table from these users just take it back from clerks role.

revoke update on emp from clerks;


To Drop a role

Drop role clerks;

LISTING INFORMATION ABOUT PRIVILEGES


To see which table privileges are granted by you to other users.

SELECT * FROM USER_TAB_PRIVS_MADE

To see which table privileges are granted to you by other users

SELECT * FROM USER_TAB_PRIVS_RECD;

To see which column level privileges are granted by you to other users.

SELECT * FROM USER_COL_PRIVS_MADE

To see which column level privileges are granted to you by other users

SELECT * FROM USER_COL_PRIVS_RECD;

To see which privileges are granted to roles

SELECT * FROM USER_ROLE_PRIVS;

INTEGRITY CONSTRAINTS


Integrity Constraints are used to prevent the entry of invalid information into tables. There are five Integrity Constraints Available in Oracle. They are :

·         Not Null
·         Primary Key
·         Foreign Key
·         Check
·         Unique

Not Null


By default all columns in a table can contain null values. If you want to ensure that a column must always have a value, i.e. it should not be left blank, then define a NOT NULL constraint on it.

Always be careful in defining NOT NULL constraint on columns, for example in employee table some employees might have commission  and some employees might not have any commission. If you put NOT NULL constraint on COMM column then you will not be able insert rows for those employees whose commission is null. Only put NOT NULL constraint on those column which are essential for example in EMP table ENAME column is a good candidate for NOT NULL constraint.

Primary Key


Each table can have one primary key, which uniquely identifies each row in a table and ensures that no duplicate rows exist. Use the following guidelines when selecting a primary key:
·         Whenever practical, use a column containing a sequence number. It is a simple way to satisfy all the other guidelines.
·         Minimize your use of composite primary keys. Although composite primary keys are allowed, they do not satisfy all of the other recommendations. For example, composite primary key values are long and cannot be assigned by sequence numbers.
·         Choose a column whose data values are unique, because the purpose of a primary key is to uniquely identify each row of the table.
·         Choose a column whose data values are never changed. A primary key value is only used to identify a row in the table, and its data should never be used for any other purpose. Therefore, primary key values should rarely or never be changed.
·         Choose a column that does not contain any nulls. A PRIMARY KEY constraint, by definition, does not allow any row to contain a null in any column that is part of the primary key.
·         Choose a column that is short and numeric. Short primary keys are easy to type. You can use sequence numbers to easily generate numeric primary keys.
For example in EMP table EMPNO column is a good candidate for PRIMARY KEY.

To define a primary key on a table give the following command.

Alter table emp add constraint emppk primary key (empno);

The above command will succeed only if the existing values are compliant i.e. no duplicates are there in EMPNO column. If EMPNO column contains any duplicate value then the above command fails and Oracle returns an error indicating of non compliant values.

Whenever you define a PRIMARY KEY oracle automatically creates a index on that column. If an Index already exist on that column then oracle uses that index only.

FOREIGN KEY


On whichever column you put FOREIGN KEY constraint then the values in that column must refer to existing values in the other table. A foreign key column can refer to primary key or unique key column of other tables. This Primary key and foreign key relationship is also known as PARENT-CHILD relationship i.e. the table which has Primary Key is known as PARENT table and the table which has Foreign key is known as CHILD table. This relationship is also known as REFERENTIAL INTEGRITY.

The following shows an example of parent child relationship.

Here EMPNO in attendance table is a foreign key referring to EMPNO of EMP table.

Alter table attendance add constraint empno_fk
     Foreign key (empno) references emp(empno);

The above command succeeds only if EMPNO column in ATTENDANCE table contains values which are existing in EMPNO column of EMP table. If any value is not existing then the above statement fails and Oracle returns an error indicating non compliant values.

Some points to remember for referential integrity

·         You cannot delete a parent record if any existing child record is there. If you have to first delete the child record before deleting the parent record. In the above example you cannot delete row of employee no. 101 since it’s child exist in the ATTENDANCE table. However, you can delete the row of employee no. 103 since no child record exist for this employee in ATTENDANCE table.  If you define the FOREIGN KEY with ON DELETE CASCADE option then you can delete the parent record and if any child record exist it will be automatically deleted.

To define a foreign key constraint with ON DELETE CASCADE option give the following command.

Alter table attendance add constraint empno_fk
          Foreign key (empno) references emp(empno)
              On delete cascade;                   

In Oracle 9i oracle has also given a new feature i.e. ON DELETE SET NULL . That is it sets the value for foreign key to null whenever the parent record is deleted.

To define a foreign key constraint with ON DELETE SET NULL option give the following command.

Alter table attendance add constraint empno_fk
          Foreign key (empno) references emp(empno)
              On delete set null;                  

·         You also cannot drop the parent table without first dropping the FOREIGN KEY constraint from attendance table. However if you give CASCADE CONSTRAINTS option in DROP TABLE statement then Oracle will automatically drop the references and then drops the table.

CHECK


Use the check constraint to validate values entered into a column. For example in the above ATTENDANCE table, the DAYS column should not contain any value more than 31. For this you can define a CHECK constraint as given below

Alter table attendance add constraint dayscheck
              Check (days <= 31);

Similarly if you  want the salaries entered in to SAL column of employee table should be between 1000 and 20000 then you can define a CHECK constraint on EMP table as follows

alter table emp add constraint sal_check
                   check (sal between 1000 and 20000);

You can define as  many check constraints on a single column as you want there is no restrictions on number of check constraints.


UNIQUE KEY


Unique Key constraint is same as primary key i.e. it does not accept duplicate values, except the following differences

·         There can be only on Primary key per table. Whereas, you can have as many Unique Keys per table as you want.

·         Primary key does not accept NULL values whereas, unique key columns can be left blank.

You can also refer to Unique key from Foreign key of other tables.

On which columns you should put Unique Key Constraint ?

It depends on situations, first situation is suppose you have already defined a Primary key constraint on one column and now you have another column which also should not contain any duplicate values, Since a table can have only one primary key,  you can define Unique Key constraint on these columns.  Second situation is when a column should not contain any duplicate value but it should also be left blank. For example in the EMP table IDNO is a good candidate for Unique Key because all the IDNO’s are unique but some employees might not have ID Card so you want to leave this column blank.

To define a UNIQUE KEY constraint on an existing table give the following command.

Alter table emp add constraint id_unique unique (idno);

Again the above command will execute successfully if IDNO column contains complying values otherwise you have to remove non complying values and then add the constraint.

DEFAULT

You can also specify the DEFAULT value for columns i.e. when user does not enter anything in that column then that column will have the default value. For example in EMP table suppose most of the employees are from Hyderabad, then you can put this as default value for CITY column. Then while inserting records if user doesn’t enter anything in the CITY column then the city column will have Hyderabad.

To define default value for columns create the table as given below

create table emp (empno number(5),
                   name varchar2(20),
                   sal number(10,2),
                   city varchar2(20) default ‘Hyd’);

Now, when user inserts record like this

insert into emp values (101,’Sami’,2000,’Bom’);

Then the city column will have value ‘Bom ‘. But when user inserts a record like this

Insert into emp (empno,name,sal) values (102,’Ashi’,4000);

Then the city column will have  value ‘Hyd’. Since it is the default.

Examples

Defining Constraints in CREATE TABLE statement.

create table emp (empno number(5) constraint emppk
                                  Primary key,
                   ename varchar2(20) constraint namenn
                                  not null,
                   sal  number(10,2) constraint salcheck
                        check (sal between 1000 and 20000)
                   idno varchar2(20) constraint id_unique
                             unique );

create table attendance (empno number(5) constraint empfk
                             references emp (empno)
                             on delete cascade,
                   month varchar2(10),
                   days number(2) constraint dayscheck
                             check (days <= 31) );

The name of the constraints are optional. If you don’t define the names then oracle generates the names randomly like ‘SYS_C1234’



Another way of defining constraint in CREATE TABLE statement.

create table emp (empno number(5),
                   ename varchar2(20) not null,
                   sal  number(10,2),
                   idno varchar2(20),
                      constraint emppk Primary key (empno)
  constraint salcheck
                        check (sal between 1000 and 20000)
                     constraint id_unique unique (idno) );

create table attendance (empno number(5),
                   month varchar2(10),
                   days number(2),
constraint empfk foreign key (empno)    
     references emp (empno)
       on delete cascade
constraint dayscheck
                        check (days <= 31) );

Deferring Constraint Checks

You may wish to defer constraint checks on UNIQUE and FOREIGN keys if the data you are working with has any of the following characteristics:
  • Tables are snapshots
  • Tables that contain a large amount of data being manipulated by another application, which may or may not return the data in the same order
  • Update cascade operations on foreign keys
When dealing with bulk data being manipulated by outside applications, you can defer checking constraints for validity until the end of a transaction.
Ensure Constraints Are Created Deferrable
After you have identified and selected the appropriate tables, make sure their FOREIGN, UNIQUE and PRIMARY key constraints are created deferrable. You can do so by issuing a statement similar to the following:
create table attendance (empno number(5),
                   month varchar2(10),
                   days number(2),
constraint empfk foreign key (empno)    
     references emp (empno)
       on delete cascade
          DEFERRABLE
constraint dayscheck
                        check (days <= 31) );


Now give the following statement

Set constraint empfk deferred;
Update attendance set empno=104 where empno=102;
Insert into emp values (104,’Sami’,4000,’A123’);
Commit;
You can check for constraint violations before committing by issuing the SET CONSTRAINTS ALL IMMEDIATE statement just before issuing the COMMIT. If there are any problems with a constraint, this statement will fail and the constraint causing the error will be identified. If you commit while constraints are violated, the transaction will be rolled back and you will receive an error message.

 

ENABLING AND DISABLING CONSTRIANTS.

You can enable and disable constraints at any time.
To enable and disable constraints the syntax is

ALTER TABLE <TABLE_NAME> ENABLE/DISABLE
           CONSTRAINT  <CONSTRAINT_NAME>

For example to disable primary key of EMP table give the following statement

Alter table emp disable constraint emppk;

And to enable it again, give the following statement

Alter table emp enable constraint emppk;

Dropping constraints.


You can drop constraint by using ALTER TABLE DROP constraint statement.
For example to drop Unique constraint from emp table, give the following statement

Alter table emp drop constraint id_unique;

To drop primary key constraint from emp table.

Alter table emp drop constraint emppk;

The above statement will succeed only if the foreign key is first dropped otherwise you have to first drop the foreign key and then drop the primary key. If you want to drop primary key along with the foreign key in one statement then CASCADE CONSTRAINT statement like this

Alter table emp drop constraint emppk cascade;

Viewing Information about constraints


To see information about constraints, you can query the following data dictionary tables.

select * from user_constraints;
select * from user_cons_columns;

Views

Views are known as logical tables. They represent the data of one of more tables. A view derives its data from the tables on which it is based. These tables are called base tables. Views can be based on actual tables or another view also.
Whatever DML operations you performed on a view they actually affect the base table of the view. You can treat views same as any other table. You can Query, Insert, Update and delete from views, just as any other table.
Views are very powerful and handy since they can be treated just like any other table but do not occupy the space of a table.
The following sections explain how to create, replace, and drop views using SQL commands.

Creating Views

Suppose we have EMP and DEPT table. To see the empno, ename, sal, deptno, department name and location we have to give a join query like this.
select e.empno,e.ename,e.sal,e.deptno,d.dname,d.loc
        From emp e, dept d where e.deptno=d.deptno;
So everytime we want to see emp details and department names where they are working we have to give a long join query. Instead of giving this join query again and again, we can create a view on these table by using a CREATE VIEW command given below
create view emp_det as select e.empno,
e.ename,e.sal,e.deptno,d.dname,d.loc
        from emp e, dept d where e.deptno=d.deptno;
Now to see the employee details and department names we don’t have to give a join query, we can just type the following simple query.
select * from emp_det;
This will show same result as you have type the long join query.  Now you can treat this EMP_DET view same as  any other table.
For example, suppose all the employee working in Department No. 10 belongs to accounts department and most of the time you deal with these people. So every time you  have to give a DML or Select statement you have to give a WHERE condition like .....WHERE DEPTNO=10. To avoid this, you can create a view as given below

CREATE VIEW accounts_staff AS
    SELECT Empno, Ename, Deptno
    FROM Emp
    WHERE Deptno = 10
    WITH CHECK OPTION CONSTRAINT ica_Accounts_cnst;
 
Now to see the account people you don’t have to give a query with where condition you can just type the following query.
 
Select * from accounts_staff;
Select sum(sal) from accounst_staff;
Select max(sal) from accounts_staff; 
 
As you can see how views make  things easier.
The query that defines the ACCOUNTS_STAFF view references only rows in department 10. Furthermore, WITH CHECK OPTION creates the view with the constraint that INSERT and UPDATE statements issued against the view are not allowed to create or result in rows that the view cannot select.
Considering the example above, the following INSERT statement successfully inserts a row into the EMP table through the ACCOUNTS_STAFF view:
INSERT INTO Accounts_staff VALUES (110, 'ASHI', 10);
However, the following INSERT statement is rolled back and returns an error because it attempts to insert a row for department number 30, which could not be selected using the ACCOUNTS_STAFF view:
INSERT INTO Accounts_staff VALUES (111, 'SAMI', 30);

Creating FORCE VIEWS 

A view can be created even if the defining query of the view cannot be executed, as long as the CREATE VIEW command has no syntax errors. We call such a view a view with errors. For example, if a view refers to a non-existent table or an invalid column of an existing table, or if the owner of the view does not have the required privileges, then the view can still be created and entered into the data dictionary.
You can only create a view with errors by using the FORCE option of the CREATE VIEW command:
CREATE FORCE VIEW AS ...;
When a view is created with errors, Oracle returns a message and leaves the status of the view as INVALID. If conditions later change so that the query of an invalid view can be executed, then the view can be recompiled and become valid. Oracle dynamically compiles the invalid view if you attempt to use it. 

Replacing/Altering Views

To alter the definition of a view, you must replace the view using one of the following methods:
  • A view can be dropped and then re-created. When a view is dropped, all grants of corresponding view privileges are revoked from roles and users. After the view is re-created, necessary privileges must be regranted.
  • A view can be replaced by redefining it with a CREATE VIEW statement that contains the OR REPLACE option. This option replaces the current definition of a view, but preserves the present security authorizations.
For example, assume that you create the ACCOUNTS_STAFF view, as given in a previous example. You also grant several object privileges to roles and other users. However, now you realize that you must redefine the ACCOUNTS_STAFF view to correct the department number specified in the WHERE clause of the defining query, because it should have been 30. To preserve the grants of object privileges that you have made, you can replace the current version of the ACCOUNTS_STAFF view with the following statement:
CREATE OR REPLACE VIEW Accounts_staff AS
    SELECT Empno, Ename, Deptno
    FROM Emp
    WHERE Deptno = 30
    WITH CHECK OPTION CONSTRAINT ica_Accounts_cnst;
Replacing a view has the following effects:
  • Replacing a view replaces the view's definition in the data dictionary. All underlying objects referenced by the view are not affected.
  • If previously defined but not included in the new view definition, then the constraint associated with the WITH CHECK OPTION for a view's definition is dropped.
  • All views and PL/SQL program units dependent on a replaced view become invalid.
With some restrictions, rows can be inserted into, updated in, or deleted from a base table using a view. The following statement inserts a new row into the EMP table using the ACCOUNTS_STAFF view:
INSERT INTO Accounts_staff
    VALUES (199, 'ABID', 30);
Restrictions on DML operations for views use the following criteria in the order listed:
  1. If a view is defined by a query that contains SET or DISTINCT operators, a GROUP BY clause, or a group function, then rows cannot be inserted into, updated in, or deleted from the base tables using the view.
  1. If a view is defined with WITH CHECK OPTION, then a row cannot be inserted into, or updated in, the base table (using the view), if the view cannot select the row from the base table.
  1. If a NOT NULL column that does not have a DEFAULT clause is omitted from the view, then a row cannot be inserted into the base table using the view.
  1. If the view was created by using an expression, such as DECODE(deptno, 10, "SALES", ...), then rows cannot be inserted into or updated in the base table using the view.
The constraint created by WITH CHECK OPTION of the ACCOUNTS_STAFF view only allows rows that have a department number of 10 to be inserted into, or updated in, the EMP table. Alternatively, assume that the ACCOUNTS_STAFF view is defined by the following statement (that is, excluding the DEPTNO column):
CREATE VIEW Accounts_staff AS
    SELECT Empno, Ename
    FROM Emp
    WHERE Deptno = 10
    WITH CHECK OPTION CONSTRAINT ica_Accounts_cnst;
Considering this view definition, you can update the EMPNO or ENAME fields of existing records, but you cannot insert rows into the EMP table through the ACCOUNTS_STAFF view because the view does not let you alter the DEPTNO field. If you had defined a DEFAULT value of 10 on the DEPTNO field, then you could perform inserts.
If you don’t want any DML operations to be performed on views, create them WITH READ ONLY option. Then no DML operations are allowed on views.

Referencing Invalid Views

When a user attempts to reference an invalid view, Oracle returns an error message to the user:
ORA-04063: view 'view_name' has errors
This error message is returned when a view exists but is unusable due to errors in its query (whether it had errors when originally created or it was created successfully but became unusable later because underlying objects were altered or dropped).

 

Dropping Views

Use the SQL command DROP VIEW to drop a view. For example:
DROP VIEW Accounts_staff;

Modifying a Join View

Oracle allows you, with some restrictions, to modify views that involve joins. Consider the following simple view:
CREATE VIEW Emp_view AS
    SELECT Ename, Empno, deptno FROM Emp;
This view does not involve a join operation. If you issue the SQL statement:
UPDATE Emp_view SET Ename = 'SHAHRYAR' WHERE Empno = 109;
then the EMP base table that underlies the view changes, and employee 109's name changes from ASHI to SHAHRYAR in the EMP table.
However, if you create a view that involves a join operation, such as:
CREATE VIEW Emp_dept_view AS
  SELECT e.Empno, e.Ename, e.Deptno, e.Sal, d.Dname, d.Loc
    FROM Emp e, Dept d    /* JOIN operation */
     WHERE e.Deptno = d.Deptno
       AND d.Loc IN ('HYD', 'BOM', 'DEL');
then there are restrictions on modifying either the EMP or the DEPT base table through this view.
A modifiable join view is a view that contains more than one table in the top-level FROM clause of the SELECT statement, and that does not contain any of the following:
  • DISTINCT operator
  • Aggregate functions: AVG, COUNT, GLB, MAX, MIN, STDDEV, SUM, or VARIANCE
  • Set operations: UNION, UNION ALL, INTERSECT, MINUS
  • GROUP BY or HAVING clauses
  • START WITH or CONNECT BY clauses
  • ROWNUM pseudocolumn
Any UPDATE, INSERT, or DELETE statement on a join view can modify only one underlying base table.
The following example shows an UPDATE statement that successfully modifies the EMP_DEPT_VIEW view:
UPDATE Emp_dept_view
  SET Sal = Sal * 1.10 
    WHERE Deptno = 10;
The following UPDATE statement would be disallowed on the EMP_DEPT_VIEW view:
UPDATE Emp_dept_view
  SET Loc = 'BOM'
    WHERE Ename = 'SAMI';
This statement fails with an ORA-01779 error ("cannot modify a column which maps to a non key-preserved table"), because it attempts to modify the underlying DEPT table, and the DEPT table is not key preserved in the EMP_DEPT view.
In general, all modifiable columns of a join view must map to columns of a key-preserved table. If the view is defined using the WITH CHECK OPTION clause, then all join columns and all columns of repeated tables are not modifiable.
So, for example, if the EMP_DEPT view were defined using WITH CHECK OPTION, then the following UPDATE statement would fail:
UPDATE Emp_dept_view
    SET Deptno = 10
        WHERE Ename = 'SAMI';
The statement fails because it is trying to update a join column.

Deleting from a Join View

You can delete from a join view provided there is one and only one key-preserved table in the join.
The following DELETE statement works on the EMP_DEPT view:
DELETE FROM Emp_dept_view
    WHERE Ename = 'SMITH';
This DELETE statement on the EMP_DEPT view is legal because it can be translated to a DELETE operation on the base EMP table, and because the EMP table is the only key-preserved table in the join.
In the following view, a DELETE operation cannot be performed on the view because both E1 and E2 are key-preserved tables:
CREATE VIEW emp_emp AS
    SELECT e1.Ename, e2.Empno, e1.Deptno
        FROM Emp e1, Emp e2
        WHERE e1.Empno = e2.Empno;
If a view is defined using the WITH CHECK OPTION clause and the key-preserved table is repeated, then rows cannot be deleted from such a view. For example:
CREATE VIEW Emp_mgr AS
    SELECT e1.Ename, e2.Ename Mname
       FROM Emp e1, Emp e2
            WHERE e1.mgr = e2.Empno
            WITH CHECK OPTION;
No deletion can be performed on this view because the view involves a self-join of the table that is key preserved.

Inserting into a Join View

The following INSERT statement on the EMP_DEPT view succeeds, because only one key-preserved base table is being modified (EMP), and 40 is a valid DEPTNO in the DEPT table (thus satisfying the FOREIGN KEY integrity constraint on the EMP table).
INSERT INTO Emp_dept (Ename, Empno, Deptno)
    VALUES ('ASHU', 119, 40);
The following INSERT statement fails for the same reason: This UPDATE on the base EMP table would fail: the FOREIGN KEY integrity constraint on the EMP table is violated.
INSERT INTO Emp_dept (Ename, Empno, Deptno)
    VALUES ('ASHU', 110, 77);
The following INSERT statement fails with an ORA-01776 error ("cannot modify more than one base table through a view").
INSERT INTO Emp_dept (Ename, Empno, Deptno)
    VALUES (110, 'TANNU’, 'BOMBAY');
An INSERT cannot, implicitly or explicitly, refer to columns of a non-key-preserved table. If the join view is defined using the WITH CHECK OPTION clause, then you cannot perform an INSERT to it.

Listing Information about VIEWS.

To see how many views are there in your schema. Give the following query.

Select * from user_views;

 

To see which columns are updatable in join views.

Data Dictionaries which shows which columns are updatable.
View Name 
Description 
USER_UPDATABLE_COLUMNS 
Shows all columns in all tables and views in the user's schema that are modifiable 
DBA_UPDATABLE_COLUMNS 
Shows all columns in all tables and views in the DBA schema that are modifiable 
ALL_UPDATABLE_VIEWS 
Shows all columns in all tables and views that are modifiable 

If you are in doubt whether a view is modifiable, then you can SELECT from the view USER_UPDATABLE_COLUMNS to see if it is. For example:
SELECT * FROM USER_UPDATABLE_COLUMNS WHERE TABLE_NAME = 'EMP_DEPT_VIEW';
This might return:
OWNER       TABLE_NAME    COLUMN_NAM      UPD
----------  ----------    ----------      ---
SCOTT       EMP_DEPT      EMPNO           NO
SCOTT       EMP_DEPT      ENAME           NO
SCOTT       EMP_DEPT      DEPTNO          NO
SCOTT       EMP_DEPT      DNAME           NO
SCOTT       EMP_DEPT      LOC             NO
 
5 rows selected.



Expressions in a SELECT statement: Arithmetic operations can be performed using

SELECT   statement as shown below.

SQL> SELECT 10+5 FROM DUAL;
      10+5
----------
        15

SQL> SELECT 10-5 FROM DUAL;
      10-5
----------
         5

SQL> SELECT 10*5 FROM DUAL;

      10*5
----------
        50

SQL> SELECT 10/5 FROM DUAL;

      10/5
----------
         2




Numeric Functions: 

These functions operate on Numeric data hence is the name.
Note: Argument “num” in the following functions is any float-valued number.

ABS(num): Returns absolute value of the given number.(i.e.  Always positive value)

SQL> SELECT ABS(10) FROM DUAL;
   ABS(10)
----------
        10
SQL> SELECT ABS(-10) FROM DUAL;
  ABS(-10)
----------
        10
CEIL(num): It returns the smallest integer greater than the given number.

SQL> SELECT CEIL(123.456) FROM DUAL;

CEIL(123.456)
-------------
          124
FLOOR(num): It returns the largest integer smaller than the given value.
SQL> SELECT FLOOR(123.456) FROM DUAL;

FLOOR(123.456)
--------------
           123
LN(num) : It returns natural logarithm value of “num” .

SQL> SELECT LN(10) FROM DUAL;
    LN(10)
----------
2.30258509

LOG(m, n): It returns logarithm of  “n”  with base “m”.

SQL> SELECT LOG(100,10) FROM DUAL;
LOG(100,10)
-----------
         .5
SQL> SELECT LOG(10,100) FROM DUAL;
LOG(10,100)
-----------
          2
MOD(m, n) :  It returns remainder of “m” divided by “n”.

SQL> SELECT MOD(10,3) FROM DUAL;
 MOD(10,3)
----------
         1
POWER(m, n):  It returns value equal to “m” raised by “n”.

SQL> SELECT POWER(10,2) FROM DUAL;
POWER(10,2)
-----------
        100
ROUND(m, n): It rounds the given float-valued number “m” to the “n” places after the decimal

SQL> SELECT ROUND(1.23456) FROM DUAL;
ROUND(1.23456)
--------------
              1
SQL> SELECT ROUND(1.23456,3) FROM DUAL;

ROUND(1.23456,3)
----------------
           1.235

SQRT(m):  It calculates square root value of number “m”


SQL> SELECT SQRT(9) FROM DUAL;

   SQRT(9)
----------
         3
TRUNC(m, n): It truncates given float-valued number “m” to “n” places after the decimal.

SQL> SELECT TRUNC(1.23456) FROM DUAL;
TRUNC(1.23456)
--------------
             1
SQL> SELECT TRUNC(1.23456,3) FROM DUAL;

TRUNC(1.23456,3)
----------------
             1.234

GREATEST(expr1, expr2, …) : It finds the greatest value among the given expressions.

SQL> SELECT GREATEST(4,7,3,5,9,2) FROM DUAL;
GREATEST(4,7,3,5,9,2)
---------------------
                    9
LEAST(expr1, expr2, …): It finds the Lowest value among the given expressions.
SQL> SELECT LEAST(4,7,3,5,9,2) FROM DUAL;

LEAST(4,7,3,5,9,2)
------------------
                  2

CHARACTER FUNCTIONS:



UPPER( str) :  It converts all letters in the given string “str” into Upper case.

SQL> SELECT UPPER('abcDEfg') FROM DUAL;
UPPER('
-------
ABCDEFG

LOWER(str):  It converts all the letters in the given string  “str” into Lower Case.

SQL> SELECT LOWER('ABCDEfg') FROM DUAL;
LOWER('
-------
abcdefg

INITCAP(str): It converts first letter of every word in the given string “str” into Upper Case and remaining letters into lower case. It is like proper function in FoxPro.

SQL> SELECT INITCAP('ABCDEF') FROM DUAL;

INITCA
------
Abcdef





LENGTH(str) : This function returns the number of characters in the given string (including spaces)

SQL> SELECT LENGTH('ABCD') FROM DUAL;

LENGTH('ABCD')
--------------
             4

SQL> SELECT LENGTH('AB CD') FROM DUAL;

LENGTH('ABCD')
--------------
              5

SUBSTR(str, m, n) : Will extract  “n” characters from the given string starting from
“m th” position.

SQL>  SELECT SUBSTR('ABCDEFG',2,3) FROM DUAL
SUB
---
BCD

SQL> SELECT SUBSTR('ABCDEF',1,3) FROM DUAL
SUB
---
ABC
INSTR(string, str): It displays the location of  “str” in the given string “string” .

SQL> SELECT INSTR('TRYING TO KEEP THE THINGS AS SIMPLE AS POSSIBLE','AS') FROM DUAL;
INSTR('
-----------------------------------------------------
       27

INSTR(string, str, m, n): It displays nth occurrence of  “str” in the  string “string” starting from “m”.

SQL> SELECT INSTR('TRYING TO KEEP THE THINGS AS SIMPLE AS POSSIBLE','AS',1,2) FROM DUAL
INSTR(
------------------------
       37



Note : DUAL IS A TABLE WITH 1 COLUMN AND 1 ROW OF DATA IN IT.

SQL > DESC DUAL
 Name                                      Null?    Type
 ----------------------------------------- -------- -
 DUMMY                                              VARCHAR2(1)

SQL > SELECT * FROM DUAL;

DUMMY
------------
X

LPAD() : This function is used to left pad the the given string with specified character or string.

SQL > SELECT LPAD('BCD',4,'A') FROM DUAL;

LPAD
----
ABCD

Explanation: To the given string "BCD" add "A" to the left necessary number of times to make it a string of 4 characters.

SQL > SELECT LPAD('BCD',5,'A') FROM DUAL;

LPAD(
-----
AABCD
Explanation: To the given string "BCD" add "A" to the left necessary number of times to make it a string of 5 characters.

SQL > SELECT LPAD('BCD',3,'A') FROM DUAL;

LPA
---
BCD

Explanation: To the given string "BCD" add "A" to the left necessary number of times to make it a string of 3 characters.






SQL > SELECT LPAD(' ',ROWNUM,'*') FROM EMP;
LPAD('',ROWNUM,'*')
-----------------------------------------------------------------
*
**
***
****
*****
******
*******
********
*********
**********
***********
************
*************
RPAD(): This function is used to left pad the the given string with specified character or string.

SQL > SELECT RPAD('BILL ' , 12 , 'CLINTON') FROM DUAL;

RPAD('BILL',
------------
BILL CLINTON


LTRIM(): This function removes specified string from the given string if it is there to the left of given string.

SQL > SELECT LTRIM('GEORGE BUSH', 'GEORGE') FROM DUAL;

LTRIM
-----
 BUSH

RTRIM(): This function removes specified string from the given string if it is there to the right of given string.

SQL > SELECT RTRIM('TONY BLAIR', 'AIR') FROM DUAL;

RTRIM('
-------
TONY BL

ASCII(): Displays equivalent ASCII value of a character.
SQL > SELECT ASCII('A') FROM DUAL;

ASCII('A')
----------
        65


SQL >SELECT TRANSLATE('JOHN','H','N') FROM DUAL;

TRAN
----
JONN

OTHER FUNCTIONS:

Note: Arguments to the below given functions are in terms of radians

COS(x): It returns the Cosine of x.
SQL> SELECT COS(0) FROM DUAL;
COS(0)
----------
         1
COSH(x) : It returns hyperbolic cosine of x.

SQL> SELECT COSH(0) FROM DUAL;

 COSH(0)
----------
         1

SIN(x) : It returns sine of x.

SQL> SELECT SIN(0) FROM DUAL;

  SIN(0)
----------
         0

SINH(x): It returns hyperbolic sine of x.

SQL> SELECT SINH(0) FROM DUAL;

 SINH(0)
----------
         0
TAN(x): It returns tangent of x.

SQL> SELECT TAN(0) FROM DUAL;

 TAN(0)
----------
         0


TANH(x): It returns hyperbolic tangent of x.
SQL> SELECT TANH(0) FROM DUAL;

TANH(0)
----------
         0


DATEFUNCTIONS:
          
 ADD_MONTHS(date, n) : Adds n months to the specified date .

  SQL> SELECT  ADD_MONTHS('1-JAN-05',5) FROM DUAL;
 ADD_MONTHS
 ------------------
  01-JUN-05
LAST_DAY(date): Gives last date of the specified month (date).

SQL> SELECT LAST_DAY('1-JAN-05') FROM DUAL;
LAST_DAY(
---------
31-JAN-05
MONTHS_BETWEEN(date1, date2): It gives difference between the two dates date1, date2 in months.

SQL>  SELECT MONTHS_BETWEEN('31-DEC-05','1-JAN-05') FROM DUAL

MONTHS_BETWEEN('31-DEC-05','1-JAN-05')
--------------------------------------
                            11.9677419

SQL>  SELECT MONTHS_BETWEEN('31-JUL-05','1-JUL-05') FROM DUAL

MONTHS_BETWEEN('31-JUL-05','1-JUL-05')
--------------------------------------
                            .967741935
NEXT_DAY(date, ‘day’ ) :  It gives date of the next occurrence of the specified day after the given date.
 
SQL> SELECT NEXT_DAY('01-JAN-05','FRI') FROM DUAL;

NEXT_DAY(                                 (Next Friday after 1-jan-05 is on 7-jan-05)
---------
07-JAN-05

TO_DATE (string): This function converts a string into an Oracle date.

SQL> SELECT TO_DATE('01 JANUARY 2005','DD MONTH YYYY') FROM DUAL;
TO_DATE('
---------
01-JAN-05

SQL> SELECT TO_DATE('MAR 05 01','MON YY DD') FROM DUAL;
TO_DATE('
---------
01-MAR-05

SQL> SELECT TO_DATE('01/01/05', 'DD/MM/YY') FROM DUAL;
TO_DATE('
---------
01-JAN-05

The USER, SYSDATE Functions:
USER   function displays login name of the user.

SQL> SELECT USER FROM DUAL;

USER
------------------------------
SCOTT

SYSDATE  function displays system date.(Date in your windows)

SQL> SELECT SYSDATE FROM DUAL;

SYSDATE
---------
1-JAN-05

CONVERSION FUNCTIONS:


TO_CHAR: This function is used to convert a date or number to character string.
SQL>  SELECT TO_CHAR(SYSDATE,'DAY DD MONTH YYYY') FROM DUAL

TO_CHAR (SYSDATE,'DAYDDMONTH
---------------------------
SATURDAY 01 JANUARY   2005

SQL> SELECT TO_CHAR (SYSDATE,' DD DY MM YY') FROM DUAL;

TO_CHAR (SYSDA
-------------
 01 SAT 01 05

NVL()  Function: This function is used to substitute any null value with a user-defined value.

Consider the following data from EMP table of SCOTT.

SQL> SELECT EMPNO, ENAME, SAL, COMM FROM EMP;

     EMPNO  ENAME             SAL       COMM
---------- ---------- ---------- -------------------------
      7369  SMITH               800
      7499  ALLEN            1600            300
      7521  WARD             1250            500
      7566  JONES            2975
      7654  MARTIN          1250          1400
      7698  BLAKE           2850
      7782  CLARK           2450
      7788  SCOTT            3000
      7839  KING                5000
      7844  TURNER          1500                 0
      7876  ADAMS           1100
      7900  JAMES             950
      7902  FORD              3000
      7934  MILLER            1300


In the above table except for 7499, 7521, 7654 and 7844 all others commissions are null
To display their commission as “0” (zero)
We can use NVL() function as shown below.

SQL> SELECT EMPNO, ENAME, SAL, NVL (COMM, 100) FROM EMP

     EMPNO  ENAME             SAL   NVL(COMM,100)
      ---------- ---------- ---------- -------------
      7369  SMITH             800         100
      7499  ALLEN            1600         300
      7521  WARD             1250         500
      7566  JONES            2975         100
      7654  MARTIN           1250        1400
      7698  BLAKE            2850         100
      7782  CLARK            2450         100
      7788  SCOTT            3000         100
      7839  KING             5000         100
      7844  TURNER           1500         0
      7876  ADAMS            1100         100
      7900  JAMES             950         100
      7902  FORD             3000         100
      7934  MILLER           1300         100

SQL> SELECT EMPNO, ENAME, SAL, NVL (COMM, 888) FROM EMP

     EMPNO  ENAME         SAL  NVL(COMM,888)
---------- ---------- ---------- -------------
      7369  SMITH          800           888
      7499  ALLEN         1600           300
      7521  WARD          1250           500
      7566  JONES          2975           888
      7654  MARTIN      1250          1400
      7698  BLAKE         2850           888
      7782  CLARK         2450           888
      7788  SCOTT          3000           888
      7839  KING             5000           888
      7844  TURNER      1500             0
      7876 ADAMS         1100           888
      7900  JAMES          950           888
      7902  FORD            3000           888
      7934  MILLER       1300           888

In above queries we have seen how to substitute a value when the comm is null.
If one want to display "Commission not payed" against the employees who have no
commission we can write the following query.







SQL > SELECT ENAME, SAL, NVL(TO_CHAR(COMM),'Commission Not Payed') FROM EMP;
ENAME             SAL  NVL(TO_CHAR(COMM),'COMMISSIONNOTPAYED')
---------- ---------- ----------------------------------------
SMITH             800  Commission Not Payed
ALLEN            1600  300
WARD             1250  500
JONES             2975  Commission Not Payed
MARTIN         1250  1400
BLAKE            2850  Commission Not Payed
CLARK            2450  Commission Not Payed
SCOTT             3000  Commission Not Payed
KING                5000  Commission Not Payed
TURNER          1500  0
ADAMS           1100  Commission Not Payed
JAMES             950  Commission Not Payed
FORD               3000  Commission Not Payed
MILLER           1300  Commission Not Payed


2 comments:

  1. I suspect she'll be dieting for beginners even when she says she is not competing which tells me that she has never seen fail: limit yourself to one. If you have a child that is overweight, the following tips should help you avoid the temptation of getting something like fast food. It will not be posting every tiny food morsel here but I will be posting my calorie intake daily.

    Feel free to visit my weblog; mountain bike rack - -

    ReplyDelete
  2. The reason is that the healthiest nutrition that consists of nutrition from all food groups is the top eating habits for everybody.
    Once you know those foods that are low on the gylcemic index
    and 15 grams of carbs per serving. Low carb veg dieting by blood type gave me
    my life back. Cookie dieting by blood type is a cure all for
    obesity. Modern conveniences make it very easy to gain weight and you will
    see the positive results soon. Why not diet and treat your gout naturally guaranteed!


    Also visit my page: construction take off software

    ReplyDelete

Write your openion about my blog spot..To get automatic facebook updates like my Pagehttps://www.facebook.com/shivashankar4u ..It takes only 1 min to write the comment and to like the page.. Thanks.