Reguler Functions in SQL
Reguler Functions in SQL
Numeric Functions
Numeric functions accept numeric input and return numeric values. Most numeric functions that
return NUMBER values that are accurate to 38 decimal digits. The transcendental functions COS,
COSH, EXP, LN, LOG, SIN, SINH, SQRT, TAN, and TANH are accurate to 36 decimal digits. The
transcendental
COUNT The COUNT function has three formats: SELECT * FROM EMPLOYEES; ANS :-
COUNT ( * DISTINCT ALL • COUNT(*) TOTAL 107 ROW
SELECT COUNT(*) FROM EMPLOYEES;
Expr ) • COUNT(expr) ANS :- 107
OVER ( analytic_clause ) • COUNT(DISTINCT expr) SELECT COUNT(*) FROM EMPLOYEES
COUNT(*) returns the number of rows in a table WHERE DEPARTMENT_ID =50; ANS :- 45
that satisfy the criteria of the SELECT statement, SELECT COUNT(DEPARTMENT_ID) FROM
EMPLOYEES; ANS :- 106 AS 1 IS NULL
including duplicate rows and rows containing null
SELECT
values in any of the columns. COUNT(NVL(DEPARTMENT_ID,8)) FROM
EMPLOYEES ; ANS :- 107 INCLUDING 1
If a WHERE clause is included in the SELECT NULL NULL
statement, COUNT(*) returns the number of rows SELECT COUNT(DEPARTMENT_ID) FROM
EMPLOYEES WHERE DEPARTMENT_ID
that satisfy the condition in the WHERE clause. =50; ANS :- 45
SELECT COUNT(DISTINCT
In contrast, COUNT(expr) returns the number of DEPARTMENT_ID) FROM EMPLOYEES;
non-null values that are in the column identified by ANS :- 11
SELECT COUNT(DISTINCT
expr. DEPARTMENT_ID) FROM EMPLOYEES
COUNT(DISTINCT expr) returns the number of WHERE DEPARTMENT_ID=50; ANS :- 1
unique, non-null values that are in the column SELECT
identified by expr. COUNT(NVL(COMMISSION_PCT,9))
FROM EMPLOYEES; ANS :- 107 WITH
COUNT(DISTINCT expr) returns the number of NULL
distinct non-null values of expr. SELECT COUNT(1) FROM DUAL; --
ANS=>1
SELECT COUNT(10) FROM EMP; --
ANS=>14
SELECT COUNT(10) FROM DUAL; --
ANS=>1
SELECT COUNT(2) FROM EMP ; --
ANS=>14
MAX MAX ( MAX returns maximum value of expr. You can SELECT MAX(salary) "Maximum" FROM
employees; --ANS=> 2400
DISTINCT ALL expr ) use it as an aggregate or analytic function.
OVER ( nalytic_clause)
MEDIAN MEDIAN is an inverse distribution function SELECT DEPARTMENT_ID,
MEDIAN ( expr ) MEDIAN(SALARY) FROM EMPLOYEES
that assumes a continuous distribution model. It GROUP BY DEPARTMENT_ID;
OVER ( takes a numeric or datetime value and returns the DEPARTMENT_ID MEDIAN(SALARY)
query_partition_clause ) middle value or an interpolated value that would ------------- --------------
be the middle value once the values are sorted. 10 4400
20 9500
Nulls are ignored in the calculation. 30 2850
If you specify only expr, then the function returns 40 6500
the same datatype as the numeric datatype of the 50 3100
argument. if you specify the OVER clause, then 60 4800
70 10000
Oracle Database determines the argument with the 80 8900
highest numeric precedence, implicitly converts the 90 17000
remaining arguments to that datatype, and returns 100 8000
that datatype. 110 10150
7000
MIN MIN returns minimum value of expr. You can SELECT MIN(HIRE_DATE) "Earliest"
MIN ( DISTINCT ALL FROM EMPLOYEES; --ANS=>17-JUN-87
use it as an aggregate or analytic function.
expr )
OVER ( nalytic_clause )
STDDEV STDDEV returns the sample standard deviation of SELECT STDDEV OVER (SALARY)
"Deviation" FROM
STDDEV ( DISTINCT expr, a set of numbers. You can use it as both an EMPLOYEES;Deviation
ALL expr ) aggregate and analytic function. It differs from ----------
OVER ( analytic_clause ) STDDEV_SAMP in that STDDEV returns zero 3909.36575
when it has only 1 row of input data, whereas
STDDEV_SAMP returns null.
SUM SUM returns the sum of values of expr. You SELECT SUM(salary) "Total" FROM
employees; --ANS=>691400
SUM ( DISTINCT ALL can use it as an aggregate or analytic function.
expr )
OVER ( analytic_clause )
VARIANCE VARIANCE returns the variance of expr. You can SELECT VARIANCE(salary)
VARIANCE ( DISTINCT "Variance" FROM employees; --
use it as an aggregate or analytic function. ANS=>15283140.5
ALL Oracle Database calculates the variance of
expr ) OVER ( expr as follows:
analytic_clause ) ■ 0 if the number of rows in expr = 1
■ VAR_SAMP if the number of rows in expr > 1
If you specify DISTINCT, then you can specify
only the query_partition_clause of the
analytic_clause. The order_by_clause and
windowing_clause are not allowed.
UPPER UPPER returns char, with all letters uppercase. SELECT UPPER('the soap')
UPPER(column|expression) "Capitals" FROM DUAL;
Converts alpha character values to uppercase SELECT UPPER(ENAME) FROM EMP;
LTRIM LTRIM removes from the left end of char all of SELECT LTRIM('ABCD','B') FROM
LTRIM ( char , set ) the characters contained in set. If you do not EMP;
specify set, it defaults to a single blank. If char is a
character literal, then you must enclose it in single
quotes. Oracle Database begins scanning char
from its first character and removes all characters
that appear in set until reaching a character not in
set and then returns the result.
RTRIM RTRIM removes from the right end of char all of SELECT RTRIM('ABCD','B') FROM
RTRIM ( char , set ) the characters that appear in set. This function is EMP;
useful for formatting the output of a query.
LENGTH The LENGTH functions return the length of char. SELECT LENGTH('CANDIDE') "Length
in characters" FROM DUAL;--
LENGTH LENGTH calculates length using characters as ANS=>7
LENGTHB defined by the input character set. LENGTHB SELECT LENGTHB (ENAME) "Length in
LENGTHC LENGTH2 uses bytes instead of characters. LENGTHC bytes"FROM EMP;--ANS=> 14BYTE
LENGTH4 ( char ) uses Unicode complete characters. LENGTH2
uses UCS2 code points. LENGTH4 uses UCS4
code points.
char can be any of the datatypes CHAR,
VARCHAR2, NCHAR, NVARCHAR2,
NCLOB. The return value is of datatype
NUMBER. If char has datatype CHAR,
then the length includes all trailing blanks. If char
is null, then this function returns null.
Restriction on LENGTHB The LENGTHB
function is supported for single- byte LOBs only.
It cannot be used with CLOB and NCLOB data in a
multibyte character set.
DATE FUNCTION
Datetime functions operate on date (DATE), timestamp (TIMESTAMP, TIMESTAMP WITH TIME
ZONE, and TIMESTAMP WITH LOCAL TIME ZONE), and interval (INTERVAL DAY TO SECOND,
INTERVAL YEAR TO MONTH) values. Some of the datetime functions were designed for the Oracle
DATE datatype (ADD_MONTHS, CURRENT_DATE, LAST_DAY, NEW_TIME, and NEXT_DAY). If you
provide a timestamp value as their argument, Oracle Database internally converts the input type to a
DATE value and returns a DATE value. The exceptions are the MONTHS_BETWEEN function, which
returns a number, and the ROUND and TRUNC functions, which do not accept timestamp or interval
values at all. The remaining datetime functions were designed to accept any of the three types of data
(date, timestamp, and interval) and to return a value of one of these types. The datetime functions
are:
Operation Result Description
date + number Date Adds a number of days to a date
date – number Date Subtracts a number of days from a date
date – date Number of days Subtracts one date from another
date + number/24 Date Adds a number of hours to a date
CONVERSION FUNCTIONS
Conversion functions convert a value from one datatype to another. Generally, the form of the
function names follows the convention datatype TO datatype. The first datatype is the input
datatype. The second datatype is the output datatype. The SQL conversion functions are
Element Description
SCC or CC Century; server prefixes B.C. date with -
Years in dates YYYY or SYYYY Year; server prefixes B.C. date with -
YYY or YY or Y Last three, two, or one digits of year
Y,YYY Year with comma in this position
IYYY, IYY, IY, I Four-, three-, two-, or one-digit year based on the ISO
standard
SYEAR or YEAR Year spelled out; server prefixes B.C. date with -
BC or AD Indicates B.C. or A.D. year
B.C. or A.D. Indicates B.C. or A.D. year using periods
Q Quarter of year
MM Month: two-digit value
MONTH Name of month padded with blanks to length of nine
characters
MON Name of month, three-letter abbreviation
RM Roman numeral month
WW or W Week of year or month
DDD or DD or D Day of year, month, or week
DAY Name of day padded with blanks to a length of nine
characters
DY Name of day; three-letter abbreviation
J Julian day; the number of days since December 31,
4713
B.C.
AM or PM Meridian indicator
A.M. or P.M. Meridian indicator with periods
HH or HH12 or HH24 Hour of day, or hour (1–12), or hour (0–23)
MI Minute (0–59)
SS Second (0–59)
SSSSS Seconds past midnight (0–86399)
/ . , Punctuation is reproduced in the result.
“of the” Quoted string is reproduced in the result.
TH Ordinal number (for example, DDTH for 4TH)
SP Spelled-out number (for example, DDSP for FOUR)
SPTH or THSP Spelled-out ordinal numbers (for example, DDSPTH for
FOURTH)
Time elements format the time portion of the date:
HH24:MI:SS AM 15:45:32 PM
Add character strings by enclosing them in double quotation marks:
DD "of" MONTH 12 of OCTOBER
Number suffixes spell out numbers:
ddspth fourteenth
Element Description Example Result
9 Numeric position (number of 9s 999999 1234
determine display width)
0 Display leading zeros 099999 001234
$ Floating dollar sign $999999 $1234
L Floating local currency symbol L999999 FF1234
D Returns in the specified position the 99D99 99.99
decimal character. The default is a
period (.).
. Decimal point in position specified 999999.99 1234.00
G Returns the group separator in the 9,999 9G999
specified position. You can specify
multiple group separators in a
number format model.
, Comma in position specified 999,999 1,234
MI Minus signs to right (negative 999999MI 1234-
values)
PR Parenthesize negative numbers 999999PR <1234>
EEEE Scientific notation (format must 99.999EEEE 1.234E+03
specify four Es)
U Returns in the specified position the U9999 €1234
"Euro" (or other) dual currency
V Multiply by 10 n times (n = number 9999V99 123400
of 9s after V)
S Returns the negative or positive S9999 -1234 or
value +1234
B Display zero values as blank, not 0 B9999.99 1234.00
0–49 50–99
If two digits The return date is in The return date is in
of the 0–49 the current century the century before
current the current one
year are: The return date is in The return date is in
50–99 the century after the current century
the current one
Current Year Specified Date RR Format YY Format
1995 27-OCT-95 1995 1995
1995 27-OCT-17 2017 1917
2001 27-OCT-17 2017 2017
2001 27-OCT-95 1995 2095
TRANSLATE ... USING.. TRANSLATE ... USING converts char into the CREATE TABLE translate_tab
(char_col VARCHAR2(100),
USINGTRANSLATE ( char character set specified for conversions between nchar_col NVARCHAR2(50));
USING CHAR_CS the database character set and the national INSERT INTO translate_tab SELECT
NCHAR_CS ) character set. NULL, translated_name FROM
product_descriptions WHERE
product_id = 3501;
NULL-RELATED FUNCTIONS
The NULL-related functions facilitate null handling. The NULL-related functions are:
The Oracle DECODE function allows you to add the procedural if-then-else logic to the query. In
the following example, the Oracle DECODE function compares the first argument (1) with the
second argument (1). Because they are equal, the function returns the second argument which is
the string One.
The following example is slightly different from the one above. The query returns a null value
because one does not equal two.
If you want to specify a default value when the first argument is not equal to the second one, you
append the default value to the argument list as shown below:
SELECT
DECODE ( REGION, 'N','North',
'S','South',
'E','East',
'W','West',
'UNKNOWN' )
FROM CUSTOMER;
What if you want to compare the first argument with a list of arguments? See the following
example:
In this example, the function compares the first argument (2) with the second one. If the first
argument equal the second one, the function returns the third argument (One). Otherwise, it
compares the first argument with the fourth argument (2). If they are equal, the function returns the
fifth argument (Two).
It works like the following if-then-els if statement:
IF 2 = 1 THEN
RETURN 'One';
ELSIF 2 = 2 THEN RETURN 'Two';
END IF;
If you want to specify a default value when the function does not find any match, you do it as follows:
SELECT DECODE (3, 1, 'One', 2, 'Two', 'Not one or two') FROM dual;
SELECT category_name,
SUM (DECODE (GREATEST (list_price, 0), LEAST (list_price, 1000), 1, 0)) "< 1000",
SUM (DECODE (GREATEST (list_price, 1001), LEAST (list_price, 2000), 1, 0)) "1001-2000",
SUM (DECODE (GREATEST (list_price, 2001), LEAST (list_price, 3000), 1, 0)) "2001-3000",
SUM (DECODE (GREATEST (list_price, 3001), LEAST (list_price, 8999), 1, 0)) "3001-8999"
FROM products INNER JOIN product_categories USING (category_id) GROUP BY category_name;
Here is the output: