PL/SQL single-row functions and group functions
A function is a program with zero or multiple parameters and a return value. Oracle has a series of built-in functions in SQL, which can be called SQL or PL/SQL statements. functions are mainly divided into two categories:
Single Row Function
Group functions
This article will discuss how to use single-row functions and use rules.
Single Row functions in SQL
SQL and PL/SQL contain many types of functions, including character, number, date, conversion, and hybrid functions. Therefore, these functions can be collectively called single-row functions. These functions can be used in clauses such as SELECT, WHERE, and order by. For example, the following example contains single-row functions such as TO_CHAR, UPPER, and SOUNDEX.
SELECT ename, TO_CHAR (hiredate, 'day, DD-Mon-YYYY ') FROM empWhere UPPER (ename) Like 'al %' order by soundex (ename)
Single-row functions can also be used in other statements, such as the SET clause of update, the VALUES clause of INSERT, And the WHERE clause of DELET. During the certification exam, pay special attention to using these functions in SELECT statements, so our attention is also concentrated in the SELECT statement.
NULL and single-row Functions
It is very difficult to understand NULL, and even a very experienced person is still confused about it. NULL indicates an unknown data or a NULL value. Any operand of the arithmetic operator is NULL, and the result is a NULL value. This rule is also applicable to many functions, only CONCAT, DECODE, DUMP, NVL, and REPLACE can return non-NULL values when the NULL parameter is called. Among these functions, NVL is the most important because it can directly process NULL values. NVL has two parameters: NVL (x1, x2), x1, and x2 expressions, if x1 is null, return X2; otherwise, return x1.
Let's take a look at the emp data table. It includes two items: salary and bonus. We need to calculate the total compensation.
Column name emp_id salary bonuskey type pk nulls/unique nn, u nnfk table datatype number numberlength 11.2 11.2
It is not simply to add up the salary and bonus. If a row is null, the result will be null. For example:
Update empset salary = (salary + bonus) * 1.1
In this statement, both the employee's salary and bonus will be updated to a new value, but if there is no bonus, that is, salary + null, the wrong conclusion will be drawn, in this case, the nvl function is used to exclude the impact of null values.
The correct statement is:
Update empset salary = (salary + nvl (bonus, 0) * 1.1
Single-line string functions
A single-line string function is used to manipulate string data. Most of them have one or more parameters, and most of them return strings.
ASCII ()
C1 is a string and returns the ASCII code of the first letter of c1. Its Inverse Function is CHR ()
Select ascii ('A') BIG_A, ASCII ('Z') BIG_z FROM empBIG_A BIG_z65 122
CHR (<I>) [NCHAR_CS]
I is a number. The function returns the characters in decimal format.
Select CHR (65), CHR (122), CHR (223) FROM empCHR65 CHR122 CHR223A z B
CONCAT (,)
C1 and c2 are strings. The function connects c2 to the end of c1. If c1 is null, c2. if c2 is null, c1 is returned. If c1 and c2 are both null, returns null. He and operator | the returned result is the same
Select concat ('slobo', 'svoboda') username from dualusernameslobo Syoboda
INITCAP ()
C1 is a string. The function returns the first letter of each word in upper case and other letters in lower case. Words are limited by spaces, control characters, and punctuation marks.
Select INITCAP ('Veni, vedi, vici') Ceasar from dualCeasarVeni, Vedi, vici
INSTR (, [, <I> [,])
C1 and c2 are strings, and I and j are integers. The function returns the position where c2 appears for the nth occurrence of c1, and searches for the position starting from the nth occurrence of c1. If no expected character is found, 0 is returned. If I is a negative number, the search proceeds from right to left, but the position is calculated from left to right, the default values of I and j are 1.
Select INSTR ('Mississippi ',' I ', 3,3) from dualINSTR ('Mississippi', 'I', 3,3) 11 select INSTR ('Mississippi ',' I ', -2, 3) from dualINSTR ('Mississippi ',' I ', 3, 3) 2
Limit B (, [, I [, j])
Like the INSTR () function, it only returns bytes. For a single byte, bytes B () equals to INSTR ()
LENGTH ()
C1 is a string and returns the length of c1. If c1 is null, null is returned.
Select LENGTH ('ipso facto') ergo from dualergo10
LENGTHb ()
Returns bytes like LENGTH.
Lower ()
Returns the lowercase character of c, which is often found in the where substring.
Select LOWER (colorname) from itemdetail where lower (colorname) LIKE '% white %' COLORNAMEWinterwhite
LPAD (, <I> [,])
C1 and c2 are strings and I is an integer. On the left side of c1, use the c2 string to supplement the length I, which can be repeated multiple times. If I is less than the length of c1, only the c1 characters that are as long as I are returned, and the others are truncated. The default value of c2 is single space. See RPAD.
Select LPAD (answer, 7, '') padded, answer unpadded from question; padded unpadded Yes YesNO NOMaybe maybe
LTRIM (,)
Remove the leftmost character from c1 so that the first character is not in c2. If there is no c2 character, c1 will not change.
Select LTRIM ('Mississippi ', 'mis') from dualLTRppi
RPAD (, <I> [,])
On the right side of c1, use the c2 string to supplement the length I, which can be repeated multiple times. If I is less than the length of c1, only the c1 characters that are as long as I are returned, and the others are truncated. The default value of c2 is a single space. Others are similar to LPAD.
RTRIM (,)
Remove the rightmost character from c1 so that the last character is not in c2. If there is no c2 character, c1 will not change.
REPLACE (, [,])
C1, c2, and c3 are strings. The function uses c3 instead of c2 that appears in c1 and returns the result.
Select REPLACE ('uptown', 'up', 'low') from dualREPLACEdowntown
STBSTR (, <I> [,])
C1 is a string, where I and j are integers. Starting from the I-bit of c1, a substring with the length of j is returned. If j is empty, it is returned until the end of the string.
Select SUBSTR ('message', 1, 4) from dualSUBSMess
SUBSTRB (, <I> [,])
It is roughly the same as SUBSTR, except that I and J are calculated in bytes.
SOUNDEX ()
Returns a word with the same pronunciation as c1.
Select SOUNDEX ('dawes') dawes SOUNDEX ('daws') daws, SOUNDEX ('dawson') from dualDawes Daws DawsonD200 D200 D250
TRANSLATE (,,)
Replace the characters in c1 with those in c2 with c3.
Select TRANSLATE ('fumble ', 'U', 'ar') test from dualTEXTramble
TRIM ([[] from c3)
Delete the first, last, or all of the c3 strings.
Select TRIM ('space padded') trim from dual TRIMspace padded
UPPER ()
Returns the uppercase value of c1, which is often in the where substring.
Select name from dual where UPPER (name) LIKE 'Ki % 'NAMEKING
Single-row numeric Functions
A single-row numeric function operates on numeric data and performs mathematical and arithmetic operations. All functions have numeric parameters and return numeric values. The operands and values of all trigonometric functions are radians rather than degrees. oracle does not provide built-in radians and angle conversion functions.
ABS ()
Returns the absolute value of n.
ACOS ()
Returns the number between-1 and 1 in the anti-Yuxuan function. N indicates radians
Select ACOS (-1) pi, ACOS (1) zero from dualPI ZERO3.14159265 0
ASIN ()
Returns-1 to 1, and n to indicate radians.
ATAN ()
Returns the arc tangent value of n. n indicates radians.
CEIL ()
Returns the smallest integer greater than or equal to n.
COS ()
Returns the remainder Xuan value of n, and n is a radian.
COSH ()
Returns the hyperbolic remainder of n, where n is a number.
Select COSH (<1.4>) FROM dualCOSH (1.4) 2.15089847
EXP ()
Returns the n power of e, e = 2.71828183.
FLOOR ()
Returns the largest integer less than or equal to N.
LN ()
Returns the natural logarithm of N. N must be greater than 0.
LOG (,)
Returns the base n2 logarithm of n1.
MOD ()
Returns the remainder of n1 divided by n2,
POWER (,)
Returns the n2 power of n1.
ROUND (,)
Return the value of n1 rounded to the right of the decimal point. The default value of n2 is 0. This is the nearest integer to the decimal point. If n2 is a negative number, it is rounded to the corresponding digit on the left of the decimal point, n2 must be an integer.
Select ROUND (12345,-2), ROUND (12345.54321, 2) FROM dualROUND (12345,-2) ROUND (12345.54321, 2) 12300 12345.54
SIGN ()
If n is negative,-1 is returned. If n is positive, 1 is returned. If n = 0, 0 is returned.
SIN ()
Returns the positive and negative values of n, and n is a radian.
SINH ()
Returns the hyperbolic Xuan value of n, which is radian.
SQRT ()
Returns the square root of n, and n is a radian.
TAN ()
Returns the tangent of n. n is a radian.
TANH ()
Returns the hyperbolic tangent of n. n is a radian.
TRUNC (,)
Return the n1 value from the ending point to the n2 decimal point. The default value of n2 is 0. When n2 is the default value, the ending point of n1 is an integer. If n2 is a negative value, it is truncated at the right of the decimal point.
Single Row date functions
A single-row date function operates on DATA types. The vast majority of DATA type parameters are available, and the vast majority of returned DATA types are also values.
ADD_MONTHS (, <I>)
Returns the result after date d plus I months. I can make any integer. If I is a decimal point, the database implicitly converts it to an integer, and the part after the decimal point is truncated.
LAST_DAY ()
Returns the last day of the month containing the date d.
MONTHS_BETWEEN (,)
Returns the number of months between d1 and d2. If the date of d1 and d2 is the same, or the last day of the month is used, an integer is returned, otherwise, the returned result contains a score.
NEW_TIME (,,)
D1 is a date data type. When the date and time in Zone tz1 are d, the date and time in Zone tz2. Tz1 and tz2 are strings.
NEXT_DAY (,)
Returns the first day of the condition given by dow after the date d. dow specifies a day in a week using the language given in the current session, and returns the same time component as the time component of d.
Select NEXT_DAY ('01-Jan-2000 ', 'monday') "1st Monday", NEXT_DAY ('01-Nov-2004', 'tuesday') + 7 "2nd Tuesday ") from dual; 1st Monday 2nd Tuesday03-Jan-2000 09-Nov-2004
ROUND ([,])
Round the date d in the format specified by fmt, and fmt is a string.
SYADATE
The function has no parameters. The current date and time are returned.
TRUNC ([,])
Returns the date d of the unit specified by fmt.
Single Row Conversion Function
The single-row conversion function is used to operate on multiple data types and convert data types.
CHARTORWID ()
C makes a string, and the function converts c to the RWID data type.
SELECT test_id from test_case where rowid = CHARTORWID ('aaaa0saacaaaaliaaa ')
CONVERT (, [,])
String at the end of c. dset and sset are two character sets. The function converts string c from the sset character set to the dset character set, and the sset is set to the database character set by default.
HEXTORAW ()
X is a hexadecimal string. The function converts hexadecimal x to the RAW data type.
RAWTOHEX ()
X is a RAW data string. The function converts the RAW data class to a hexadecimal data type.
ROWIDTOCHAR ()
The function converts the ROWID data type to the CHAR data type.
TO_CHAR ([[,)
X is a data or number data type. The function converts x to the char data type in the specified format of fmt. If x is the date nlsparm = NLS_DATE_LANGUAGE, the language used to control the returned month and day. If x is the number nlsparm = NLS_NUMERIC_CHARACTERS, it is used to specify the Separators for decimal places and kilobytes, as well as currency symbols.
NLS_NUMERIC_CHARACTERS = "dg", NLS_CURRENCY = "string"
TO_DATE ([,[,)
C Indicates a string, and fmt indicates a string in a special format. Returns the c language in the fmt Format. The nlsparm indicates the language used. The function converts string c to the date data type.
TO_MULTI_BYTE ()
C Represents a string, and the function converts the truncation character of c to multi-byte characters.
TO_NUMBER ([,[,)
C Indicates a string, fmt indicates a special string, and the function return value is displayed in the format specified by fmt. Nlsparm indicates the language, and the function returns numbers represented by c.
TO_SINGLE_BYTE ()
Converts multiple characters in string c into equivalent single-byte characters. This function is used only when the database character set contains single-byte and multi-byte characters at the same time.
Other single-row Functions
BFILENAME (
,)
Dir is a directory object, and file is a file name. The function returns an empty BFILE Location value indicator. The function is used to initialize the BFILE variable or BFILE column.
DECODE (, [, [])
X is an expression, m1 is a matching expression, and x is compared with m1. If m1 is equal to x, r1 is returned. Otherwise, x is compared with m2, and so on, m5 .... until a result is returned.
DUMP (, [, [, [,])
X is an expression or character. fmt indicates octal, decimal, hexadecimal, or single character. The function returns a value of the VARCHAR2 type that contains the internal representation of x. If n1 and n2 are specified, bytes starting from n1 with n2 will be returned.
EMPTY_BLOB ()
This function has no parameters. The function returns an empty BLOB location indicator. Function is used to initialize a BLOB variable or BLOB column.
EMPTY_CLOB ()
This function has no parameters. The function returns an empty CLOB location indicator. The function is used to initialize a CLOB variable or CLOB column.
GREATEST ()
Exp_list is a column expression that returns the largest expression. Each expression is implicitly converted to the Data Type of the first expression. If the first expression is any of the string data types, the returned result is of the varchar2 data type, and the comparison is of the non-padding space type.
LEAST ()
Exp_list is a column expression that returns the smallest expression. Each expression is implicitly converted to the Data Type of the first expression. If the first expression is any of the string data types, the returned result is of the varchar2 data type, and the comparison is of the non-padding space type.
UID
This function has no parameters and returns an integer that uniquely identifies the current database user.
USER
Returns the username of the current user.
USERENV ()
Returns information about the current session based on opt. The optional value of opt is:
SYSDBA role response in ISDBA session, returns TRUE
SESSIONID return Audit Session identifier ENTRYID return available audit item identifier
After the INSTANCE is connected to the session, the INSTANCE identifier is returned. This value is only used when the Parallel server is running and multiple instances exist.
LANGUAGE returns the character set of the LANGUAGE, region, and database.
LANG returns the ISO abbreviation of the language name.
TERMINAL is the identifier of the operating system returned by the TERMINAL or computer used by the current session.
VSIZE ()
X is an expression. Returns the number of bytes in x.
Group functions in SQL
A group function is also called a set function. It returns a single result based on multiple rows. The exact number of rows cannot be determined unless the query is executed and all results are included. Different from a single-row function, all rows are known during parsing. Due to this difference, the requirements and behaviors of group functions and single-row functions are slightly different.
Group (multiple rows) Function
Compared with single-row functions, oracle provides a wide range of group-based, multi-row functions. These functions can be used in select or select having clauses. They are often used together with group by when used for select substrings.
AVG ([{DISYINCT | ALL}])
Returns the average value of a value. The default value is ALL.
Select avg (sal), AVG (ALL sal), AVG (DISTINCT sal) FROM scott. empAVG (SAL) AVG (all sal) AVG (distinct sal) 1877.94118 1877.94118 1916.071413
COUNT ({* | DISTINCT | ALL })
Returns the number of rows in the query. The default value is ALL. * indicates that ALL rows are returned.
MAX ([{DISTINCT | ALL}])
Returns the maximum value of the selected list item. If x is a string DATA type, a VARCHAR2 DATA type is returned. If X is a DATA type, a date is returned. If X is a numeric DATA type, returns a number. Note that distinct and all do not work. The maximum value must be the same as the two settings.
MIN ([{DISTINCT | ALL}])
Returns the minimum value of the selected list.
STDDEV ([{DISTINCT | ALL}])
Returns the standard deviation of the selected item list. The so-called standard deviation is the square root of the variance.
SUM ([{DISTINCT | ALL}])
Returns the total number of items in the selected list.
VARIANCE ([{DISTINCT | ALL}])
Returns the statistical variance of the selected items.
GROUP
As the question implies, a GROUP function is used to operate data that has already been divided into groups. We tell the database how to GROUP or classify data using group, when we use GROUP functions in the SELECT clause of the SELECT statement, we must place grouping or extraordinary series in the group BY clause. If we do not use GROUP by for special processing, the default classification is to set the entire result to a class.
Select stat, counter (*) zip_count from zip_codes group by state; ST ZIP_COUNT -- --------- AK 360AL 1212AR 1309AZ 768CA 3982
In this example, we use the state field for classification. If we want to sort the results BY zip_codes, we can use the order by statement. The order by clause can use columns or group functions.
Select stat, counter (*) zip_count from zip_codes group by state order by count (*) DESC; st count (*) -- -------- NY 4312 PA 4297TX 4123CA 3982
Use HAVING clause to restrict grouped data
Now you know that you can use the primary function in the SELECT statement and order by clause of the query. Group functions can only be used in two substrings. Group functions cannot be used in WHERE substrings, for example, the following query is incorrect:
Error SELECT sales_clerk, SUN (sale_amount) FROM gross_sales WHERE sales_dept = 'outline' and sum (sale_amount)> 10000 group by sales_clerk
In this statement, the database does not know what SUM () is. When we need to instruct the database to group rows and then limit the output of rows after the grouping, the correct method is to use the HAVING statement:
SELECT sales_clerk, SUN (sale_amount) FROM gross_sales WHERE sales_dept = 'outline' group by sales_clerkHAVING SUM (sale_amount)> 10000;
Nested Functions
Functions can be nested. The output of a function can be the input of another function. The operands have an inherited execution process. However, the priority of a function is only based on the position, and the function follows the principle from inside to outside, from left to right. Nested technology is generally used for functions such as DECODE that can be used to logically determine the statement IF... THEN... ELSE.