Oracle Sql Part3

Welcome To Tripathi SQL Page

DATE FUNCTIONS
 Oracle default date format is DD-MON-YY.
We can change the default format to our desired format by using the following command.

SQL> alter session set nls_date_format = ‘DD-MONTH-YYYY’;
        But this will expire once the session was closed.

a) SYSDATE

     This will give the current date and time.
      Ex:
           SQL> select sysdate from dual;

SYSDATE
-----------
24-DEC-06

b) CURRENT_DATE
     This will returns the current date in the session’s timezone.
      Ex:
           SQL> select current_date from dual;
CURRENT_DATE
------------------
     24-DEC-06

c) CURRENT_TIMESTAMP

     This will returns the current timestamp with the active time zone information.
      Ex:
           SQL> select current_timestamp from dual;

CURRENT_TIMESTAMP
---------------------------------------------------------------------------
24-DEC-06 03.42.41.383369 AM +05:30


d) SYSTIMESTAMP

     This will returns the system date, including fractional seconds and time zone of the
      database.

      Ex:
           SQL> select systimestamp from dual;
SYSTIMESTAMP
---------------------------------------------------------------------------
24-DEC-06 03.49.31.830099 AM +05:30

e) LOCALTIMESTAMP

     This will returns local timestamp in the active time zone information, with no time
     zone information shown.

      Ex:
                   SQL> select localtimestamp from dual;

LOCALTIMESTAMP
---------------------------------------------------------------------------
24-DEC-06 03.44.18.502874 AM


f) DBTIMEZONE

    This will returns the current database time zone in UTC format. (Coordinated Universal
    Time)

    Ex:
                   SQL> select dbtimezone from dual;

DBTIMEZONE
---------------
   -07:00 

g) SESSIONTIMEZONE

    This will returns the value of the current session’s time zone.

    Ex:
         SQL> select sessiontimezone from dual;

SESSIONTIMEZONE
------------------------------------
+05:30

       
       h) TO_CHAR

    This will be used to extract various date formats.
    The available date formats as follows.

    Syntax: to_char (date, format)

Ex:
    SQL> select to_char(sysdate,'dd month yyyy hh:mi:ss am dy') from dual;

