Class Copy of SQL OPERATORS(Chap 5)

Embed Size (px)

Citation preview

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    1/50

    SQL OPERATORS

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    2/50

    A)Arithmetic OperatorsArithmetic operators operate on numeric datatypes.

    Following are the various arithmetic operators in Oracle and how

    to use them.i)+ - Unary operators: Use to represent positive or negative data

    item. For positive items, the + is optional.

    Example:

    1)create table num(no number(4));

    2)insert into num values(17);3)select -no from num;

    4)update num set no=-no;

    5)insert into num values(-17);

    6)update num set no=-no;

    ii)+ Addition: Use to add two data items or expressions.

    Example:

    1)select sal+comm from emp;

    2)Select (sal+100)+(comm+5) from emp;

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    3/50

    iii)- Subtraction: Use to find the difference between

    two data items or expressions.

    Example:1)select sal-comm from emp;

    iv)* Multiplication: Use to multiply two data items or

    expressions.

    Example:

    1)select sal*comm from emp;

    v)/ Division: Use to divide a data item or expression

    with another.

    Example:

    1)select sal/comm from emp;

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    4/50

    Renaming Columns Used with Expression list

    Rename the default output column names with an alias,when required.

    Syntax:

    Select , from

    Example:

    1)select sal+comm Net Salary from emp;

    Renaming Existing Columns

    Syntax:

    Alter table Rename Column To

    Example

    Alter table Emp rename column sal to salary;

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    5/50

    Concatenation Operator The concatenation operator is used to concatenate orjoin

    two character (text) strings. The result ofconcatenation is another character string.

    Ifone of the string is NULL, the result is another string.

    Concatenating a zero-length string ('') with another string

    results in another string. Two vertical bars (||) are used as the concatenation

    operator.

    Examples:

    1)'Oracle10g' || 'Database' results in 'Oracle10gDatabase2)SELECT first_name || ' ' || last_name FROM emp;

    gives the name of the employees in the emp table.

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    6/50

    B)Comparison Operators

    Comparison operators compare two values or

    expressions and give a Boolean result ofTRUE,FALSE or NULL.

    i)= Equality test

    Example:

    SELECT * FROM emp WHERE last_name = 'SCOTT';ii)!=,,^= Inequality test

    Any of the three operators may be used.

    Example:

    SELECT * FROM emp WHERE first_name != 'TIGER';iii)< Less than test

    Example:

    SELECT last_name FROM emp WHERE salary < 2000;

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    7/50

    iv)> Greater thantest

    Example: SELECT first_name, salary FROM emp WHERE salary >

    10000;

    v)=10000;

    vii)[NOT] IN Equal to any member of test.

    If NOT is used,evaluates to TRUE if the value is not in the member list.

    Example:i)SELECT first_name, salary FROM emp WHERE first_name IN ('JOHN,

    'SAM', MARY', 'LEEZA');

    ii)SELECT last_name FROM emp WHERE last_name NOT IN (SELECT

    last_name FROM emp WHERE dept = 10);

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    8/50

    viii)[NOT] BETWEEN a AND b

    TRUE if value greater than or equal to a and less

    than or equal to b. IfNOT is used, the result is the reverse.

    Example:

    1)SELECT last_name FROM emp WHERE salaryBETWEEN 5000 and 10000;

    2)SELECT last_name FROM emp WHERE salary NOTBETWEEN 5000 and 10000;

    ix)[NOT] EXISTS

    TRUE if a subquery returns at least one row.

    FALSE if the value does not exist.

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    9/50

    1)create table branch(bno number(2) primary

    key,name varchar2(20));

    2)select * from branch;

    bno name

    1 mumbai

    2 solapur

    3 sangli

    4 satara

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    10/50

    3) create table emp(eno number(2) primary key,ename

    varchar2(20),city varchar2(20));

    4)select * from emp;eno ename city

    11 shaha mumbai

    12 patil pune13 joshi sangli

    14 shinde satara

    5)SELECT name FROM branch B WHERE NOT EXISTS (SELECTcity FROM emp WHERE city = B.name); o/p-solapur

    6)SELECT name FROM branch B WHERE EXISTS (SELECT city

    FROM emp WHERE city=B.name); o/p-mumbai,sangli, satara

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    11/50

    x)a [NOT] LIKE b

    Used for pattern matching; TRUE if pattern amatches to

    pattern b.

    Wild character % is used to match any string of length zero

    or more characters.

    Wild character _ is used to match any single character.

    Examplei)SELECT last_name FROM emp WHERE last_name NOT LIKE

    'THO%';

    ii)SELECT last_name FROM emp WHERE last_name LIKE '_HOR%';

    xi)IS [NOT] NULL The only operator used to test for NULL values.

    Example:

    SELECT last_name FROM emp WHERE salary IS NULL;

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    12/50

    C)Logical Operators Logical operators are used to combine the results of two comparison conditions

    to produce a single result or to reverse the result of a single comparison.

    i)NOT

    Used to reverse the result.

    Evaluates to TRUE if the operand is FALSE.

    Evaluates to FALSE if the operand is TRUE.

    Returns NULL if the operand is NULL.

    Example:

    SELECT * FROM emp WHERE NOT (salary < 1000);ii)AND

    Evaluates to TRUE if both operands are TRUE.

    Evaluates to FALSE if either operand is FALSE. Otherwise returns NULL.

    Example:

    SELECT * FROM emp WHERE last_name = 'JACOB' AND sal > 5000;iii)OR Evaluates to TRUE if either operand is TRUE.

    Evaluates to FALSE if both operands are FALSE. Otherwise returns NULL.

    Example:SELECT * FROM emp WHERE last_name = 'JACOB' OR last_name = 'THOMAS';

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    13/50

    SQL FUNCTIONS

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    14/50

    Oracle functions serve the purpose ofmanipulating

    data items & returning a result.

    Functions accepts variables or constants &operating on them.

    Such variables or constants are called Arguments.

    Any no. of arguments(or no arguments at all) can bepassed to a function in the following Syntax:

    Function_Name(argument1,argument2,-----)

    Oracle functions can be clubbed together depending

    upon whether they operate on a single row or a

    group of rows retrieved from a table.

    Accordingly functions are classified as follows:

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    15/50

    A)Group Functions(Aggregate functions)

    Functions that act on a set of values are called asGroup functions.

    E.g.,AVG, is a function ,which calculates the averageof set of numbers.

    A group function returns a single result row for agroup of queried rows.

    B)Scalar Functions(Single Row Functions)

    Functions that act on only one value at a time arecalled Scalar Functions.

    E.g.Length, is a function,which calculates the lengthof one particular string value.

    A single row function returns one result for everyrow of a table.

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    16/50

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    17/50

    A)Group Functions(Aggregate functions)

    i)Avg:Returns an average value of n,ignoring null

    values in a column.Syntax:

    Avg([|] )

    Example:

    Select Avg(balance) Average Balance from acct_mstr;

    ii)Min:Returns a minimum value of expression.

    Syntax:

    Min([|] )Example:

    Select Min(balance) Minimum Balance fromacct_mstr;

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    18/50

    iii)Max:Returns a maximum value of expression.

    Syntax:

    Max([|] )Example:

    Select Max(balance) Maximum Balance fromacct_mstr;

    iv)Count(expr):Returns the no. of rows where expr is

    not null.

    Syntax:

    Count([|] )Example:

    Select Count(Acc_no) No. of Accounts from

    acct_mstr;

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    19/50

    v)Count(*):Returns the no. of rows in the table,

    including duplicates & those with nulls.

    Syntax:

    Count(*)

    Example:

    Select Count(*) No. of records from acct_mstr;

    vi)Sum:Returns the sum of values of n.

    Syntax:

    Sum([|] )

    Example:

    Select Sum(balance) Total Balance from acct_mstr;

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    20/50

    B)Scalar Functions (Single Row Functions)

    a)Numeric Functions

    i)ABS:Returns an absolute value of n.

    Syntax:ABS(n)

    Example:

    Select Abs(-7) Absolute numbers from Num; o/p 7

    ii)Power(m,n):Returns m raised to the nth

    power.n must be aninteger,else an error is returned.

    Syntax:

    Power(m,n)

    Example:

    1)Select power(3,2) Raised from Dual; o/p-9

    2)Select power(0,9) "Raised" from Dual; o/p-0

    3)Select power(9,0) "Raised" from Dual; o/p-1

    4)Select power(3,-2) "Raised" from Dual;o/p-0.1111111111--------

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    21/50

    Note: DUAL is a dummy table available to all users in the

    database.

    The DUAL table is used to select system variables orto evaluate an expression.

    SELECT SYSDATE, USER FROM DUAL;

    will show the current system date and theconnected username.

    Dual consists of exactly one column whose name isdummy and one record.

    The value of that record is X. The dual table is used in Oracle when you need to

    run SQL that does not logically have a table name.

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    22/50

    iii)Round:Returns n,rounded to m places to the right of a

    decimal point.Ifm is omitted,n is rounded to 0

    places. m can be negative to round off digits to theleft of the decimal point. m must be an integer.

    Syntax:

    Round(n,[m])

    Example:1)Select Round(15.19,1) round from dual; o/p-15.2

    2)Select Round(15.19,3) "round" from dual; o/p-15.19

    3)Select Round(1846.19,-2) "round" from dual; o/p-1800

    4)Select Round(1856.19,-2) "round" from dual; o/p-19005)Select Round(1846.19,-3) "round" from dual; o/p-2000

    6)Select Round(1846.19,-4) "round" from dual; o/p-0

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    23/50

    iv)SQRT:Returns square root ofn. error.SQRT

    returns a real result.Ifn

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    24/50

    v)Extract:Returns a value extracted from a date or an intervalvalue.A DATE can be used only to extract YEAR,MONTH &DAY while TIMESTAMP can be used to extract HOUR,

    MINUTE & SECOND.Syntax:

    Extract{YEAR|MONTH|DAY|HOUR|MINUTE|SECOND}

    FROM {DATE_VALUE|INTERVAL_VALUE}

    Example:1) SELECT EXTRACT(YEAR FROM TO_DATE('01-JAN-2005')) AS YEAR FROM dual;

    2) SELECT EXTRACT(MONTH FROM TO_DATE('01-JAN-2005')) AS MONTHFROM dual;

    3) SELECT EXTRACT(DAY FROM TO_DATE('01-JAN-2005')) AS DAY FROM dual;

    4) SELECT EXTRACT(HOUR FROM TO_TIMESTAMP('01-JAN-2005 19:15:26,'DD-

    MON-YYYY HH24:MI:SS')) AS HOUR FROM dual5) SELECT EXTRACT(MINUTE FROM TO_TIMESTAMP('01-JAN-2005 19:15:26',

    'DD- MON-YYYY HH24:MI:SS')) AS MINUTE FROM dual;

    6) SELECT EXTRACT(SECOND FROM TO_TIMESTAMP('01-JAN-2005 19:15:26','DD-MON-YYYY HH24:MI:SS')) AS SECOND FROM dual;

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    25/50

    vi)Greatest:Returns the greatest value in a list of expressions.

    Syntax:

    Greatest(expr1,expr2,-------,expr_n)where,expr1,expr2,----expr_n are expressions that areevaluated by the Greatest function.

    Example:

    SELECT Greatest(3,6,67) greatest num1, Greatest(34,6,1)

    greatest num2 from dual;

    vii)Least:Returns the least value in a list of expressions.Syntax:

    Least(expr1,expr2,-------,expr_n)where,expr1,expr2,----expr_n are expressions that are evaluated bythe Least function.

    Example:SELECT Least(3,6,67) Smallest num1, Least(34,6,1) Smallest

    Num2 from dual;

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    26/50

    Note:In the Least() & Greatest() function if the datatype of the

    expressions are different,all expressions will be converted to

    datatype of first expression.If the comparison is based oncharacter comparison,one character is considered greater thananother based on Ascii value of first character in the expression.

    Example:

    1) SELECT GREATEST('gh','DFG','hj',789) from dual; O/P-hj

    [comparing(103,68,104,55)]2) SELECT GREATEST(789 ,'gh','DFG','hj') from dual; o/p-error

    Because we cannot convert Character into Number

    3) SELECT LEAST('ORACLE','SQL Server','DB2') as Least_Value FROMdual; o/p-DB2 [comparing(79,83,68)

    4) SELECT LEAST('ORACLE',123,345) as Least_Value FROM dual;O/P-123 [comparing(79,49,51)]

    5) SELECT LEAST('a',1,null) as Least_Value FROM dual; o/p-null

    [comparing(97,49,null)]

    Ascii Chart:

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    27/50

    viii)Mod:Returns the remainder of a first number divided by secondnumber passed a parameter.If the second number is zero,the result is the same as the first number.

    Syntax:Mod(m,n)

    Example:1)SELECT Mod(15,7) Mod1, Mod(15.7,7) Mod2 from dual; o/p-1,1.7

    2)SELECT Mod(0,7) "Mod1", Mod(15.7,0) "Mod2" from dual; o/p-0,15.7

    ix)Trunc:Returns a number truncated to a certain number of decimalplaces.The decimal place value must be an integer.If thisparameter is omitted,the Trunc function will truncate thenumber to 0 decimal places.

    Syntax:

    Trunc(number,[decimal_places])Example:1)SELECT Trunc(125.815,1) Trunc1, Trunc(125.815,-2) Trunc2 from dual;

    o/p-125.8, 100

    2) SELECT Trunc(125.815,4) "Trunc1", Trunc(125.815,-3) "Trunc2" from dual;

    o/p-125.815, 0

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    28/50

    x)Ceil:Returns the smallest integer value that is greater than orequal to number.

    Syntax:

    Ceil(n)Example:1)SELECT Ceil(15.7) Ceil1, Ceil(13.15) Ceil2 , Ceil(-1.23) Ceil3 from dual;

    o/p-16 , 14 ,-1

    2)SQL> select * from myTable

    ID VALUE---------- ----------

    1 12.122 -12.123 22.14 2.1

    SQL> SELECT id, value,Ceil(value) FROM myTableID VALUE Ceil(VALUE)

    ---------- ---------- -------------------------1 12.12 132 -12.12 -123 22.1 234 2.1 3

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    29/50

    xi)Floor:Returns the largest integer value that is less than or equal to anumber.

    Syntax:

    Floor(n)Example:1)SELECT Floor(125.8) Floor1, Floor(13.15) Floor2 from dual;

    o/p-125, 13

    2)SQL> select * from myTableID VALUE

    ---------- ----------1 92 2.113 3.444 -4.21

    SQL> SELECT id, value,FLOOR(value) FROM myTable

    ID VALUE FLOOR(VALUE)---------- ---------- -------------------------

    1 9 92 2.11 23 3.44 34 -4.21 -5

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    30/50

    b)String Functions

    i)Lower:Returns char,with all letters in lowercase.

    Syntax:Lower(char)

    Example:

    1)Select Lower(ORACLE) Lower from dual; o/p-oracle

    2)Select Lower(oracle) Lower from dual; o/p-oracleii)Upper:Returns char,with all letters in uppercase.

    Syntax:

    Upper(char)

    Example:

    1)Select Upper(oracle) Upper from dual; o/p- ORACLE

    2)Select Upper(ORACLE) Upper from dual; o/p-ORACLE

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    31/50

    iii)Initcap:Returns a string first letter of each word in Upper case.

    Syntax:

    Initcap(char)

    Example:1)Select Initcap(ORACLE DATABASE ) Title Case from dual;

    o/p-Oracle Database

    iv)Substr:Returns a portion of characters,beginning at character m &

    going upto character n.Ifn is omitted,the result returned is upto

    last character in the string.The first position of char is 1.Syntax:

    Substr(,,[])

    where,string is the source string.

    start_position is the position for extraction.The first position in the

    string is always 1.length is the number of characters to extract.

    Example:

    1)Select Substr(oracle,3,4) substring from dual; o/p- acle

    2)Select Substr(oracledatabase,-5,4) substring from dual; o/p-abas

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    32/50

    v)Ascii:Returns the NUMBER code that represents thespecified character.If more than one character

    is entered,the function will return the value for

    the first character & ignore all of the characters

    after the first.

    Syntax:Ascii()

    where, single_character is the specified character to

    retrieve the NUMBER code for.

    Example:

    1)Select Ascii(a) Ascii1, Ascii(A) Ascii2 from dual;

    o/p-97,65

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    33/50

    vi)Instr:Returns a location of a substring in a string.

    Syntax:

    Instr(,,[],[])

    where,string1 is the string to search.

    string2 is the substring to search for in string1

    start_position is the position in string1 where the search will start. If

    omitted,it defaults to 1.The first position in the string is

    1.If the start_position is negative, the function counts

    back start_position number of characters from the

    end of string1 & then searches towards the beginning

    of string1.

    nth

    _appearance is the nth

    _appearance of string2.If omitted,it defaultsto 1 .

    Example:

    1)Select Instr(Functions accepts variables ,t) Instr1, Instr(Functions accepts

    variables ,t,1,2) Instr2 from dual; o/p- 5,16

    2) Select Instr('Functions accepts variables','s',-10,2) "Instr2" from dual; o/p-9

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    34/50

    vii)Translate:Replaces a sequence of characters in a string,withanother set of characters.However,it replaces a

    single character at a time.e.g.,it will replace the 1st

    character in the string_to_replace with the 1st

    character in the replacement_string.Then it will

    replace the 2nd character in the replacement_string

    & so on.

    Syntax:Translate(,,)

    where,string1 is the string to replace a sequence of characters

    with another set of characters.

    string_to_replace is the string that will be searched for in string1.

    All characters in the string_to_replace will be

    replaced with the corresponding character in the replacement_string.

    Example:

    1)Select Translate(Functions,uts,123) Change from dual;

    o/p- F1nc2ion3

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    35/50

    viii)Length:Returns a length of a word.

    Syntax: Length(word)

    Example: 1)Select Length(oracle) Length from dual; o/p- 6

    ix)Ltrim:Removes a characters from the left of char with initialcharacters removed upto the first character not in set.

    Syntax: Ltrim(char[,set])

    Example:1)Select Ltrim(oracle,o) Ltrim from dual; o/p-racle2)Select Ltrim('ooracle','ora') "Ltrim" from dual; o/p- cle

    3)Select Ltrim('ooracle','orc') "Ltrim" from dual; o/p- acle

    4)Select Ltrim('ooracle','ra') "Ltrim" from dual; o/p- error

    x)Rtrim:Returns char, with final characters removed after the lastcharacter not in set.

    Syntax: Rtrim(char[,set])

    Example:1)Select Rtrim(oracle,el) Rtrim from dual; o/p-orac

    2)Select Rtrim('oracle',lc') Rtrim" from dual; o/p- error

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    36/50

    xi)Trim:Removes all specified characters either from beginning

    or the ending of string.

    Syntax:Trim([leading | trailing | both [ from ]] )

    Where,

    leading-remove trim_string from the front ofstring1.

    trailing-remove trim_string from the end ofstring1.

    both-remove trim_string from the front & end ofstring1.

    Ifnone of the above option is chosen,the Trim function

    will remove trim_string from both the front & end ofstring1.

    Trim_character is the character that will be removed

    from string1.If this parameter is omitted,the trim functionwill remove all leading & trailing spaces from string1.

    string1 is the string to trim.

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    37/50

    Example:

    1)Select Trim( oracle ) Trim both sides fromdual; o/p-oracle

    2)Select Trim(leading x from xxxoraclexxx')Remove prefixes" from dual; o/p-oraclexxx

    3)Select Trim(trailing x from xxxoraclexxx')Remove suffixes" from dual; o/p-xxxoracle

    4)Select Trim(both x from xxxoraclexxx') Removeprefixes & suffixes" from dual; o/p-oracle

    5)Select Trim(both 1 from 123oracle12111')Remove string" from dual; o/p-23oracle12

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    38/50

    xii)Lpad:Returns char1,left-padded to length n with the sequence ofcharacters specified in char2.Ifchar2 is not specified Oracle

    uses blanks by default.

    Syntax: Lpad(char1,n ,[,char2])Example:1)Select Lpad(oracle,10,*) Lpad from dual; o/p-****oracle (total

    length is 10)

    2)select Lpad('oracle',2) "Lpad" from dual; o/p- or

    xiii)Rpad:Returns char1,right-padded to length n with thecharacters specified in char2.Ifchar2 is not specified

    Oracle uses blanks by default.

    Syntax: Rpad(char1,n ,[,char2])Example:1)Select Rpad(oracle,10,*) Rpad from dual;

    o/p-oracle**** (total length is 10)

    2)select Rpad('oracle',2) Rpad" from dual; o/p- or

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    39/50

    c)Conversion Functionsi)To_number:converts char,a CHARACTER value expressing a

    number, to a NUMBER datatype.

    Syntax:To_number(char)

    Example:

    1)Select to_number(123) from dual; o/p-123

    2)Select curbal+to_number(1000) from customer;

    ii)To_char(Number Conversion):

    Converts a value of a NUMBER datatype to a character

    Datatype,using the optional format string.To_char() accepts a

    number(n) & a numeric format(fmt ) in which the number has to

    appear.Iffmt is omitted,n is converted to a char value exactly longenough to hold all significant digits.

    Syntax: To_char(n [,fmt])

    Example:

    1)Select to_char(17689,$099,999) char from dual; o/p- $017,689

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    40/50

    iii)To_char(Date Conversion):

    Converts a value of a DATE datatype to a

    CHAR value.To_char() accepts a date, as well asthe format ( fmt ) in which the date has to

    appear. fmt must be in date format .Iffmt is

    omitted, the date is converted to a char valueusing the default date format i.e.DD-MON-YY.

    Syntax:

    To_char(date [,fmt])

    Example:

    1)Select to_char(jdate,Month DD,YYYY) New date

    format from employee where eno=100;

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    41/50

    Date Conversion function:

    iv)To_date

    Converts a char field to a DATE field.

    Syntax:

    To_date(char [,fmt])

    Example:

    1)Insert into emp(eno,ename,salary,jdate) values

    (100,satish,20000,to_date(06-NOV-1999 10:55

    :06 A.M. , DD-MON-YYYY HH:MI:SS A.M.));

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    42/50

    d)Date FunctionsTo manipulate & extract values from the date column of atable Oracle provides some date functions as follows:

    i)Add_months:Returns date after adding the number ofmonths specified in the function.

    Syntax:

    Add_months(d,n)

    Example:1)Select add_months(sysdate,3) from dual;

    ii)Last_day: Returns the last date of the month specified with

    the function.

    Syntax:Last_day(d)

    Example:

    1)Select sysdate,last_day(sysdate) from dual;

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    43/50

    iii)Months_between:Returns the number of months between d1 & d2.

    Syntax:

    Months_between(d1,d2)

    Example:1)Select Months_between(02-nov-1999,02-sep-1992) from dual; o/p-86

    iv)Next_day: Returns the date of the first weekday named by char that is

    after the date named by date.char must be a day of the

    week.

    Syntax:Next_day(date,char)

    Example:

    1)Select next_day(25-jan-2012,Wednesday) from dual;

    o/p- 01-feb-2012

    2)Select next_day(25-jan-2012,monday) from dual;o/p- 30-jan-2012

    3)Select next_day(21-jan-2012,saturday) from dual;

    o/p- 28-jan-2012

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    44/50

    Special Date Formats Using To_char Function

    Sometimes the date value is required to be

    displayed in special formats. e.g.instead of 03-JAN-81,displays the date as

    03rdJanuary-1981.

    For this.Oracle provides Special attributes, whichcan be used in the format specified with the

    To_char function.

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    45/50

    1)Use of TH in the To_char() function

    DDTH places TH,RD,ND for the date (DD).

    e.g. 2ND,3RD,8TH etc.

    Example:

    i)select cust_no,name,To_char(dob,ddth-mon-yy )dob_ddth from customer where cust_no=10;

    o/p- 10 shaha 03rd-jan-99ii)select cust_no,name,To_char(dob,ddth-month-yyyy) dob_ddth from customer where

    cust_no =11;

    o/p- 11 patil 2nd -October-1990iii)select cust_no,name,To_char(dob,ddth)dob_ddth from customer where cust_no =12;

    o/p- 12 mane 2nd

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    46/50

    2)Use of SP in the To_char() function

    DDSP indicates that the date (DD) must be displayed byspelling the date,e.g.ONE,TWELVE etc.

    Example:

    i)select cust_no,name,To_char(dob,ddsp-mon-yy )dob_ddsp from customer where cust_no=10;

    o/p- 10 shaha three-jan-99ii)select cust_no,name,To_char(dob,ddsp-month-

    yyyy) dob_ddsp from customer wherecust_no =11;

    o/p- 11 patil twenty-two -October-1990iii)select cust_no,name,To_char(dob,ddsp) dob_ ddsp

    from customer where cust_no =12;

    o/p- 12 mane nineteen

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    47/50

    3)Use of SPTH in the To_char() function

    SPTH displays the date (DD) with th added to the spellingfourteenth,twelfth,thirtieth etc.

    Example:

    i)select cust_no,name,To_char(dob,ddspth-mon-yy )dob_ddspth from customer where cust_no=10;

    o/p- 10 shaha third-jan-99ii)select cust_no,name,To_char(dob,ddspth-month-yyyy)

    dob_ddspth from customer where cust_no =11;

    o/p- 11 patil twenty-second-October-1990

    iii)select cust_no,name,To_char(dob,ddspth)dob_ ddsp th from customer where cust_no =12;

    o/p- 12 mane nineteenth

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    48/50

    Group By Clause The Group By clause creates a data set,containing several sets of records

    grouped together based on a condition.Syntax:

    Select ,,----, ,Aggregate_Function(Expression) from Tablename where Group bY,,------, ;

    Example:

    EMPNO NAME BRANCHNO

    1 SHAHA 10

    2 SHUKLA 12

    3 MANE 10

    4 RANE 15

    5 SANE 11

    6 DESHPANDE 10

    1)Find out how many employees are there in each branch.

    Ans.-Select BRANCHNO BRANCH NO,Count(EMPNO) NO. OF EMPLOYEES FROM

    EmpBranch Group By BRANCHNO;O/P BRANCH NO NO. OF EMPLOYEES

    11 1

    10 3

    12 1

    15 1

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    49/50

    Having Clause The Having clause can be used in conjunction with the

    GROUP BY clause.

    Having imposes a condition on the Group by clause,which further filters the groups created by the Group byclause.

    Each column specification specified in the Having clause

    must occur within a statistical function or must occur inthe list of columns named in the Group By Clause.

    Example:

    Q.Find out the branches which has more than 2 employees.

    Ans.-Select Branchno "BRANCH NO",Count(Empno)"NO. OFEMPLOYEES" FROM EmpBranch Group By Branchnohaving count(empno)>2;

    o/p BRANCHNO NO. OF EMPLOYEES

    10 3

  • 8/3/2019 Class Copy of SQL OPERATORS(Chap 5)

    50/50

    Rules for Group By & Having Clause

    Columns listed in the select statement have to be

    listed in the Group By clause.

    Only group functions can be used in the Having

    clause.