SQL FUNCTIONS


The data in database are the basis of critical business information. Generating information from data often requires many data manipulations. Sometimes such data manipulation involves the decomposition of data elements.
            SQL functions are very useful tools. There are many types of SQL functions, such as arithmetic, trigonometric, string, date, and time functions.

NOTE: DUAL is oracles pseudo table used only for case where a table is not really needed

·         SYSDATE: Returns today’s date.

            SQL> select sysdate
            2       from dual;

SYSDATE
--------------
04-MAR-12

·         ADD_MONTHS: Returns date after adding the number of months specified in the function.
Syntax:  ADD_MONTHS(DATE_VALUE,N)

SQL> select add_months(sysdate,4)
  2      from dual;                 

ADD_MONTH
------------------
04-JUL-12
SQL> select add_months(sysdate,4)"addmonths"
  2     from dual;

addmonths
-------------
04-JUL-12
SQL> select add_months(sysdate,4) as addmonths
  2     from dual;

ADDMONTHS
-----------------
04-JUL-12

·         LAST_DAY: Returns the date of the last day of the month given in a date.
Syntax: LAST_DAY(DATE_VALUE)
SQL> select sysdate,last_day(sysdate)"lastday"
  2  from dual;

SYSDATE      lastday
--------------    ------------
04-MAR-12    31-MAR-12
NUMERIC FUNCTIONS:
      Numeric functions can be grouped in many different ways, such as algebraic, trigonometric and logarithmic. The following are selected group of numeric functions.

·         ABS: Returns the absolute value of a number
Syntax: ABS(NUMERIC_VALUE)

SQL> select 1.93,-1.93, abs (1.93), abs (-1.93)
  2     from dual;

      1.93      -1.93     ABS (1.93)    ABS (-1.93)
  ----------- ----------- -------------    -------------
      1.93      -1.93       1.93             1.93

·         POWER:  Returns m raised to the nth power. n must be an integer, else an error is returned .
Syntax: POWER(m,n)
Eg. Find 52
 SQL> select power(5,2)
  2       from dual;

POWER(5,2)
---------------
        25

·         ROUND:  Returns n, rounded to m places to the right of a decimal point. If m is omitted , n is rounded to zero places
Syntax: ROUND(n,m)

SQL> select round(15.193,1)
  2     from dual;
ROUND(15.193,1)
---------------------
           15.2
SQL> select round(15.193)
  2      from dual;

ROUND(15.193)
-------------------
           15

·         SQRT: Returns square root of n.
Syntax: SQRT(n)
Eg. Find the square root of 625
SQL> select sqrt(625)
  2    from dual;

 SQRT(625)
--------------
        25
·         MOD: Returns the remainder of a first number divided by second number passed a parameter. If the second number is zero, the result is the same as the first number.
            Syntax: MOD(m,n)
Eg. Find 15 mod 4

            SQL> select mod(15,4)
            2       from dual;

 MOD(15,4)
-------------
                         3
·         FLOOR: Returns the largest integer value that is equal to or less than a number.
Syntax: FLOOR(n)
Eg. Find floor(24.8)

SQL> select floor(24.8)
  2     from dual;

FLOOR(24.8)
---------------
         24
·         CEIL: Returns the smallest integer value that is greater than or equal to a number
Syntax: CEIL(n)
Eg. Find ceil(24.8)

SQL> select ceil(24.8)
  2      from dual;

CEIL(24.8)
-------------
        25


STRING FUNCTIONS:

·         CONCATENATION:  (||) Concatenates data from two different character columns and returns a single column

·         LOWER: Returns char , with all letters in lower case.
Syntax: LOWER(char)

SQL> select lower('KNREDDY') as lower
  2     from dual;

LOWER
----------
knreddy


·         INITCAP: returns a string with the first letter of each word in upper case
Syntax: INITCAP(char)

SQL> select initcap('nageswarareddy') as initcap
  2     from dual;

INITCAP
--------------
Nageswarareddy

·         UPPER: Returns a string with all letters forced to upper
Syntax: UPPER(char)

