SlideShare a Scribd company logo
Operators and Built-in Functions  
Operators Operators are used to manipulate data using the select statement.  Arithmetic Relational Logical Special  String Built-in Functions Character Numeric Date Aggregate/Group Conversion General/Other  
Arithmetic Operators Operators  are   +,  -,  *,  /   SELECT * FROM EMP WHERE SAL + COMM > 3000; The above Example will select the employee(s) whose salary + commission is more than 3000.   SELECT * FROM EMP WHERE SAL – COMM > 2000; The above example will select the employee(s) whose salary – commission is more than 2000;    SELECT * FROM EMP WHERE COMM > SAL * 10/100; The above example will select the employee(s) whose commission is more than 10% of their salary.
Logical Operators AND  (logical AND),  OR  (logical OR) and  NOT  (logical NOT). SELECT * FROM EMP  WHERE JOB = ‘CLERK’ AND DEPTNO=20 ; The above example will select the employee(s) who is working in dept 10 and he should be a CLERK. In the above case, both the job and deptno should satisfy the given condition i.e., both the conditions should be true. SELECT ENAME FROM EMP  WHERE JOB=’SALESMAN’ OR JOB=’ANALYST’; The above example will select the employee(s) whose  JOB is either SALESMAN or ANALYST. SELECT * FROM EMP  WHERE DEPTNO NOT IN (10, 20); The above example will select the employee(s) who are not working in department 10 and 20.
Relational Operators   =  Equal to <>, !=,^= Not Equal to < Less than > Greater than >= Greater than or  <= Less than or  Equal to
Examples for Relational Operators: (= , <>) SELECT * FROM EMP  WHERE DEPTNO = 10;   The above example will select the employee(s) who are working in deptno 10;   SELECT * FROM EMP WHERE DEPTNO <> 10; The above example will select the employee(s) who are not working in deptno 10.    
Example for > ,>=, <. <= SELECT * FROM EMP WHERE  SAL > 3000 ; The above example will select the employee(s) who is getting salary from 3001 onwards. SELECT * FROM EMP WHERE  SAL >= 3000 ;   The above example will select the employee(s) who is getting salary from 3000 onwards. SELECT * FROM EMP WHERE  SAL < 2000 ;   The above example will select the employee(s) who is getting salary below 2000; SELECT * FROM EMP WHERE  SAL <= 2000 ; The above example will select the employee(s) who is getting salary 2000 and less.
Special Operators   LIKE, BETWEEN AND, IN, ANY and ALL   Examples: SELECT * FROM EMP WHERE ENAME  LIKE  ‘ALLEN’;  The above example will select the employee(s) whose name is exactly like ‘ ALLEN’. Even it will not fetch the employee whose name is ‘allen’ or ‘ Allen’ or ‘Allen’.   SELECT * FROM EMP WHERE SAL  BETWEEN  1500  AND  3500 ;   The above example will select the employee(s) who is getting salary between 1500 and 3500; ANY, IN and ALL operators will be explained more in SUB-QUERIES.
String Operators   %   (percentage) _  (underscore) ||  (concatenation)   The above operators are used to compare the string values.  
Examples:  SELECT * FROM EMP WHERE ENAME LIKE ‘E%’; The above example will select the employee(s) who’s name  starts with ‘E’ followed by any number of characters .   SELECT * FROM EMP WHERE ENAME LIKE ‘S_ _ _ _ _’; The above example which uses the _(underscore) after ‘S’, will fetch the employee(s) who’s  name starts with ‘S’ and whose length of name is exactly five characters . SELECT ENAME||JOB||HIREDATE FROM EMP; The above example will list the ENAME, JOB, HIREDATE  column values joined together  without any space in between.  
Built-in SQL functions SQL provides a number of predefined functions that can be called from within an SQL statement. It is used to manipulate data items.   Advantages of Functions   Functions can be used to perform complex calculations on data.   Functions can modify individual data items.   Functions can very easily manipulate output for group of rows.   Functions can alter date formats for display.
Types of Functions   Ø        Character functions Ø        Arithmetic functions Ø        Date functions Ø  Conversion functions  Ø        Aggregate / Group functions
Character Functions CHR Syntax: CHR(x) Purpose: Returns the character that has the value equivalent to x in the database character set. CHR and ASCII are opposite functions. CHR returns the character given the character number, and ASCII returns the character number given the character. Example: SELECT CHR(37) a, CHR(100) b, CHR(101) c from dual; Output: A  B C - - - % d  e
What is DUAL? Dual is a small Oracle table created for testing functions or doing quick calculations which has one row and column. Since Oracle’s many functions work on both columns and literals. Some Oracle functions use just literals in these situations DUAL table can be used.  Structure of Null table: Name  Null?  Type ----------------------------------------------------- -------- ----------------- DUMMY  VARCHAR2(1) Select * from dual; D - X
CONCAT   Syntax: CONCAT (String1, String 2)   Purpose  Returns  string1  concatenated with  string2.  This function is identical to the || operator.   Example:   SELECT CONCAT(‘Information  ’, ‘  Technology’)  “Computer” from dual;   Output: Computer ------------- Information Technology  
INITCAP   Syntax: INITCAP( String )   Purpose: Returns  string  with the first character of each word capitalized and the remaining characters of each word in lowercase.  Characters that are not letters are unaffected.   Example:   SELECT INITCAP (‘time is gold’) “Time” from dual;   Output: Speech ----------------------- Time is gold
LOWER   Syntax: LOWER(String)   Purpose: Returns  string  with all characters in lowercase.  Any characters that are not letters will not convert.  If  string  has the CHAR datatype, the result is also CHAR.  If  string  is VARCHAR2, the result is VARCHAR2.   Example:   SELECT LOWER (‘EVERYTHING IN LOWER CASE’) “lower” from dual;    Output:  lower -------------- everything in lower case  
UPPER   Syntax: UPPER(string)   Purpose  Returns  string  with all letters in uppercase.  If string has datatype CHAR, the return value is also CHAR.  If string has datatype VARCHAR2, then the return value is VARCHAR2.  Any Characters that are not letters are left intact in the returned value. Example:  SELECT UPPER (‘print in uppercase’) “UPPER” FROM dual; Output: UPPER PRINT IN UPPERCASE
LPAD Syntax: LPAD(String1,  x [,string2]) Purpose : Returns string1 after padding string2 from left to length x. If  string2  is less than  x  characters, it is duplicated as necessary.  If  string2  is more than  x  characters, only the first required  x  characters are used.  If  string2  is not specified, it defaults to a single blank for each space.  Examples: SELECT LPAD (‘have a good day’,18) “First” from dual; Output: First ----- have a good day
SELECT LPAD (‘have a good day’, 20, ‘XY’) “Demo” from dual;   Output: Demo XYXYXhave a good day   SELECT LPAD (‘have a good day’, 16, ’XY’) “Test” from dual;   Output: Test Xhave a good day
RPAD   Syntax: RPAD(String1,x[,string2])   Purpose: Returns  string1  padded on the right to length x with the characters in  string2.  If  string2  is less than x characters, it is duplicated as necessary.  If  string2  is more than x characters, only the first x are used.  If  string2  is not specified, it defaults to a single blank.    Examples:   SELECT RPAD (‘Cricket’, 10, ‘!’) “First” from dual;   Output: First ---------- Cricket!!!  
SELECT RPAD(‘Cricket’, 10, ‘AB’) “Second” from dual;   Output: Second ---------- CricketABA   SELECT RPAD ('Cricket', 3) &quot;Third&quot; from dual;   Output:  Thi --- Cri
RTRIM   Syntax: RTRIM(String1[,string2])   Purpose: Returns  string1  with the rightmost characters appearing in  string2  removed.  String2  defaults to a single blank.  The database will scan  String1,  starting from the rightmost position.  When the first character not in  String2  is encountered, the result is returned.    Examples: SELECT RTRIM(‘This is a string  ’)  “First” from dual; Output:   First     This is a string  
SELECT RTRIM(‘This is a stringxxxxx’, ‘x’) “Second” from dual;   Output: Second ---------------- This is a string   SELECT RTRIM(‘This is a string as well’, ‘well’) “Third” from dual;   Output: Third -------------------- This is a string as
TRIM  This function can used instead of LTRIM and  RTRIM   Example:     SELECT TRIM(‘  INDIA  ‘) FROM DUAL;   Output:  TRIM( ----- INDIA  
REPLACE Syntax: REPLACE (String, search_str[, replace_str])   Purpose : Returns  string  with every occurrence of  search_str  replaced with  replace_str.  If  replace_str  is not specified, all occurrences of search_str are removed. Examples: SELECT REPLACE (‘This and That’, ‘Th’, ‘B’)”First” from dual;   Output: First Bis and Bat  
SELECT REPLACE (‘This and That’, ‘Th’)”Second” from dual;   Output: Second ------------ is and at   SELECT REPLACE (‘This and That’, null) “Third” from dual;   Output: Third ------------ This and That
SUBSTR   Syntax  :  SUBSTR ( string ,  a  [,  b ])   Purpose: Returns a portion of  string  starting at character  a, b  characters long . If  a  is 0, it is treated as 1(the beginning of the string).  If  b  is positive, characters are returned counting from the left.  If  b  is negative, characters are returning starting from the end of  string,  and counting from the right .  If  b  is not present, it defaults to the entire string.  If  b  is less than 1, NULL is returned.  Examples: SELECT SUBSTR('He is a Good Boy', 2) &quot;First&quot; from dual; Output: First e is a Good Boy SELECT SUBSTR('He is a Good Boy', 2, 4) &quot;Second&quot; from dual Output: Second e is
SELECT SUBSTR ('He is a Good Boy', -5) &quot;Third&quot; from dual   Output: Third ----- d Boy   SELECT SUBSTR ('He is a Good Boy', -5, 3) &quot;Four&quot; from dual   Output: Fou --- d B
TRANSLATE Syntax: TRANSLATE ( string , from_str , to_str ) Purpose: Returns  string  with all occurrences of each character in  from_str  replaced by the corresponding character in  to_str. If  from_str  is longer than  to_str,  any extra characters in  from_str  not in to_str are removed from  string , since they have no corresponding characters.  to_str cannot be empty.  If any argument to TRANSLATE is null, the result is NULL as well.   Examples:   SELECT TRANSLATE(‘abcdefghij’,’abcdef’,’123456’) from dual;   Output: TRANSLATE( 123456ghij SELECT TRANSLATE (‘abcdefghij’, ‘abcdefghij’, ‘123456’) from dual;   Output: TRANSL 123456  
SOUNDEX   Syntax: Soundex( string )   Purpose : Returns the phonetic representation of  string.  This is useful for comparing words that are spelled differently but sound alike. Example: SELECT ENAME FROM EMP  WHERE SOUNDEX(ENAME) = SOUNDEX('SMEETH');   Output: ENAME ---------- SMITH
Date Functions   The date functions take arguments of type DATE,  except  for the MONTHS_BETWEEN function, which returns a  NUMBER, all of the functions return DATE values.  
SYSDATE Syntax: SYSDATE Purpose: Returns the current date and time, of type DATE.  Takes no arguments.  When used in distributed SQL statement, SYSDATE returns the date and time of the local database. ( For instance if the current date is 4th May 2002) Example:    SELECT SYSDATE FROM DUAL; Output:  SYSDATE    ---------   05-MAY-02
ADD_MONTHS Syntax: ADD_MONTHS ( d,x  ) Purpose: Returns the date  d  plus  x  months or  d  minus  x . x can be any integer.  Example: SELECT ADD_MONTHS(‘02-MAR-88’, 3),  ADD_MONTHS(‘30-JAN- 00’, 1)  FROM DUAL;   Output:  ADD_MONTH ADD_MONTH ------------------  ------------ ------ 02-JUN-88  29-FEB-00
MONTHS_BETWEEN Syntax:  MONTHS_BETWEEN(DATE1,DATE2) Purpose: Returns the number of months between date1 and date2.  If both date1 and date2 have the same day component, or if both are the last day of their respective months, then the result is an integer. Otherwise, the result will contain the fractional portion of a 31-day month. Example: SELECT MONTHS_BETWEEN('12-APR-71', '12-MAR-97') &quot;First&quot;,      MONTHS_BETWEEN ('12-APR-71', '12-MAR-60') &quot;Second&quot;  FROM dual;   Output:   First Second ------- ----------   -311 132.67742
LAST_DAY   Syntax: LAST_DAY( d) Purpose:  Return the date of last day of the month that contains  d.  This function can be used to determine how many days are left in the current month. Example: SELECT LAST_DAY('12-APR-71') &quot;CURRENT&quot;,  LAST_DAY('12-APR-71') - TO_DATE('12-APR-71')  &quot;Days left&quot; FROM dual;   Output:   Current Days Left   ------- ---------- 30-APR-71   18
NEXT_DAY Syntax: NEXT_DAY(d, string) Purpose  : This function returns the date of next specified day of the week(string)  after the  d (date). Example: SELECT NEXT_DAY('07-MAY-02','MONDAY') FROM DUAL; Output: NEXT_DAY( --------- 13-MAY-02
ROUND   Syntax: ROUND(d,  [, format) Purpose  : Returns the date d to the unit specified by format. If format is not specified, it defaults to 'DD', which rounds d to the nearest day. Example:   SELECT ROUND(TO_DATE(‘12-APR-71’), ‘MM’) &quot;Nearest Month&quot;  FROM dual;   Output : Nearest Month ----------------- 01-APR-71   (1-15 it will round to the same month, 16 and after - next month)
TRUNC   Syntax: TRUNC(d, [,format]) Purpose: Returns the date d truncated to the unit specified by format.  If format is not specified, it defaults to 'DD', which truncates d to the nearest day. Example: SELECT TRUNC(   FROM dual;   Output:  First Day -------------- 01-JAN-71
Date Arithmetic Applying the arithmetic operators to dates and numbers are described. When one date value is subtracted from another, the result is a number.   Examples of valid date arithmetic expressions follow:   Example 1:  Adding to Date   SELECT SYSDATE, SYSDATE + 1 &quot;Tomorrow&quot; FROM dual;   Output: SYSDATE  Tomorrow -------------- ------------- 13-NOV-95 14-NOV-95  
Subtracting from Date Example 1: SELECT TO_DATE('12-APR-71 12:00:00', 'DD-MON-YY HH24:MI:SS')  - TO_DATE(15-MAR-71 15:00 -MON-YY HH24:MI:SS')  &quot;Difference&quot; FROM dual;   Output: Difference --------------   27.875  
Example 2:   SELECT TO_DATE('10-AUG-98') - TO_DATE('12-FEB-98') FROM DUAL;   Output:  TO_DATE('10-AUG-98')-TO_DATE('12-FEB-98') --------------------------------------------------------------   179  
Conversion Functions   TO_NUMBER   Syntax: TO_NUMBER( string  [, format [,nlsparams]])   Purpose:   Converts the CHAR or VARCHAR2 string to a NUMBER value. If format is specified, string should correspond to number format. Example: SELECT TO_NUMBER('25') + TO_NUMBER('50') &quot;TOTAL&quot; FROM DUAL;   Output: TOTAL     75
TO_CHAR (WITH NUMBERS)   Syntax: TO_CHAR( num,  [,format[, nlsparams ]])   Purpose: Converts the NUMBER argument  num  to a VARCHAR2.   If  format  not specified, the resultant string will have exactly as many characters as necessary to hold the significant digits of  num. Example: SELECT TO_CHAR(123) FROM DUAL;   Output TO_ 123
TO_CHAR (WITH DATE) Syntax: TO_CHAR(d,[,format [,nlsparams]]) Purpose: TO_CHAR can also be used for the conversion of dates values to a specified character format. TO_CHAR allows us to format the date in various different ways. Example 1: SELECT TO_CHAR(SYSDATE, ‘DAY DDSPTH MONTH YEAR') FROM DUAL; Output : TO_CHAR(SYSDATE,'DAYDDSPTHMONTHYEAR') --------------------------------------------------------------------- WEDNESDAY  FOURTEENTH  MARCH  TWO THOUSAND ONE  
Example 2: SELECT TO_CHAR(HIREDATE, 'DDTH MONTH YEAR') &quot;JOINING DATE&quot;  FROM EMP  WHERE EMPNO = 7788; Output: JOINING DATE ------------------------------------------------- 09TH DECEMBER  TWENTY EIGHTY-TWO Example3: SELECT TO_CHAR(TO_DATE('14-MAR-01'), 'RM') FROM  DUAL; Output: TO_C   III RM – Roman Numeral Month 
Group / Aggregate Functions
Group / Aggregate Functions Group functions are those statistical functions, which gives information about a group of value taken as whole.  The aggregate function produce a single value for an entire group or table.  In all group functions, NULLs are ignored.  These functions are valid in the select list of a query and the GROUP BY clause only.
AVG Syntax: AVG([DISTINCT | ALL]col) Purpose: Returns the average of the column values.   Example:   SELECT AVG(sal) FROM EMP;
COUNT  Syntax  :  COUNT(*|[DISTINCT |ALL]col) Purpose  :  Count function determines the number of rows or non-NULL column values.    If * is passed, then the total number of rows is returned.   Example 1: SELECT COUNT(*) FROM EMP; Example 2:   SELECT COUNT(deptno) FROM EMP; Example3:   SELECT COUNT(DISTINCT deptno) FROM EMP;
MAX   Syntax: MAX([DISTINCT | ALL] coL) Purpose  : Returns the maximum value of the select list item.    Example 1: SELECT MAX(SAL) FROM EMP; Example 2:    SELECT MAX(LENGTH(ENAME)) FROM EMP; This example returns the length of the longest name in the EMP table:
MIN   Syntax  : MIN([DISTINCT | ALL] coL)   Purpose:  Returns the maximum value of the select list item.  Example: SELECT MIN(COMM) “MIN-COMM”, MIN(SAL) “MIN-SAL” FROM EMP;   Output: MIN-COMM  MIN-SAL ----------------- -------------   0  800
SUM   Syntax  : SUM([DISTINCT | ALL] Col)   Purpose: Returns the sum of the values for the select list item.   Example 1:   SELECT SUM(SAL) FROM EMP;  
Other / General Functions DECODE Syntax: DECODE( base_expr,   compare1, value1,   compare2, value2,    . . .      default ) Purpose  : The DECODE statement is similar to a series of nested IF-THEN-ELSE statements.  The  base_expr  is compared to each of  compare1, compare2 , etc., in sequence. If  base_expr  matches the i th  compare item, the  i th  value is returned. If  base_expr  doesn't match any of the compare values,  default  is returned.  Each compare value is evaluated in turn.  If a match is found, the remaining  compare  values, if any, are not evaluated.  A NULL  base_expr  is considered equivalent to a NULL compare value.  
Example 1:   SELECT DECODE(10, 10, 'TEN', 20, 'TWENTY', 30, 'THIRTY') &quot;MATCH&quot;  FROM DUAL;   Output: MAT TEN  
Example 2:   SELECT DECODE(50, 10, ‘TEN’, 20, ‘TWENTY’, 30, ‘THIRTY’, ‘NEW VALUE’) FROM DUAL;   Output: DECODE(50 --------- NEW VALUE   Example 3:   SELECT DECODE(NULL, ‘A’, ‘ARUN’, NULL, ‘NOVALUE’, ‘B’, ‘BHARATH’) FROM DUAL;   Output: DECODE( ------- NOVALUE
GREATEST Syntax  :  GREATEST (expr1[,expr2]…)   Purpose : Returns the greatest expression of its arguments. Each expression is implicitly converted to the type of expr1 before the comparisons are made.  Example 1:   SELECT GREATEST (10, '7', -1) FROM dual;   Output: GREATEST (10, '7', -1) ---------------------   10   Example 2:   SELECT GREATEST(‘ASHWIN’, ‘SOFIA’) FROM DUAL;   Output: GREAT --------- SOFIA
LEAST   Syntax  : LEAST(expr1 [, expr2]…)   Purpose : This function returns the least value in the list of expressions.  LEAST behaves similarly to GREATEST, in that all expressions are implicitly converted to the datatype of the first.  Example 1:   SELECT LEAST (10, '7', -1) FROM dual; Output: LEAST(10,'7', -1) ----------------   -1   Example 2:   SELECT LEAST ('ASHWIN', 'SOFIA') FROM DUAL;   Output: LEAST( ------ ASHWIN
NVL Syntax: NVL( expr1, expr2 ) Purpose: If  expr1  is NULL, returns  expr2;  otherwise, returns  expr1.  The columns with NULL values are ignored in all of the group functions such as sum, Avg etc.  The NULL function helps in substituting a value in place of a NULL.    Example:  SELECT  NVL (null, ‘this is a null value’)  “NullTest” FROM DUAL; Output :  NullTest    ---------------------  this is a null value   SELECT ENAME, SAL, COMM, SAL + COMM “GROSS SAL”, SAL + NVL (COMM, 0) “CORRECT SAL” FROM EMP;   (The above command will substitute 0 for commission where the commission is NULL).
UID Syntax  : UID   Purpose : Returns an integer that uniquely identifies the current database user. UID takes no arguments.   Example: This example shows a sample SQL*Plus session. SQL> Connect Scott/Tiger Connected.  SQL> SELECT UID FROM dual; UID 8 SQL> connect system/manager Connected.    SQL> SELECT UID FROM dual; UID 5
USER   Syntax  : USER   Purpose : Returns a VARCHAR2 value containing the name of the current Oracle user. USER takes no arguments.   Example:  This example shows a sample SQL*PLUS statements   SQL> connect Scott/Tiger   Connected.  SQL> SELECT USER FROM dual; USER SCOTT SQL> Connect Sys/Change_on_install    Connected. SQL> SELECT USER FROM dual; USER SYS

More Related Content

PPTX
Introduction to SQL
Ehsan Hamzei
 
PPTX
Cursors
Priyanka Yadav
 
PDF
UNIT-5 IoT Reference Architecture.pdf
MansiMehta96928
 
PPTX
SQL commands
GirdharRatne
 
PPTX
Voldemort
fasiha ikram
 
PPT
Cloud computing simple ppt
Agarwaljay
 
PPTX
Consistency in NoSQL
Dr-Dipali Meher
 
Introduction to SQL
Ehsan Hamzei
 
UNIT-5 IoT Reference Architecture.pdf
MansiMehta96928
 
SQL commands
GirdharRatne
 
Voldemort
fasiha ikram
 
Cloud computing simple ppt
Agarwaljay
 
Consistency in NoSQL
Dr-Dipali Meher
 

What's hot (20)

DOC
SQL practice questions - set 3
Mohd Tousif
 
PPTX
Aggregate function
Rayhan Chowdhury
 
PPT
Joins in SQL
Vigneshwaran Sankaran
 
PPTX
Sql operator
Pooja Dixit
 
DOC
Sql queries with answers
vijaybusu
 
PPT
Aggregate functions
sinhacp
 
PDF
Sql queries questions and answers
Michael Belete
 
PDF
PL/SQL TRIGGERS
Lakshman Basnet
 
PPT
Sql query [select, sub] 4
Dr. C.V. Suresh Babu
 
DOC
Dbms lab questions
Parthipan Parthi
 
PDF
Managing I/O in c++
Pranali Chaudhari
 
PPTX
Expression and Operartor In C Programming
Kamal Acharya
 
PDF
Array data structure
maamir farooq
 
PPT
SQL select statement and functions
Vikas Gupta
 
PDF
Python list
Mohammed Sikander
 
PPTX
Sql commands
Pooja Dixit
 
PPTX
Inheritance in java
Tech_MX
 
PPT
Using the set operators
Syed Zaid Irshad
 
PPT
Array in c
Ravi Gelani
 
PPT
SQL subquery
Vikas Gupta
 
SQL practice questions - set 3
Mohd Tousif
 
Aggregate function
Rayhan Chowdhury
 
Joins in SQL
Vigneshwaran Sankaran
 
Sql operator
Pooja Dixit
 
Sql queries with answers
vijaybusu
 
Aggregate functions
sinhacp
 
Sql queries questions and answers
Michael Belete
 
PL/SQL TRIGGERS
Lakshman Basnet
 
Sql query [select, sub] 4
Dr. C.V. Suresh Babu
 
Dbms lab questions
Parthipan Parthi
 
Managing I/O in c++
Pranali Chaudhari
 
Expression and Operartor In C Programming
Kamal Acharya
 
Array data structure
maamir farooq
 
SQL select statement and functions
Vikas Gupta
 
Python list
Mohammed Sikander
 
Sql commands
Pooja Dixit
 
Inheritance in java
Tech_MX
 
Using the set operators
Syed Zaid Irshad
 
Array in c
Ravi Gelani
 
SQL subquery
Vikas Gupta
 
Ad

Viewers also liked (20)

PPTX
SQL Functions
ammarbrohi
 
PPTX
Special operators in Database
Rosie Jane Enomar
 
PPTX
introdution to SQL and SQL functions
farwa waqar
 
PDF
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Beat Signer
 
PDF
SQL Functions and Operators
Mohan Kumar.R
 
PPTX
Sql Server execution plans
Florin Cardasim
 
PDF
D drops
Zoran Stojcevski
 
PDF
XML on SQL Server
torp42
 
PPT
7a advanced tsql
Nauman R
 
DOCX
Complex queries in sql
Charan Reddy
 
DOC
Xl shortcuts
Babu Jeevan
 
DOC
Complete Sql Server querries
Ibrahim Jutt
 
PPTX
Sql query analyzer & maintenance
nspyrenet
 
PDF
SQL Server - Querying and Managing XML Data
Marek Maśko
 
PDF
Stored-Procedures-Presentation
Chuck Walker
 
PDF
CSS3 and Responsive Web Design - Web Technologies (1019888BNR)
Beat Signer
 
PDF
Imp notes dbms
vishal jadav
 
PDF
Unit 1 basic concepts of DBMS
Roshan Rajbhandari
 
DOC
SQL
Tuhin_Das
 
SQL Functions
ammarbrohi
 
Special operators in Database
Rosie Jane Enomar
 
introdution to SQL and SQL functions
farwa waqar
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Beat Signer
 
SQL Functions and Operators
Mohan Kumar.R
 
Sql Server execution plans
Florin Cardasim
 
XML on SQL Server
torp42
 
7a advanced tsql
Nauman R
 
Complex queries in sql
Charan Reddy
 
Xl shortcuts
Babu Jeevan
 
Complete Sql Server querries
Ibrahim Jutt
 
Sql query analyzer & maintenance
nspyrenet
 
SQL Server - Querying and Managing XML Data
Marek Maśko
 
Stored-Procedures-Presentation
Chuck Walker
 
CSS3 and Responsive Web Design - Web Technologies (1019888BNR)
Beat Signer
 
Imp notes dbms
vishal jadav
 
Unit 1 basic concepts of DBMS
Roshan Rajbhandari
 
Ad

Similar to Sql operators & functions 3 (20)

PPTX
Functions
Ankit Dubey
 
PPTX
2 puc cs.pptx bsbshsjshsbbsjsjshdbdbbdbdd
DevKartikSharma1
 
DOCX
Database Query Using SQL_ip.docx
VandanaGoyal21
 
PPTX
C++ Programming Homework Help
C++ Homework Help
 
PDF
Introduction to oracle functions
Nitesh Singh
 
PPT
Module03
Sridhar P
 
PPT
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
अभिषेक शर्मा
 
PPT
Chinabankppt
newrforce
 
PPTX
string functions in SQL ujjwal matoliya.pptx
ujjwalmatoliya
 
PDF
Sap script system_symbol
moderngladiator
 
PPT
Intro to tsql unit 10
Syed Asrarali
 
PPTX
My SQL.pptx
KieveBarreto1
 
PPTX
Basics of SQL understanding the database.pptx
vikkylion302
 
DOCX
Unitii string
Sowri Rajan
 
PPTX
Diploma ii cfpc u-4 function, storage class and array and strings
Rai University
 
PDF
012. SQL.pdf
recosi2217
 
PPTX
Bsc cs i pic u-4 function, storage class and array and strings
Rai University
 
PDF
iRODS Rule Language Cheat Sheet
Samuel Lampa
 
PPT
Chapter-5.ppt
CindyCuesta
 
Functions
Ankit Dubey
 
2 puc cs.pptx bsbshsjshsbbsjsjshdbdbbdbdd
DevKartikSharma1
 
Database Query Using SQL_ip.docx
VandanaGoyal21
 
C++ Programming Homework Help
C++ Homework Help
 
Introduction to oracle functions
Nitesh Singh
 
Module03
Sridhar P
 
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
अभिषेक शर्मा
 
Chinabankppt
newrforce
 
string functions in SQL ujjwal matoliya.pptx
ujjwalmatoliya
 
Sap script system_symbol
moderngladiator
 
Intro to tsql unit 10
Syed Asrarali
 
My SQL.pptx
KieveBarreto1
 
Basics of SQL understanding the database.pptx
vikkylion302
 
Unitii string
Sowri Rajan
 
Diploma ii cfpc u-4 function, storage class and array and strings
Rai University
 
012. SQL.pdf
recosi2217
 
Bsc cs i pic u-4 function, storage class and array and strings
Rai University
 
iRODS Rule Language Cheat Sheet
Samuel Lampa
 
Chapter-5.ppt
CindyCuesta
 

More from Dr. C.V. Suresh Babu (20)

PPTX
Data analytics with R
Dr. C.V. Suresh Babu
 
PPTX
Association rules
Dr. C.V. Suresh Babu
 
PPTX
Clustering
Dr. C.V. Suresh Babu
 
PPTX
Classification
Dr. C.V. Suresh Babu
 
PPTX
Blue property assumptions.
Dr. C.V. Suresh Babu
 
PPTX
Introduction to regression
Dr. C.V. Suresh Babu
 
PPTX
Expert systems
Dr. C.V. Suresh Babu
 
PPTX
Dempster shafer theory
Dr. C.V. Suresh Babu
 
PPTX
Bayes network
Dr. C.V. Suresh Babu
 
PPTX
Bayes' theorem
Dr. C.V. Suresh Babu
 
PPTX
Knowledge based agents
Dr. C.V. Suresh Babu
 
PPTX
Rule based system
Dr. C.V. Suresh Babu
 
PPTX
Formal Logic in AI
Dr. C.V. Suresh Babu
 
PPTX
Production based system
Dr. C.V. Suresh Babu
 
PPTX
Game playing in AI
Dr. C.V. Suresh Babu
 
PPTX
Diagnosis test of diabetics and hypertension by AI
Dr. C.V. Suresh Babu
 
PPTX
A study on “impact of artificial intelligence in covid19 diagnosis”
Dr. C.V. Suresh Babu
 
PDF
A study on “impact of artificial intelligence in covid19 diagnosis”
Dr. C.V. Suresh Babu
 
Data analytics with R
Dr. C.V. Suresh Babu
 
Association rules
Dr. C.V. Suresh Babu
 
Classification
Dr. C.V. Suresh Babu
 
Blue property assumptions.
Dr. C.V. Suresh Babu
 
Introduction to regression
Dr. C.V. Suresh Babu
 
Expert systems
Dr. C.V. Suresh Babu
 
Dempster shafer theory
Dr. C.V. Suresh Babu
 
Bayes network
Dr. C.V. Suresh Babu
 
Bayes' theorem
Dr. C.V. Suresh Babu
 
Knowledge based agents
Dr. C.V. Suresh Babu
 
Rule based system
Dr. C.V. Suresh Babu
 
Formal Logic in AI
Dr. C.V. Suresh Babu
 
Production based system
Dr. C.V. Suresh Babu
 
Game playing in AI
Dr. C.V. Suresh Babu
 
Diagnosis test of diabetics and hypertension by AI
Dr. C.V. Suresh Babu
 
A study on “impact of artificial intelligence in covid19 diagnosis”
Dr. C.V. Suresh Babu
 
A study on “impact of artificial intelligence in covid19 diagnosis”
Dr. C.V. Suresh Babu
 

Recently uploaded (20)

PPTX
Accounting for Managers and businesses .pptx
Nikita Bhardwaj
 
PPT
geometric-modelingEast Coast of Kamchatka, 8.7M · 30 Jul 2025 08:52:50, Publi...
gshivakrishna3
 
PDF
Enabling Strategic Clarity in a Complex MoR Landscape.pdf
Jasper Colin
 
PDF
LM Curve Deri IS-LM Framework sess 10.pdf
mrigankjain19
 
PDF
A Brief Introduction About Greg Kutzin
Greg Kutzin
 
PDF
Top Hospital CEOs in Asia 2025 - by Hospital Asia Management Journal
Gorman Bain Capital
 
PDF
Melcom Copeland_Ripple_XRPL_First Ledger_Case Study (2024).pdf
MelcomCopeland
 
PDF
An Uncut Conversation With Gemini | PDF Document
Mike Hydes
 
PDF
The Integration of Bophuthatswana Electricity Corporation into Eskom by Matth...
Matthews Bantsijang
 
PPTX
Chapter One. Basics of public finance and taxation
kumlachewTegegn1
 
PPTX
d and f block elements chapter 4 in class 12
dynamicplays04
 
PPTX
STAFFING AND DIRECTING presentation .pptx
iqbalchjaved00
 
PPTX
01_4E - Ten Principles of Economics.pptx
AzelChio
 
PDF
CV of Dr.Choen Krainara Thai National, Nonthaburi City
Dr.Choen Krainara
 
PDF
SCB EIC expects CLMV outlook to face diverging risks amid global trade headwinds
SCBEICSCB
 
PPTX
H1 2025 review - a review of our trade recommendations for H1 2025
Mathias Lascar
 
PPTX
COMPOUND INTEREST PRESENTATION PPT REPORT
AngelicaAyon2
 
PDF
Torex to Acquire Prime Mining - July 2025
Adnet Communications
 
PDF
Cryptocurrency Wallet Security Protecting Your Digital Assets.pdf
Kabir Singh
 
PPTX
DR EDU INTRO TO CORPORATE FINANCING [Autosaved].pptx
BENDORMOSES
 
Accounting for Managers and businesses .pptx
Nikita Bhardwaj
 
geometric-modelingEast Coast of Kamchatka, 8.7M · 30 Jul 2025 08:52:50, Publi...
gshivakrishna3
 
Enabling Strategic Clarity in a Complex MoR Landscape.pdf
Jasper Colin
 
LM Curve Deri IS-LM Framework sess 10.pdf
mrigankjain19
 
A Brief Introduction About Greg Kutzin
Greg Kutzin
 
Top Hospital CEOs in Asia 2025 - by Hospital Asia Management Journal
Gorman Bain Capital
 
Melcom Copeland_Ripple_XRPL_First Ledger_Case Study (2024).pdf
MelcomCopeland
 
An Uncut Conversation With Gemini | PDF Document
Mike Hydes
 
The Integration of Bophuthatswana Electricity Corporation into Eskom by Matth...
Matthews Bantsijang
 
Chapter One. Basics of public finance and taxation
kumlachewTegegn1
 
d and f block elements chapter 4 in class 12
dynamicplays04
 
STAFFING AND DIRECTING presentation .pptx
iqbalchjaved00
 
01_4E - Ten Principles of Economics.pptx
AzelChio
 
CV of Dr.Choen Krainara Thai National, Nonthaburi City
Dr.Choen Krainara
 
SCB EIC expects CLMV outlook to face diverging risks amid global trade headwinds
SCBEICSCB
 
H1 2025 review - a review of our trade recommendations for H1 2025
Mathias Lascar
 
COMPOUND INTEREST PRESENTATION PPT REPORT
AngelicaAyon2
 
Torex to Acquire Prime Mining - July 2025
Adnet Communications
 
Cryptocurrency Wallet Security Protecting Your Digital Assets.pdf
Kabir Singh
 
DR EDU INTRO TO CORPORATE FINANCING [Autosaved].pptx
BENDORMOSES
 

Sql operators & functions 3

  • 1. Operators and Built-in Functions  
  • 2. Operators Operators are used to manipulate data using the select statement. Arithmetic Relational Logical Special String Built-in Functions Character Numeric Date Aggregate/Group Conversion General/Other  
  • 3. Arithmetic Operators Operators are +, -, *, /   SELECT * FROM EMP WHERE SAL + COMM > 3000; The above Example will select the employee(s) whose salary + commission is more than 3000. SELECT * FROM EMP WHERE SAL – COMM > 2000; The above example will select the employee(s) whose salary – commission is more than 2000;  SELECT * FROM EMP WHERE COMM > SAL * 10/100; The above example will select the employee(s) whose commission is more than 10% of their salary.
  • 4. Logical Operators AND (logical AND), OR (logical OR) and NOT (logical NOT). SELECT * FROM EMP WHERE JOB = ‘CLERK’ AND DEPTNO=20 ; The above example will select the employee(s) who is working in dept 10 and he should be a CLERK. In the above case, both the job and deptno should satisfy the given condition i.e., both the conditions should be true. SELECT ENAME FROM EMP WHERE JOB=’SALESMAN’ OR JOB=’ANALYST’; The above example will select the employee(s) whose JOB is either SALESMAN or ANALYST. SELECT * FROM EMP WHERE DEPTNO NOT IN (10, 20); The above example will select the employee(s) who are not working in department 10 and 20.
  • 5. Relational Operators = Equal to <>, !=,^= Not Equal to < Less than > Greater than >= Greater than or <= Less than or Equal to
  • 6. Examples for Relational Operators: (= , <>) SELECT * FROM EMP WHERE DEPTNO = 10;   The above example will select the employee(s) who are working in deptno 10;   SELECT * FROM EMP WHERE DEPTNO <> 10; The above example will select the employee(s) who are not working in deptno 10.    
  • 7. Example for > ,>=, <. <= SELECT * FROM EMP WHERE SAL > 3000 ; The above example will select the employee(s) who is getting salary from 3001 onwards. SELECT * FROM EMP WHERE SAL >= 3000 ;   The above example will select the employee(s) who is getting salary from 3000 onwards. SELECT * FROM EMP WHERE SAL < 2000 ;   The above example will select the employee(s) who is getting salary below 2000; SELECT * FROM EMP WHERE SAL <= 2000 ; The above example will select the employee(s) who is getting salary 2000 and less.
  • 8. Special Operators   LIKE, BETWEEN AND, IN, ANY and ALL   Examples: SELECT * FROM EMP WHERE ENAME LIKE ‘ALLEN’;  The above example will select the employee(s) whose name is exactly like ‘ ALLEN’. Even it will not fetch the employee whose name is ‘allen’ or ‘ Allen’ or ‘Allen’.   SELECT * FROM EMP WHERE SAL BETWEEN 1500 AND 3500 ;   The above example will select the employee(s) who is getting salary between 1500 and 3500; ANY, IN and ALL operators will be explained more in SUB-QUERIES.
  • 9. String Operators   % (percentage) _ (underscore) || (concatenation)   The above operators are used to compare the string values.  
  • 10. Examples: SELECT * FROM EMP WHERE ENAME LIKE ‘E%’; The above example will select the employee(s) who’s name starts with ‘E’ followed by any number of characters .   SELECT * FROM EMP WHERE ENAME LIKE ‘S_ _ _ _ _’; The above example which uses the _(underscore) after ‘S’, will fetch the employee(s) who’s name starts with ‘S’ and whose length of name is exactly five characters . SELECT ENAME||JOB||HIREDATE FROM EMP; The above example will list the ENAME, JOB, HIREDATE column values joined together without any space in between.  
  • 11. Built-in SQL functions SQL provides a number of predefined functions that can be called from within an SQL statement. It is used to manipulate data items.   Advantages of Functions   Functions can be used to perform complex calculations on data.   Functions can modify individual data items.   Functions can very easily manipulate output for group of rows.   Functions can alter date formats for display.
  • 12. Types of Functions   Ø       Character functions Ø       Arithmetic functions Ø       Date functions Ø Conversion functions Ø       Aggregate / Group functions
  • 13. Character Functions CHR Syntax: CHR(x) Purpose: Returns the character that has the value equivalent to x in the database character set. CHR and ASCII are opposite functions. CHR returns the character given the character number, and ASCII returns the character number given the character. Example: SELECT CHR(37) a, CHR(100) b, CHR(101) c from dual; Output: A B C - - - % d e
  • 14. What is DUAL? Dual is a small Oracle table created for testing functions or doing quick calculations which has one row and column. Since Oracle’s many functions work on both columns and literals. Some Oracle functions use just literals in these situations DUAL table can be used. Structure of Null table: Name Null? Type ----------------------------------------------------- -------- ----------------- DUMMY VARCHAR2(1) Select * from dual; D - X
  • 15. CONCAT   Syntax: CONCAT (String1, String 2)   Purpose Returns string1 concatenated with string2. This function is identical to the || operator.   Example:   SELECT CONCAT(‘Information ’, ‘ Technology’) “Computer” from dual;   Output: Computer ------------- Information Technology  
  • 16. INITCAP   Syntax: INITCAP( String )   Purpose: Returns string with the first character of each word capitalized and the remaining characters of each word in lowercase. Characters that are not letters are unaffected.   Example:   SELECT INITCAP (‘time is gold’) “Time” from dual;   Output: Speech ----------------------- Time is gold
  • 17. LOWER   Syntax: LOWER(String)   Purpose: Returns string with all characters in lowercase. Any characters that are not letters will not convert. If string has the CHAR datatype, the result is also CHAR. If string is VARCHAR2, the result is VARCHAR2.   Example:   SELECT LOWER (‘EVERYTHING IN LOWER CASE’) “lower” from dual;   Output: lower -------------- everything in lower case  
  • 18. UPPER   Syntax: UPPER(string)   Purpose Returns string with all letters in uppercase. If string has datatype CHAR, the return value is also CHAR. If string has datatype VARCHAR2, then the return value is VARCHAR2. Any Characters that are not letters are left intact in the returned value. Example: SELECT UPPER (‘print in uppercase’) “UPPER” FROM dual; Output: UPPER PRINT IN UPPERCASE
  • 19. LPAD Syntax: LPAD(String1, x [,string2]) Purpose : Returns string1 after padding string2 from left to length x. If string2 is less than x characters, it is duplicated as necessary. If string2 is more than x characters, only the first required x characters are used. If string2 is not specified, it defaults to a single blank for each space. Examples: SELECT LPAD (‘have a good day’,18) “First” from dual; Output: First ----- have a good day
  • 20. SELECT LPAD (‘have a good day’, 20, ‘XY’) “Demo” from dual;   Output: Demo XYXYXhave a good day   SELECT LPAD (‘have a good day’, 16, ’XY’) “Test” from dual;   Output: Test Xhave a good day
  • 21. RPAD   Syntax: RPAD(String1,x[,string2])   Purpose: Returns string1 padded on the right to length x with the characters in string2. If string2 is less than x characters, it is duplicated as necessary. If string2 is more than x characters, only the first x are used. If string2 is not specified, it defaults to a single blank.   Examples:   SELECT RPAD (‘Cricket’, 10, ‘!’) “First” from dual;   Output: First ---------- Cricket!!!  
  • 22. SELECT RPAD(‘Cricket’, 10, ‘AB’) “Second” from dual;   Output: Second ---------- CricketABA   SELECT RPAD ('Cricket', 3) &quot;Third&quot; from dual;   Output: Thi --- Cri
  • 23. RTRIM   Syntax: RTRIM(String1[,string2])   Purpose: Returns string1 with the rightmost characters appearing in string2 removed. String2 defaults to a single blank. The database will scan String1, starting from the rightmost position. When the first character not in String2 is encountered, the result is returned.   Examples: SELECT RTRIM(‘This is a string ’) “First” from dual; Output: First This is a string  
  • 24. SELECT RTRIM(‘This is a stringxxxxx’, ‘x’) “Second” from dual;   Output: Second ---------------- This is a string   SELECT RTRIM(‘This is a string as well’, ‘well’) “Third” from dual;   Output: Third -------------------- This is a string as
  • 25. TRIM This function can used instead of LTRIM and RTRIM   Example:   SELECT TRIM(‘ INDIA ‘) FROM DUAL;   Output: TRIM( ----- INDIA  
  • 26. REPLACE Syntax: REPLACE (String, search_str[, replace_str])   Purpose : Returns string with every occurrence of search_str replaced with replace_str. If replace_str is not specified, all occurrences of search_str are removed. Examples: SELECT REPLACE (‘This and That’, ‘Th’, ‘B’)”First” from dual;   Output: First Bis and Bat  
  • 27. SELECT REPLACE (‘This and That’, ‘Th’)”Second” from dual;   Output: Second ------------ is and at   SELECT REPLACE (‘This and That’, null) “Third” from dual;   Output: Third ------------ This and That
  • 28. SUBSTR   Syntax : SUBSTR ( string , a [, b ])   Purpose: Returns a portion of string starting at character a, b characters long . If a is 0, it is treated as 1(the beginning of the string). If b is positive, characters are returned counting from the left. If b is negative, characters are returning starting from the end of string, and counting from the right . If b is not present, it defaults to the entire string. If b is less than 1, NULL is returned. Examples: SELECT SUBSTR('He is a Good Boy', 2) &quot;First&quot; from dual; Output: First e is a Good Boy SELECT SUBSTR('He is a Good Boy', 2, 4) &quot;Second&quot; from dual Output: Second e is
  • 29. SELECT SUBSTR ('He is a Good Boy', -5) &quot;Third&quot; from dual   Output: Third ----- d Boy   SELECT SUBSTR ('He is a Good Boy', -5, 3) &quot;Four&quot; from dual   Output: Fou --- d B
  • 30. TRANSLATE Syntax: TRANSLATE ( string , from_str , to_str ) Purpose: Returns string with all occurrences of each character in from_str replaced by the corresponding character in to_str. If from_str is longer than to_str, any extra characters in from_str not in to_str are removed from string , since they have no corresponding characters. to_str cannot be empty. If any argument to TRANSLATE is null, the result is NULL as well.   Examples:   SELECT TRANSLATE(‘abcdefghij’,’abcdef’,’123456’) from dual;   Output: TRANSLATE( 123456ghij SELECT TRANSLATE (‘abcdefghij’, ‘abcdefghij’, ‘123456’) from dual;   Output: TRANSL 123456  
  • 31. SOUNDEX   Syntax: Soundex( string )   Purpose : Returns the phonetic representation of string. This is useful for comparing words that are spelled differently but sound alike. Example: SELECT ENAME FROM EMP WHERE SOUNDEX(ENAME) = SOUNDEX('SMEETH');   Output: ENAME ---------- SMITH
  • 32. Date Functions   The date functions take arguments of type DATE, except for the MONTHS_BETWEEN function, which returns a NUMBER, all of the functions return DATE values.  
  • 33. SYSDATE Syntax: SYSDATE Purpose: Returns the current date and time, of type DATE. Takes no arguments. When used in distributed SQL statement, SYSDATE returns the date and time of the local database. ( For instance if the current date is 4th May 2002) Example: SELECT SYSDATE FROM DUAL; Output: SYSDATE --------- 05-MAY-02
  • 34. ADD_MONTHS Syntax: ADD_MONTHS ( d,x ) Purpose: Returns the date d plus x months or d minus x . x can be any integer. Example: SELECT ADD_MONTHS(‘02-MAR-88’, 3), ADD_MONTHS(‘30-JAN- 00’, 1) FROM DUAL;   Output: ADD_MONTH ADD_MONTH ------------------ ------------ ------ 02-JUN-88 29-FEB-00
  • 35. MONTHS_BETWEEN Syntax: MONTHS_BETWEEN(DATE1,DATE2) Purpose: Returns the number of months between date1 and date2. If both date1 and date2 have the same day component, or if both are the last day of their respective months, then the result is an integer. Otherwise, the result will contain the fractional portion of a 31-day month. Example: SELECT MONTHS_BETWEEN('12-APR-71', '12-MAR-97') &quot;First&quot;, MONTHS_BETWEEN ('12-APR-71', '12-MAR-60') &quot;Second&quot; FROM dual;   Output: First Second ------- ---------- -311 132.67742
  • 36. LAST_DAY   Syntax: LAST_DAY( d) Purpose: Return the date of last day of the month that contains d. This function can be used to determine how many days are left in the current month. Example: SELECT LAST_DAY('12-APR-71') &quot;CURRENT&quot;, LAST_DAY('12-APR-71') - TO_DATE('12-APR-71') &quot;Days left&quot; FROM dual;   Output: Current Days Left ------- ---------- 30-APR-71 18
  • 37. NEXT_DAY Syntax: NEXT_DAY(d, string) Purpose : This function returns the date of next specified day of the week(string) after the d (date). Example: SELECT NEXT_DAY('07-MAY-02','MONDAY') FROM DUAL; Output: NEXT_DAY( --------- 13-MAY-02
  • 38. ROUND   Syntax: ROUND(d, [, format) Purpose : Returns the date d to the unit specified by format. If format is not specified, it defaults to 'DD', which rounds d to the nearest day. Example:   SELECT ROUND(TO_DATE(‘12-APR-71’), ‘MM’) &quot;Nearest Month&quot; FROM dual;   Output : Nearest Month ----------------- 01-APR-71   (1-15 it will round to the same month, 16 and after - next month)
  • 39. TRUNC   Syntax: TRUNC(d, [,format]) Purpose: Returns the date d truncated to the unit specified by format. If format is not specified, it defaults to 'DD', which truncates d to the nearest day. Example: SELECT TRUNC( FROM dual;   Output: First Day -------------- 01-JAN-71
  • 40. Date Arithmetic Applying the arithmetic operators to dates and numbers are described. When one date value is subtracted from another, the result is a number.   Examples of valid date arithmetic expressions follow:   Example 1: Adding to Date   SELECT SYSDATE, SYSDATE + 1 &quot;Tomorrow&quot; FROM dual;   Output: SYSDATE Tomorrow -------------- ------------- 13-NOV-95 14-NOV-95  
  • 41. Subtracting from Date Example 1: SELECT TO_DATE('12-APR-71 12:00:00', 'DD-MON-YY HH24:MI:SS') - TO_DATE(15-MAR-71 15:00 -MON-YY HH24:MI:SS') &quot;Difference&quot; FROM dual;   Output: Difference -------------- 27.875  
  • 42. Example 2:   SELECT TO_DATE('10-AUG-98') - TO_DATE('12-FEB-98') FROM DUAL;   Output: TO_DATE('10-AUG-98')-TO_DATE('12-FEB-98') -------------------------------------------------------------- 179  
  • 43. Conversion Functions   TO_NUMBER   Syntax: TO_NUMBER( string [, format [,nlsparams]])   Purpose: Converts the CHAR or VARCHAR2 string to a NUMBER value. If format is specified, string should correspond to number format. Example: SELECT TO_NUMBER('25') + TO_NUMBER('50') &quot;TOTAL&quot; FROM DUAL;   Output: TOTAL 75
  • 44. TO_CHAR (WITH NUMBERS)   Syntax: TO_CHAR( num, [,format[, nlsparams ]])   Purpose: Converts the NUMBER argument num to a VARCHAR2. If format not specified, the resultant string will have exactly as many characters as necessary to hold the significant digits of num. Example: SELECT TO_CHAR(123) FROM DUAL;   Output TO_ 123
  • 45. TO_CHAR (WITH DATE) Syntax: TO_CHAR(d,[,format [,nlsparams]]) Purpose: TO_CHAR can also be used for the conversion of dates values to a specified character format. TO_CHAR allows us to format the date in various different ways. Example 1: SELECT TO_CHAR(SYSDATE, ‘DAY DDSPTH MONTH YEAR') FROM DUAL; Output : TO_CHAR(SYSDATE,'DAYDDSPTHMONTHYEAR') --------------------------------------------------------------------- WEDNESDAY FOURTEENTH MARCH TWO THOUSAND ONE  
  • 46. Example 2: SELECT TO_CHAR(HIREDATE, 'DDTH MONTH YEAR') &quot;JOINING DATE&quot; FROM EMP WHERE EMPNO = 7788; Output: JOINING DATE ------------------------------------------------- 09TH DECEMBER TWENTY EIGHTY-TWO Example3: SELECT TO_CHAR(TO_DATE('14-MAR-01'), 'RM') FROM DUAL; Output: TO_C III RM – Roman Numeral Month 
  • 47. Group / Aggregate Functions
  • 48. Group / Aggregate Functions Group functions are those statistical functions, which gives information about a group of value taken as whole. The aggregate function produce a single value for an entire group or table. In all group functions, NULLs are ignored. These functions are valid in the select list of a query and the GROUP BY clause only.
  • 49. AVG Syntax: AVG([DISTINCT | ALL]col) Purpose: Returns the average of the column values.   Example:   SELECT AVG(sal) FROM EMP;
  • 50. COUNT Syntax : COUNT(*|[DISTINCT |ALL]col) Purpose : Count function determines the number of rows or non-NULL column values. If * is passed, then the total number of rows is returned.   Example 1: SELECT COUNT(*) FROM EMP; Example 2:   SELECT COUNT(deptno) FROM EMP; Example3:   SELECT COUNT(DISTINCT deptno) FROM EMP;
  • 51. MAX   Syntax: MAX([DISTINCT | ALL] coL) Purpose : Returns the maximum value of the select list item. Example 1: SELECT MAX(SAL) FROM EMP; Example 2:   SELECT MAX(LENGTH(ENAME)) FROM EMP; This example returns the length of the longest name in the EMP table:
  • 52. MIN   Syntax : MIN([DISTINCT | ALL] coL)   Purpose: Returns the maximum value of the select list item. Example: SELECT MIN(COMM) “MIN-COMM”, MIN(SAL) “MIN-SAL” FROM EMP;   Output: MIN-COMM MIN-SAL ----------------- ------------- 0 800
  • 53. SUM   Syntax : SUM([DISTINCT | ALL] Col)   Purpose: Returns the sum of the values for the select list item.   Example 1:   SELECT SUM(SAL) FROM EMP;  
  • 54. Other / General Functions DECODE Syntax: DECODE( base_expr, compare1, value1, compare2, value2, . . . default ) Purpose : The DECODE statement is similar to a series of nested IF-THEN-ELSE statements. The base_expr is compared to each of compare1, compare2 , etc., in sequence. If base_expr matches the i th compare item, the i th value is returned. If base_expr doesn't match any of the compare values, default is returned. Each compare value is evaluated in turn. If a match is found, the remaining compare values, if any, are not evaluated. A NULL base_expr is considered equivalent to a NULL compare value.  
  • 55. Example 1:   SELECT DECODE(10, 10, 'TEN', 20, 'TWENTY', 30, 'THIRTY') &quot;MATCH&quot; FROM DUAL;   Output: MAT TEN  
  • 56. Example 2:   SELECT DECODE(50, 10, ‘TEN’, 20, ‘TWENTY’, 30, ‘THIRTY’, ‘NEW VALUE’) FROM DUAL;   Output: DECODE(50 --------- NEW VALUE   Example 3:   SELECT DECODE(NULL, ‘A’, ‘ARUN’, NULL, ‘NOVALUE’, ‘B’, ‘BHARATH’) FROM DUAL;   Output: DECODE( ------- NOVALUE
  • 57. GREATEST Syntax : GREATEST (expr1[,expr2]…)   Purpose : Returns the greatest expression of its arguments. Each expression is implicitly converted to the type of expr1 before the comparisons are made. Example 1:   SELECT GREATEST (10, '7', -1) FROM dual;   Output: GREATEST (10, '7', -1) --------------------- 10   Example 2:   SELECT GREATEST(‘ASHWIN’, ‘SOFIA’) FROM DUAL;   Output: GREAT --------- SOFIA
  • 58. LEAST   Syntax : LEAST(expr1 [, expr2]…)   Purpose : This function returns the least value in the list of expressions. LEAST behaves similarly to GREATEST, in that all expressions are implicitly converted to the datatype of the first. Example 1:   SELECT LEAST (10, '7', -1) FROM dual; Output: LEAST(10,'7', -1) ---------------- -1   Example 2:   SELECT LEAST ('ASHWIN', 'SOFIA') FROM DUAL;   Output: LEAST( ------ ASHWIN
  • 59. NVL Syntax: NVL( expr1, expr2 ) Purpose: If expr1 is NULL, returns expr2; otherwise, returns expr1. The columns with NULL values are ignored in all of the group functions such as sum, Avg etc. The NULL function helps in substituting a value in place of a NULL.   Example: SELECT NVL (null, ‘this is a null value’) “NullTest” FROM DUAL; Output : NullTest --------------------- this is a null value   SELECT ENAME, SAL, COMM, SAL + COMM “GROSS SAL”, SAL + NVL (COMM, 0) “CORRECT SAL” FROM EMP;   (The above command will substitute 0 for commission where the commission is NULL).
  • 60. UID Syntax : UID   Purpose : Returns an integer that uniquely identifies the current database user. UID takes no arguments.   Example: This example shows a sample SQL*Plus session. SQL> Connect Scott/Tiger Connected. SQL> SELECT UID FROM dual; UID 8 SQL> connect system/manager Connected.   SQL> SELECT UID FROM dual; UID 5
  • 61. USER   Syntax : USER   Purpose : Returns a VARCHAR2 value containing the name of the current Oracle user. USER takes no arguments.   Example: This example shows a sample SQL*PLUS statements   SQL> connect Scott/Tiger   Connected. SQL> SELECT USER FROM dual; USER SCOTT SQL> Connect Sys/Change_on_install   Connected. SQL> SELECT USER FROM dual; USER SYS