TO_CHAR(SYSDATE,'DD MONTH YYYYHH:MI
----------------------------------------------------
24 december  2006 02:03:23 pm sun     

    SQL> select to_char(sysdate,'dd month year') from dual;


TO_CHAR(SYSDATE,'DDMONTHYEAR')
-------------------------------------------------------
24 december  two thousand six

     SQL> select to_char(sysdate,'dd fmmonth year') from dual;

TO_CHAR(SYSDATE,'DD FMMONTH YEAR')
-------------------------------------------------------
24 december two thousand six

     SQL> select to_char(sysdate,'ddth DDTH') from dual;

TO_CHAR(S
------------
24th 24TH

     SQL> select to_char(sysdate,'ddspth DDSPTH') from dual;

TO_CHAR(SYSDATE,'DDSPTHDDSPTH
------------------------------------------
twenty-fourth TWENTY-FOURTH

     SQL> select to_char(sysdate,'ddsp Ddsp DDSP ') from dual;

TO_CHAR(SYSDATE,'DDSPDDSPDDSP')
------------------------------------------------
twenty-four Twenty-Four TWENTY-FOUR

i) TO_DATE

    This will be used to convert the string into data format.

    Syntax: to_date (date)

    Ex:
         SQL> select to_char(to_date('24/dec/2006','dd/mon/yyyy'), 'dd * month * day')
                 from dual;

TO_CHAR(TO_DATE('24/DEC/20
--------------------------
24 * december  * Sunday

-- If you are not using to_char oracle will display output in default date format.
        
j) ADD_MONTHS

    This will add the specified months to the given date.

    Syntax: add_months (date, no_of_months)

    Ex:
          SQL> select add_months(to_date('11-jan-1990','dd-mon-yyyy'), 5) from dual;

ADD_MONTHS
----------------
11-JUN-90

SQL> select add_months(to_date('11-jan-1990','dd-mon-yyyy'), -5) from dual;

ADD_MONTH
---------------
11-AUG-89          

Ø  If no_of_months is zero then it will display the same date.
Ø  If no_of_months is null then it will display nothing.

k) MONTHS_BETWEEN

    This will give difference of months between two dates.

    Syntax: months_between (date1, date2)

    Ex:
         SQL> select months_between(to_date('11-aug-1990','dd-mon-yyyy'), to_date('11-
                 jan-1990','dd-mon-yyyy')) from dual;



MONTHS_BETWEEN(TO_DATE('11-AUG-1990','DD-MON-YYYY'),TO_DATE('11-JAN-1990','DD-MON-YYYY'))
-----------------------------------------------------------------------------------------
                                                                                        7
           SQL> select months_between(to_date('11-jan-1990','dd-mon-yyyy'), to_date('11-
                 aug-1990','dd-mon-yyyy')) from dual;

MONTHS_BETWEEN(TO_DATE('11-JAN-1990','DD-MON-YYYY'),TO_DATE('11-AUG-1990','DD-MON-YYYY'))
--------------------------------------------------------------------------------------
                                                                                       -7

l) NEXT_DAY
    This will produce next day of the given day from the specified date.
    Syntax: next_day (date,  day)
    Ex:
         SQL> select next_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from dual;

NEXT_DAY(
-------------
31-DEC-06

-- If the day parameter is null then it will display nothing.

m) LAST_DAY

    This will produce last day of the given date.

    Syntax: last_day (date)

    Ex:
         SQL> select last_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from dual;
LAST_DAY(
-------------
31-DEC-06

n) EXTRACT

    This is used to extract a portion of the date value.

    Syntax: extract ((year | month | day | hour | minute | second), date)

    Ex:
         SQL> select extract(year from sysdate) from dual;
EXTRACT(YEARFROMSYSDATE)
------------------------------------
                    2006

-- You can extract only one value at a time.

o) GREATEST

     This will give the greatest date.

     Syntax: greatest (date1, date2, date3 … daten)

     Ex:
         SQL> select greatest(to_date('11-jan-90','dd-mon-yy'),to_date('11-mar-90','dd-
                 mon-yy'),to_date('11-apr-90','dd-mon-yy')) from dual;

  GREATEST(
  -------------
   11-APR-90

p) LEAST

     This will give the least date.
     Syntax: least (date1, date2, date3 … daten)

     Ex:
         SQL> select least(to_date('11-jan-90','dd-mon-yy'),to_date('11-mar-90','dd-mon-
                 yy'),to_date('11-apr-90','dd-mon-yy')) from dual;

  LEAST(
  -------------
   11-JAN-90

q) ROUND

    Round will rounds the date to which it was equal to or greater than the given date.

    Syntax: round (date, (day | month | year))

    If the second parameter was year then round will checks the month of the given date in 
    the following ranges.

JAN      --          JUN     
            JUL       --          DEC

    If the month falls between JAN and JUN then it returns the first day of the current year.
    If the month falls between JUL and DEC then it returns the first day of the next year.

    If the second parameter was month then round will checks the day of the given date in
    the following ranges.

            1          --         15       
            16        --         31

    If the day falls between 1 and 15 then it returns the first day of the current month.
    If the day falls between 16 and 31 then it returns the first day of the next month.

    If the second parameter was day then round will checks the week day of the given date
    in the following ranges.

            SUN      --          WED
            THU      --          SUN

    If the week day falls between SUN and WED then it returns the previous sunday.
    If the weekday falls between THU and SUN then it returns the next sunday.

Ø  If the second parameter was null then it returns nothing.
         SQL> select round(to_date('24-dec-04','dd-mon-yy'),'year'), round(to_date('11-mar-
                 06','dd-mon-yy'),'year') from dual;

ROUND(TO_ ROUND(TO_
------------   ---------------
01-JAN-05   01-JAN-06

           SQL> select round(to_date('11-jan-04','dd-mon-yy'),'month'), round(to_date('18-
                 jan-04','dd-mon-yy'),'month') from dual;  

ROUND(TO_ ROUND(TO_
-------------  ---------------
01-JAN-04    01-FEB-04

           SQL> select round(to_date('26-dec-06','dd-mon-yy'),'day'), round(to_date('29-dec-
                 06','dd-mon-yy'),'day') from dual;
  
ROUND(TO_ ROUND(TO_
--------------  --------------
24-DEC-06     31-DEC-06

           SQL> select to_char(round(to_date('24-dec-06','dd-mon-yy')), 'dd mon yyyy
                 hh:mi:ss am') from dual;
TO_CHAR(ROUND(TO_DATE('
---------------------------------
24 dec 2006 12:00:00 am
r) TRUNC

    Trunc will chops off the date to which it was equal to or less than the given date.

    Syntax: trunc (date, (day | month | year))

Ø  If the second parameter was year then it always returns the first day of the current year.
Ø  If the second parameter was month then it always returns the first day of the current month
    Ex:
         SQL> select trunc(to_date('24-dec-04','dd-mon-yy'),'year'), trunc(to_date('11-mar-
                 06','dd-mon-yy'),'year') from dual;

TRUNC(TO_ TRUNC(TO_
-------------  --------------
01-JAN-04    01-JAN-06

                     SQL> select trunc(to_date('11-jan-04','dd-mon-yy'),'month'), trunc(to_date('18-jan-
                         04','dd-mon-yy'),'month') from dual;

TRUNC(TO_ TRUNC(TO_
-------------  -------------
01-JAN-04    01-JAN-04
  
  SQL> select trunc(to_date('26-dec-06','dd-mon-yy'),'day'), trunc(to_date('29-dec-
          06','dd-mon-yy'),'day') from dual;
                        TRUNC(TO_ TRUNC(TO_
-------------  --------------
24-DEC-06 24-DEC-06
         
          SQL> select to_char(trunc(to_date('24-dec-06','dd-mon-yy')), 'dd mon yyyy hh:mi:ss
                 am') from dual;

TO_CHAR(TRUNC(TO_DATE('
---------------------------------
24 dec 2006 12:00:00 am

s) NEW_TIME

     This will give the desired timezone’s date and time.

     Syntax: new_time (date, current_timezone, desired_timezone)

     Available timezones are as follows.
    Ex:
        SQL> select to_char(new_time(sysdate,'gmt','yst'),'dd mon yyyy hh:mi:ss am') from
                dual;

TO_CHAR(NEW_TIME(SYSDAT
-----------------------------------
24 dec 2006 02:51:20 pm

          SQL> select to_char(new_time(sysdate,'gmt','est'),'dd mon yyyy hh:mi:ss am') from
                dual;

TO_CHAR(NEW_TIME(SYSDAT
-----------------------
24 dec 2006 06:51:26 pm

t) COALESCE

    This will give the first non-null date.

    Syntax: coalesce (date1, date2, date3 … daten)

    Ex:
         SQL> select coalesce('12-jan-90','13-jan-99'), coalesce(null,'12-jan-90','23-mar-
                 98',null) from dual;

COALESCE( COALESCE(
-------------  ------------
12-jan-90     12-jan-90

MISCELLANEOUS FUNCTIONS

Ø  Uid
Ø  User
Ø  Vsize
Ø  Rank
Ø  Dense_rank

a) UID

     This will returns the integer value corresponding to the user currently logged in.

     Ex:
          SQL> select uid from dual;

       UID
----------
       319

b) USER

     This will returns the login’s user name.

     Ex:
           SQL> select user from dual;

USER
----------------
SAKETH

c) VSIZE

     This will returns the number of bytes in the expression.

     Ex:
          SQL> select vsize(123), vsize('computer'), vsize('12-jan-90') from dual;

VSIZE(123) VSIZE('COMPUTER') VSIZE('12-JAN-90')
-------------  -----------------------  ----------------------
         3                         8                                  9

d) RANK

     This will give the non-sequential ranking.

     Ex:
          SQL> select rownum,sal from (select sal from emp order by sal desc);
    ROWNUM    SAL
    ---------- ----------
         1       5000
         2       3000
         3       3000
         4       2975
         5       2850
     

     SQL> select rank(2975) within group(order by sal desc) from emp;

RANK(2975)WITHINGROUP(ORDERBYSALDESC)
---------------------------------------------------------
                                    4

d) DENSE_RANK

     This will give the sequential ranking.
    
Ex:
     SQL> select dense_rank(2975) within group(order by sal desc) from emp;

DENSE_RANK(2975)WITHINGROUP(ORDERBYSALDESC)
-----------------------------------------------------------------
                                          3

CONVERSION FUNCTIONS

a) BIN_TO_NUM

     This will convert the binary value to its numerical equivalent.

     Syntax: bin_to_num( binary_bits)

     Ex:
          SQL> select bin_to_num(1,1,0) from dual;

BIN_TO_NUM(1,1,0)
------------------------
                6

Ø  If all the bits are zero then it produces zero.
Ø  If all the bits are null then it produces an error.

b) CHARTOROWID

     This will convert a character string to act like an internal oracle row identifier or rowid.

c) ROWIDTOCHAR

    This will convert an internal oracle row identifier or rowid to character string.

d) TO_NUMBER

    This will convert a char or varchar to number.

e) TO_CHAR

    This will convert a number or date to character string.

f) TO_DATE

    This will convert a number, char or varchar to a date.
ROLLUP GROUPING CUBE

These are the enhancements to the group by feature.

USING ROLLUP

This will give the salaries in each department in each job category along wih the total salary for individual departments and the total salary of all the departments.

SQL> Select deptno,job,sum(sal) from emp group by rollup(deptno,job);

                        DEPTNO   JOB         SUM(SAL)
----------  ---------   ----------
        10    CLERK  

USING GROUPING

 In the above query it will give the total salary of the individual departments but with a  
 blank in the job column and gives the total salary of all the departments with blanks in
 deptno and job columns.

 To replace these blanks with your desired string grouping will be used

  SQL> select decode(grouping(deptno),1,'All Depts',deptno),decode(grouping(job),1,'All            
          jobs',job),sum(sal) from emp group by rollup(deptno,job);

DECODE(GROUPING(DEPTNO),1,'ALLDEPTS',DEP DECODE(GR   SUM(SAL)
-----------------------------------  ----------------------------------    --------------
10                                                        CLERK             1300
10                                                         MANAGER                 2450
bs                    29025

   Grouping will return 1 if the column which is specified in the grouping function has been
   used in rollup.
   Grouping will be used in association with decode.
USING CUBE
This will give the salaries in each department in each job category, the total salary for individual departments, the total salary of all the departments and the salaries in each job category.

SQL> select decode(grouping(deptno),1,’All Depts’,deptno),decode(grouping(job),1,’All 
        Jobs’,job),sum(sal) from emp group by cube(deptno,job);

DECODE(GROUPING(DEPTNO),1,'ALLDEPTS',DEP DECODE(GR   SUM(SAL)
-----------------------------------  ------------------------------------  ------------
10                                            CLERK                         1300
10                                            MANAGER                              2450

       VIEWS
A view is a database object that is a logical representation of a table. It is delivered from a table but has no storage of its own and often may be used in the same manner as a table.
A view takes the output of the query and treats it as a table, therefore a view can be thought of as a stored query or a virtual table.

TYPES
Ø  Simple view
Ø  Complex view

VIEWS WITH DML
Ø  View with not null column  --  insert with out not null column not possible
                                                        --  update not null column to null is not possible
                                                             --  delete possible
Ø  View with out not null column which was in base table -- insert not possible
                                                                                                     -- update, delete possible
Ø  View with expression -- insert , update not possible
                                               -- delete possibles)
CREATING VIEW WITHOUT HAVING THE BASE TABLE
SQL> Create force view stud as select *From student;
       -- Once the base table was created then the view is validated.
VIEW WITH CHECK OPTION CONSTRAINT
SQL> Create view stud as select *from student where marks = 500 with check option
         constraint Ck;
       - Insert possible with marks value as 500
       - Update possible excluding marks column
       - Delete possible
DROPPING VIEWS
SQL> drop view dept_v
SYNONYM AND SEQUENCE
SYNONYM
A synonym is a  database object, which is used as an alias for a table, view or sequence.
TYPES
Ø  Private
Ø  Public
Private synonym is available to the particular user who creates.
Public synonym is created by DBA which is available to all the users
CREATE AND DROP
SQL> create synonym s1 for emp;
SQL> create public synonym s2 for emp;
SQL> drop synonym s1;
SEQUENCE
A sequence is a database object, which can generate unique, sequential integer values.
It can be used to automatically generate primary key or unique key values.
A sequence can be either in an ascending or descending order.
Syntax:
      Create sequence <seq_name> [increment bty n] [start with n] [maxvalue n]
                                  [minvalue n] [cycle/nocycle] [cache/nocache];
By defalult the sequence starts with 1, increments by 1 with minvalue of 1 and with nocycle,  nocache.
Cache option pre-alloocates a set of sequence numbers and retains them in memory for faster access.
Ex:
     SQL> create sequence s;
     SQL> create sequence s increment by 10 start with 100 minvalue 5 maxvalue 200 cycle   
             cache 20;
USING SEQUENCE
SQL> create table student(no number(2),name varchar(10));
SQL> insert into student values(s.nextval, ‘saketh’);

Ø  Initially currval is not defined and nextval is starting value.
Ø  After that nextval and currval are always equal.
CREATING ALPHA-NUMERIC SEQUENCE
SQL> create sequence s start with 111234;
SQL> Insert into student values (s.nextval || translate   
         (s.nextval,’1234567890’,’abcdefghij’));
ALTERING SEQUENCE
We can alter the sequence to perform the following.
Ø  Set or eliminate minvalue or maxvalue.
Ø  Change the increment value.
Ø  Change the number of cached sequence numbers.
Ex:
     SQL> alter sequence s minvalue 5;
     SQL> alter sequence s increment by 2;
     SQL> alter sequence s cache 10;
DROPPING SEQUENCE
SQL> drop sequence s;
JOINS
Ø  The purpose of a join is to combine the data across tables.
Ø  A join is actually performed by the where clause which combines the specified rows of tables.
Ø  If a join involves in more than two tables then oracle joins first two tables based on the joins condition and then compares the result with the next table and so on.
TYPE
Assume that we have the following tables.
SQL> select * from dept;
    DEPTNO DNAME      LOC
     ------ ---------- ----------
        10            mkt        hyd
SQL> select * from emp
       EMPNO   ENAME      JOB       MGR     DEPTNO
      ---------- ---------- ---------- ---------- ----------
       111         saketh     analyst           444         10
       222         sudha     clerk                333         20
EQUI JOIN
A join which contains an ‘=’ operator in the joins condition.
     SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno=d.deptno;
        EMPNO     ENAME      JOB    DNAME      LOC
          ---------- ---------- ---------- ---------- ----------
            111           saketh    analyst    mkt        hy
USING CLAUSE
SQL> select empno,ename,job ,dname,loc from emp e join dept d using(deptno);
          EMPNO     ENAME      JOB    DNAME      LOC
          ---------- ---------- ---------- ---------- ----------
            111           saketh    analyst    mkt        hy      
ON CLAUSE
SQL>  select empno,ename,job,dname,loc from emp e join dept d on(e.deptno=d.deptno);
          EMPNO     ENAME      JOB    DNAME      LOC
          ---------- ---------- ---------- ---------- ----------
            111           saketh    analyst    mkt        hyd        
NON-EQUI JOIN
A join which contains an operator other than ‘=’ in the joins condition.
Ex:
     SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno >
             d.deptno;

          EMPNO     ENAME    JOB      DNAME      LOC
          ---------- ---------- ---------- ---------- ----------
       222    sudha      clerk          mkt        hyd
       444    madhu     engineer   mkt        hy
SELF JOIN
Joining the table itself is called self join.
Ex:
     SQL> select e1.empno,e2.ename,e1.job,e2.deptno from emp e1,emp e2 where
             e1.empno=e2.mgr;

     EMPNO     ENAME    JOB      DEPTNO
     ---------- ---------- ---------- ----------
       111          jagan      analyst         10
       222          madhu      clerk           4      
NATURAL JOIN
Natural join compares all the common columns.
Ex:
     SQL> select empno,ename,job,dname,loc from emp natural join dept;

     EMPNO   ENAME      JOB      DNAME    LOC
    ---------- ---------- ---------- ---------- ----------
       111          saketh     analyst     mkt        hyd      
CROSS JOIN

This will gives the cross produc
     SQL> select empno,ename,job,dname,loc from emp cross join dept;

 EMPNO  ENAME    JOB        DNAME      LOC
---------- ---------- ---------- ---------- ----------
       111     saketh   analyst      mkt        hy
OUTER JOIN

Outer join gives the non-matching records along with matching records.


LEFT OUTER JOIN

This will display the all matching records and the records which are in left hand side table those that are not in right hand side table.

Ex:
     SQL> select empno,ename,job,dname,loc from emp e left outer join dept d
             on(e.deptno=d.deptno);
Or
      SQL> select empno,ename,job,dname,loc from emp e,dept d where
             e.deptno=d.deptno(+);

                             EMPNO     ENAME   JOB       DNAME      LOC
     ---------- ---------- ---------- ---------- ----------

RIGHT OUTER JOIN

This will display the all matching records and the records which are in right hand side table those that are not in left hand side table.

Ex:
     SQL> select empno,ename,job,dname,loc from emp e right outer join dept d
              on(e.deptno=d.deptno);
Or
      SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno(+) =
             d.deptno

     EMPNO    ENAME     JOB      DNAME      LOC
     ---------- ---------- ---------- ---------- ----------
FULL OUTER JOIN

This will display the all matching records and the non-matching records from both tables.

Ex:
     SQL> select empno,ename,job,dname,loc from emp e full outer join dept d
              on(e.deptno=d.deptno);

 EMPNO   ENAME    JOB        DNAME      LO
INNER JOIN
This will display all the records that have matc
Ex:
     SQL> select empno,ename,job,dname,loc from emp inner join dept using(deptno);

     EMPNO     ENAME   JOB        DNAME    LOC
     ---------- ---------- ---------- ---------- ----------


No comments:

Post a Comment