SQL> select upper('knreddy') as upper
  2      from dual;

UPPER
-----------
KNREDDY

·         SUBSTR: Returns a portion of characters, beginning at character m, and going upto characters n. If n is omitted, the result returned is upto the last character in the string. The first position of character is 1.

Syntax: SUBSTR(<string>,<startposition>,<length>)

Where        string   - source string
                  Start position – position for extraction
      Length – number of characters to extract

SQL> select substr('databasemanagementsystems',5,4)
  2      from dual;

SUBS
--------
base

SQL> select substr('databasemanagementsystems',5)  as substr
  2      from dual;

SUBSTR
------------------------------------
basemanagementsystems

·         ASCII: Returns the number code that represents the specified character. If more than one character is entered , the function will return the value for the first character and ignore all of the characters after the first.
Syntax: ASCII(<single- character>)

SQL> select ascii('a')
  2     from dual;

ASCII('A')
----------
        97

SQL> select ascii('A')
  2     from dual;

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

SQL> select ascii('APPLE')
  2     from dual;

ASCII('APPLE')
-----------------
            65

·         LENGTH: Returns the length of a word
Syntax: LENGTH(word)

SQL> select length('database')
  2     from dual;

LENGTH('DATABASE')
-----------------------------
                 8

SQL> select length('data base')
  2     from dual;

LENGTH('DATABASE')
----------------------------
                 9
·         LTRIM: Removes characters from the left of character with initial characters removed upto the first character not in set.
Syntax: LTRIM(char,set)

SQL> select ltrim('dbms','d')
  2     from dual;

LTR
-----
bms


SQL> select ltrim('ddddbms','d')
  2      from dual;

LTR
------
bms

SQL> select ltrim('dbms','d''b')
  2     from dual;

LT
---
ms

·         RTRIM: Returns char, eith final characters removed after the last character not in the set.
Syntax: RTRIM(char,set)

SQL> select rtrim('dbms','s')
  2    from dual;

RTR
-----
dbm

SQL> select rtrim('dbms','s''m')
  2     from dual;

RT
---
Db

·         TRIM: Removes all specified characters either from the beginning or the ending of a string
Syntax: TRIM([leading|trailing|both{<trim-characters> from]] <string>)
Where leading       -remove trim string from the front of the string
          Trailing        -remove trim string from end of string
          Both                        -remove trim string from the front and end of string
If none of the above option is chosen, the TRIM function will remove trim string from both the front and end of string.
      Trim_character is the character that will be removed from string. If this parameter is omitted, the trim function will remove all leading and trailing spaces from string
       String             - string to trim      

SQL> select trim('    dbms    ')
  2      from dual;

TRIM
-------
dbms

SQL> select trim(leading 'x' from 'xxxxxdbmsxxxxx') as leading
  2      from dual;

LEADING
---------------
dbmsxxxxx

SQL> select trim(trailing 'x' from 'xxxxxdbmsxxxxx') as trailing
  2      from dual;

TRAILING
--------------
xxxxxdbms

SQL> select trim(both 'x' from 'xxxxxdbmsxxxxx')
  2     from dual;

TRIM
-------
dbms

SQL> select trim(both '1' from '1123dbms2311') as both
  2      from dual;

BOTH
------------
23dbms23

·         LPAD: Return char-1 left padded to length n with the sequence of characters specified in char-2. If char-2 is not specified oracle uses blanks by default
Syntax: LPAD(char-1,n,char-2)

SQL> select lpad('dbms',15,'@') as lpad
  2     from dual;

LPAD
----------------------------------
@@@@@@@@@@@dbms
·         RPAD: Return char-1 right padded to length n with the sequence of characters specified in char-2. If char-2 is not specified oracle uses blanks by default
Syntax: LPAD(char-1,n,char-2)

SQL> select rpad('dbms',15,'@') as rpad
  2      from dual;

RPAD
-----------------------------------
dbms@@@@@@@@@@@

EXERCICISE


Consider the following relational schema & instances:

Sailors (sid: integer, sname: string, rating: integer, age: real)

Boats (bid: integer, bname: string)

Reserves (sid: integer, bid: integer, day: date)

SAILORS                                                                               RESERVES
                                                                                   
sid
sname
rating
age
22
dinesh
7
45.0
29
bramha
1
33.0
31
lokesh
8
55.5
32
akash
8
25.5
58
 ramesh
10
35.0
64
hari
7
35.0
71
Mahesh
10
16.0
74
hari
9
35.0
85
abhi
3
25.5
95
boby
3
63.5
sid
bid
day
22
101
10-oct-98
22
102
10-oct-98
22
103
10-oct-98
22
104
10-jul-98
31
102
11-oct-98
31
103
11-jun-98
31
104
11-dec-98
64
101
9-may-98
64
102
9-aug-98
74
103
9-aug-98
             




















BOATS
bid
bname
color
101
interlake
blue
102
interlake
red
103
clipper
green
104
marine
red








Write the SQL queries and their corresponding results for the following:

1.      Find the names and ages of all sailors
2.      Find all sailors with a rating above 7
3.      Find the names of sailors who have reserved boat number 103
4.      Find the sid’s of sailors who have reserved a red boat
5.      Find the names of sailors who have reserved a red boat
6.      Find the colors of boats reserved by lokesh
7.      Find the names of sailors who have reserved at least one boat
8.      Find the name and age of sailors whose name begin with ‘b’ and ends with ‘y’ and has at least three characters.

UNION, INTERSECT, MINUS
9.      Find the names of sailors who have reserved a red or a green boat
10.  Find the names of sailors who have reserved both a red and a green boat
11.  Find the sid’s of all sailors who have reserved red boats but not green boats
12.  Find all sid’s of sailors who have a rating of 10 or reserved boat 104

NESTED QUERIES:

13.  Find the names of sailors who have reserved boat 103
14.  Find the names of sailors who have reserved a red boat
CORRELATED NESTED QUERIES:

15.  Find the names of sailors who have reserved boat number 103

SET COMPARISON OPERATORS:

16.  Find sailors whose rating is better than some sailor called hari
17.  Find the sailor with the highest rating
18.  Find the name of sailors who have reserved both a red and a green boat
19.  Find the names of sailors who have reserved all boats

AGGREGATE OPERATORS:

20.  Find the average age of sailors with a rating of 10
21.  Find the name  and age of the oldest sailor
22.  Count the number of sailors
23.  Count the number of different sailor names
24.  Find the names of sailors who are older than the oldest sailor with a rating of 10

GROUP BY CLAUSE:

25.  Find the age of the youngest sailor for each rating level
26.  Find the age of the youngest sailor who is eligible to vote(i.e., is at least 18 years old) for each rating level with at least two such sailors
27.  For each red boat find the number of reservations for this boat
28.  Find the average age of sailors for each rating level that has at least two sailors

1.      Find the names and ages of all sailors
SQL> select s.sname,s.age
  2     from sailors s;
SNAME                      AGE
---------------   ------------------         
dinesh                                45
bramha                                          33
lokesh                                55.5
akash                                 25.5
ramesh                               35
hari                                    35
mahesh                              16
hari                                    35
abhi                                   25.5
boby                                  63.5

10 rows selected.
The same query with DISTINCT clause results different.
SQL> select distinct s.sname, s.age
  2      from sailors s;
SNAME                  AGE
---------------    ------------
mahesh                      16
boby                         63.5
abhi                            25.5
bramha                                 33
ramesh                     35
hari                          35
akash                       25.5
dinesh                      45
lokesh                      55.5

9 rows selected.
2.      Find all sailors with a rating above 7
SQL> select *
  2     from sailors;
       SID   SNAME       RATING        AGE
---------- --------------- ------------- ----------
        22      dinesh                          7           45
        29      bramha                        1          33
        31      lokesh                          8           55.5
        32      akash                           8           25.5
        58      ramesh                         10        35
        64      hari                              7          35
        71      mahesh                        10        16
        74      hari                              9          35
        85      abhi                             3           25.5
        95      boby                            3           63.5
10 rows selected.
3.      Find the names of sailors who have reserved boat number 103
SQL> select s.sname
  2     from sailors s, reserves r
  3     where s.sid=r.sid and r.bid=103;

SNAME
---------------
dinesh
lokesh
hari

4.      Find the sid’s of sailors who have reserved a red boat
SQL> select r.sid
  2      from boats b, reserves r
  3      where b.bid=r.bid and b.color='red';

       SID
----------
        22
        22
        31
        31
        64

5.      Find the names of sailors who have reserved a red boat
SQL> select s.sname
  2      from sailors s, reserves r, boats b
  3      where s.sid=r.sid and r.bid =b.bid and b.color='red';

SNAME
---------------
dinesh
dinesh
lokesh
lokesh
hari

6.      Find the colors of boats reserved by lokesh
SQL> select b.color
  2     from sailors s, reserves r, boats b
  3     where s.sid=r.sid and r.bid =b.bid and s.sname='lokesh';

COLOR
------
red
green
red


7.      Find the names of sailors who have reserved at least one boat
SQL> select s.sname
  2     from sailors s, reserves r
  3     where s.sid=r.sid;

SNAME
---------------
dinesh
dinesh
dinesh
dinesh
lokesh
lokesh
lokesh
hari
hari
hari

10 rows selected.

8.      Find the name and age of sailors whose name begin with ‘b’ and ends with ‘y’ and has at least three characters.
SQL> select s.sname, s.age
  2     from sailors s
  3     where s.sname like 'b_%y';

SNAME               AGE
---------------     ----------
boby                        63.5

UNION, INTERSECT, MINUS
9.      Find the names of sailors who have reserved a red or a green boat
SQL> select s.sname
  2     from sailors s, reserves r, boats b
  3     where s.sid=r.sid and r.bid=b.bid and b.color='red'
  4     union
  5     select s2.sname
  6     from sailors s2, reserves r2, boats b2
  7     where s2.sid=r2.sid and r2.bid=b2.bid and b2.color='green';

SNAME
---------------
dinesh
hari
lokesh




10.  Find the names of sailors who have reserved both a red and a green boat

SQL> select s.sname
  2     from sailors s, reserves r, boats b
  3     where s.sid=r.sid and r.bid=b.bid and b.color='red'
  4     intersect
  5     select s2.sname
  6     from sailors s2, reserves r2, boats b2
  7     where s2.sid=r2.sid and r2.bid=b2.bid and b2.color='green';

SNAME
---------------
dinesh
hari
lokesh


11.  Find the sid’s of all sailors who have reserved red boats but not green boats

SQL> select s.sid
  2      from sailors s, reserves r,boats b
  3      where s.sid=r.sid and r.bid=b.bid and b.color='red'
  4      minus
  5      select s2.sid
  6      from sailors s2, reserves r2,boats b2
  7      where s2.sid=r2.sid and r2.bid=b2.bid and b2.color='green';

       SID
----------
        64

12.  Find all sid’s of sailors who have a rating of 10 or reserved boat 104

SQL> select s.sid
  2      from sailors s
  3      where s.rating=10
  4      union
  5      select r.sid
  6     from reserves r
  7     where r.bid=104;

       SID
----------
        22
        31
        58
        71


NESTED QUERIES:

13.  Find the names of sailors who have reserved boat 103

SQL> select s.sname
  2     from sailors s
  3     where s.sid in (  select r.sid
  4                             from reserves r
  5                             where r.bid=103);

SNAME
---------------
dinesh
lokesh
hari

14.  Find the names of sailors who have reserved a red boat

SQL> select s.sname
  2      from sailors s
  3      where s.sid in ( select r.sid
  4                            from reserves r
  5                            where r.bid in (select b.bid
  6                                                  from boats b
  7                                                  where b.color='red'));

SNAME
---------------
dinesh
lokesh
hari



15.  Find the names of sailors who have reserved boat number 103

SQL> select s.sname
  2     from sailors s
  3     where exists ( select *
  4                         from reserves r
  5                         where r.bid=103 and r.sid=s.sid);

SNAME
---------------
dinesh
lokesh
hari


16.  Find sailors whose rating is better than some sailor called hari

SQL> select s.sid
  2      from sailors s
  3      where s.rating >any (select s2.rating
  4                                    from sailors s2
  5                                    where s2.sname='hari');

       SID
----------
        58
        71
        74
        31
        32

17.  Find the sailor with the highest rating


SQL> select s.sid
  2     from sailors s
  3     where s.rating>=all(select s2.rating
  4                                 from sailors s2)

       SID
----------
        58
        71

18.  Find the name of sailors who have reserved both a red and a green boat

SQL> select s.sname
  2      from sailors s, reserves r,boats b
  3      where s.sid=r.sid and r.bid=b.bid and b.color='red'
  4          and s.sid in( select s2.sid
  5                       from sailors s2,boats b2,reserves r2
  6                       where s2.sid=r2.sid and r2.bid=b2.bid and b2.color='green');

SNAME
---------------
dinesh
dinesh
lokesh
lokesh



19.  Find the names of sailors who have reserved all boats

SQL> select s.sname
  2      from sailors s
  3     where not exists(select b.bid
  4                             from boats b
  5                             where not exists(select r.bid
  6                                                     from reserves r
  7                                                      where r.bid=b.bid and r.sid=s.sid));

SNAME
---------------
dinesh


20.  Find the average age of sailors with a rating of 10
SQL> select avg(s.age)
  2     from sailors s
  3     where s.rating=10;

AVG(S.AGE)
----------
      25.5
21.  Find the name  and age of the oldest sailor
SQL> select s.sname,s.age
  2     from sailors s
  3     where s.age=(select max(s2.age)
  4                        from sailors s2);

SNAME                  AGE
--------------- --------------
boby                       63.5

22.  Count the number of sailors
SQL> select count(*)
  2      from sailors s;

  COUNT(*)
--------------
        10

23.  Count the number of different sailor names
SQL> select count(distinct s.sname)
  2      from sailors s;

COUNT(DISTINCTS.SNAME)
-----------------------------------
                     9
24.  Find the names of sailors who are older than the oldest sailor with a rating of 10

SQL> select s.sname
  2     from sailors s
  3     where s.age>(select max(s2.age)
  4                         from sailors s2
  5                         where s2.rating=10);

                              (or)
SQL> select s.sname
  2     from sailors s
  3     where s.age> all (select s2.age
  4                              from sailors s2
  5                              where s2.rating=10);

SNAME
---------------
dinesh
lokesh
boby


25.  Find the age of the youngest sailor for each rating level
SQL> select s.rating, min(s.age)
  2     from sailors s
  3      group by s.rating;

    RATING MIN(S.AGE)
---------- -----------------
         1                  33
         8                   25.5
         7                   35
         3                   25.5
        10                  16
         9                   35

6 rows selected.

26.  Find the age of the youngest sailor who is eligible to vote(i.e., is at least 18 years old) for each rating level with at least two such sailors


SQL>select s.rating,min(s.age) as minimumage
  2    from sailors s
  3    where s.age>=18
  4    group by s.rating
  5     having count(*)>1

    RATING MINIMUMAGE
------------- --------------------
         8                   25.5
         7                   35
         3                   25.5

27.  For each red boat find the number of reservations for this boat

SQL> select b.bid,count(*) as reservationcount
  2      from boats b,reserves r
  3      where r.bid=b.bid and b.color='red'
  4      group by b.bid;

       BID RESERVATIONCOUNT
---------- ----------------------------
       102                3
       104                2

28.  Find the average age of sailors for each rating level that has at least two sailors

SQL> select s.rating, avg(s.age) as average
  2     from sailors s
  3     group by s.rating
  4     having count(*)>1;

    RATING    AVERAGE
-------------- ---------------
             8               40.5
             7               40
             3               44.5
            10              25.5