[Oracle] Oracle Series 9--Oracle Common Functions

Review of past issues

Preface

Oracle is a relational database management system that provides many built-in functions so that users can process data more easily.

1. String functions

(1)lengthb/length

Calculate string length

  • lengthb is the length of bytes (Byte, 1Byte=8bit)
  • length is obtained by character length
select lengthb('中') from dual;
select length('中') from dual;

Under ZHS16GBK, lengthb('中') is 2 bytes, length('中') is 1 (character), that is, one character occupies two bytes

CHAR(19) stored in the database represents 19 bytes.

(2)SUBSTR

SUBSTR is used to intercept substrings of strings. It should be noted that the subscripts of strings in Oracle database start from 1 instead of 0. The syntax of this function is as follows:

SUBSTR( string, start [, length] )
  • string is the string to be intercepted
  • start is the position where you want to start intercepting
  • length is the length of the substring to be intercepted (optional)

e.g

select substr('abcdefg',0,3) from dual;  

output

abc

select substr('abcdefg',1,3) from dual;  

output

abc

select substr('abcdefg',2,3) from dual;   

output

bcd

select substr('abcdefg',-3,3) from dual;    

output

efg

(3)INSTR

INSTR searches for the specified character in a string and returns the position where the specified character is found. The syntax of this function is as follows:

INSTR( string, substring [, start_position [, occurrence ]] )
  • string is the string to search for
  • substring is the substring to be found
  • start_position is the position to start the search (optional)
  • occurrence is the number of occurrences of the substring to be found (optional)
    eg
Select instr('oracle training','ai') From dual;  

output

10

(4)CONCAT

CONCAT concatenates two strings

e.g

SELECT CONCAT('Hello ', 'World', '!') FROM dual;

output

Hello World!

Update specified columns as required:

Update t_skzy Set website=concat('http://',website) Where website Not Like 'http%' And website Like '%.%'

(5)REPLACE

REPLACE is used to replace a specified substring of a string. The syntax of this function is as follows:

REPLACE( string, substring1 [, substring2] )
  • string is the string to replace the substring
  • substring1 is the substring to be replaced
  • substring2 is the string used to replace substring1 (optional)

e.g

SELECT REPLACE('Hello World!', 'Hello', 'Goodbye') FROM dual;

Output:

“Goodbye World!”

(6)TRIM, LTRIM, RTRIM

TRIM: remove spaces or specified characters from a string

The syntax is as follows:

TRIM([leading|trailing|both] [trim_character] FROM string)

leading|trailing|both: Optional parameter, used to specify to remove spaces from the string or specify whether the characters are in front, behind or on both sides of the string. The default is both.
trim_character: optional parameter, used to specify the character to be removed, the default is a space in the string.
string: Required parameter, a string to remove spaces or specified characters.
LTRIM: Remove spaces or specified characters on the left side of the string.

The syntax is as follows:

LTRIM([trim_character] FROM string)

trim_character: optional parameter, used to specify the character to be removed, the default is a space in the string.
string: Required parameter, a string to remove spaces or specified characters.
e.g.

Select ltrim('trimtest ltrim ','trim') From dual  

output

test ltrim

RTRIM: Remove spaces or specified characters on the right side of the string.

The syntax is as follows:

RTRIM([trim_character] FROM string)

trim_character: optional parameter, used to specify the character to be removed, the default is a space in the string.
string: Required parameter, a string to remove spaces or specified characters.

(7)ASCII

ASCII returns the ASCII code value of the first character in the given string.

e.g

SELECT ASCII('A') FROM dual;

output

65

(8)NVL

NVL( string1, replace_with)

If string1 is NULL, the NVL function returns the value of replace_with, otherwise it returns the value of string1.

For example, the following query will return a result that contains the employee's job title and department name, or "Unknown Department" if the employee's department is empty:

SELECT job_id, NVL(department_name, 'Unknown Department') 
FROM employees e LEFT JOIN departments d ON e.department_id = d.department_id;

(9)INITCAP,LOWER,UPPER

  • INITCAP changes the first letter of the string to uppercase
  • LOWER Lowercase all letters in the string
  • UPPER capitalizes all letters in a string

2. Mathematical functions

(1) ROUND

The ROUND function is used to round a number to a specified number of decimal places. For example, round the number 3.1415926 to two decimal places:

SELECT ROUND(3.1415926, 2) AS RoundedNumber FROM dual;

output

3.14

(2)TRUNK

The TRUNC function is used to truncate a number to a specified number of decimal places. For example, truncate the number 3.1415926 to two decimal places:

SELECT TRUNC(3.1415926, 2) AS TruncatedNumber FROM dual;

output

3.14

(3)ABS

The ABS function is used to calculate the absolute value of a number. For example, calculate the absolute value of the number -10:

SELECT ABS(-10) AS AbsoluteValue FROM dual;

output

10

(4)POWER

The POWER function is used to calculate the power of a number. For example, calculate 2 raised to the third power:

SELECT POWER(2, 3) AS PowerValue FROM dual;

output

8

(5)MOD

MOD takes the modulo operation and returns the remainder of the division of two numbers.

e.g

SELECT MOD(5, 2) FROM dual;

output

1

(6) Others

CEIL: Returns the smallest integer greater than the input value.
FLOOR: Returns the largest integer smaller than the input value.
MOD: Returns the remainder of the division of two numbers.

3. Date function

(1)CURRENT_DATE

CURRENT_DATE is a SQL standard function that returns the current date (without time) and can be used in SELECT statements. For example:

SELECT CURRENT_DATE FROM DUAL; 

Returns the current date in the format YYYY-MM-DD.

(2)SYSDATE

SYSDATE is Oracle's system function that returns the current date and time (the date and time in the time zone of the database server, not the client's time zone), including date and time accurate to seconds. For example, get the current date and time:

SELECT SYSDATE AS CurrentDateTime FROM dual;

Returns the current date and time in the format YYYY-MM-DD HH:MI:SS.

(2)ADD_MONTHS function

The ADD_MONTHS function is used to add a specified number of months to a date. For example, add 3 months to the current date:

SELECT ADD_MONTHS(SYSDATE, 3) AS FutureDate FROM dual;

(3) MONTHS_BETWEEN function

The MONTHS_BETWEEN function is used to calculate the number of months between two dates. For example, calculate the number of months between two dates:

SELECT MONTHS_BETWEEN('01-JAN-2022', '01-JAN-2021') AS MonthDifference FROM dual;

output

12

(4)TO_CHAR/TO_DATE

The TO_CHAR function can convert date data into a string.
The TO_DATE function can convert string data into a date data
. eg

select to_char(current_date,'yyyy-mm-dd hh24:mi:ss') from dual;
select to_date('1999/01/01','yyyy/mm/dd') from dual;

4. Aggregation functions

Aggregation functions are used to perform aggregate calculations on data, such as sums, averages, maximum values, minimum values, etc. Focus functions cannot be used as conditions in where clauses and need to be used together with having and group

(1)COUNT

The COUNT function is used to count the number of rows in the result set returned by a table or a query statement. If the DISTINCT keyword is specified, deduplicated rows are included in the count.

For example, a query containing the total number of employees:

SELECT COUNT(*) FROM employees;

(2)SUM

The SUM function is used to calculate the sum of the values ​​of a column in a result set returned by a table or a query statement.

For example, query the total monthly salary of employees:

SELECT SUM(salary) FROM employees;

(3)AVG

The AVG function is used to calculate the numerical average of a column in the result set returned by a certain table or a query statement. Its syntax is as follows:

For example, query the average monthly salary of employees:

SELECT AVG(salary) FROM employees;

(4)MAX/MIN

MAX/MIN are used to calculate the maximum or minimum value of a column in the result set returned by a table or a query statement respectively.

For example, the query contains the highest monthly salary of employees:

SELECT MAX(salary) FROM employees;

5. Others

(1)DECODE

DECODE: The function is used to return different values ​​according to different conditions. Its syntax is as follows:

DECODE(value, if1, then1, if2,then2, if3,then3, . . . else )

When each value is tested, if value is if1, the result of the Decode function is then1; if value is equal to if2, the result of the Decode function is then2; and so on. If the value result is not equal to any of the given pairs, the Decode result returns else. Multiple if/then pairs can be given.

For example, the employee information table contains birth year and state name, and it is necessary to count the number of people in different years and different continents.
Insert image description here

That is to form a statistical table in the following form:

Insert image description here

Select csrq 年份,
sum(decode(zm,'大洋洲',cou)) 大洋洲,
sum(decode(zm,'欧洲',cou)) 欧洲,
sum(decode(zm,'亚洲',cou)) 亚洲,
sum(decode(zm,'非洲',cou)) 非洲,
sum(decode(zm,'美洲',cou)) 美洲 From (
select t.zm,substr(csrq,1,4) csrq,Count(*) cou from employee t Group By t.zm,substr(csrq,1,4)) Group By csrq Order By csrq

(2)CASE

CASE returns different values ​​based on specified conditions. This function is similar to DECODE, but it is more flexible and can be used nested. Its syntax is as follows:

CASE expression
  WHEN value1 THEN result1
  [WHEN value2 THEN result2 ...]
  [ELSE default]
END

expression is the value to be compared
value1, value2, etc. are the conditions to be compared
result1, result2, etc. are the corresponding return values ​​(if expression is equal to a certain value, the corresponding result is returned)
default is an optional option, indicating that when expression is equal to The default value to be returned when all values ​​are not equal.
For example, the SQL statement to implement the aforementioned functions is as follows:

Select substr(csrq,1,4) 出生年份, 
Sum(Case When zm='大洋洲' Then 1 else 0 End) 大洋洲,
Sum(Case When zm='欧洲' Then 1 Else 0 End) 欧洲,
Sum(Case When zm='亚洲' Then 1 Else 0 End) 亚洲,
Sum(Case When zm='非洲' Then 1 Else 0 End) 非洲,
Sum(Case When zm='美洲' Then 1 Else 0 End) 美洲
From employee Group By substr(csrq,1,4) Order By 出生年份

(3)ROLLUP/CUBE

ROLLUP is an extension of the GROUP BY clause that returns subtotal records for each group and total records for all groups.
CUBE is also an extension of the GROUP BY clause, which can return subtotal records for each column combination and add total records at the end.
For example, a statistical table of the following form is formed:

Insert image description here

Select 年份,Sum(大洋洲) 大洋洲,Sum(欧洲) 欧洲,Sum(亚洲) 亚洲,Sum(非洲) 非洲,Sum(美洲) 美洲 From(
Select csrq 年份,
sum(decode(zm,'大洋洲',cou)) 大洋洲,
sum(decode(zm,'欧洲',cou)) 欧洲,
sum(decode(zm,'亚洲',cou)) 亚洲,
sum(decode(zm,'非洲',cou)) 非洲,
sum(decode(zm,'美洲',cou)) 美洲 From (
select t.zm,substr(csrq,1,4) csrq,Count(*) cou from employee t Group By t.zm,substr(csrq,1,4)) Group By csrq)
Group By Rollup(年份) Order By 年份

(4)MD5

DBMS_OBFUSCATION_TOOLKIT.MD5 is an MD5-encoded data packet function. This function can only be called directly in the package and cannot be directly applied to the SELECT statement.

The string returned by DBMS_OBFUSCATION_TOOLKIT.MD5 is of RAW type. To be displayed correctly, it needs to be converted by Utl_Raw.Cast_To_Raw:

CREATE OR REPLACE Function MD5(passwd Varchar2)
Return Varchar
Is
md5_output Varchar2(32);
Begin
md5_output:=utl_raw.cast_to_raw(DBMS_OBFUSCATION_TOOLKIT.MD5(INPUT_STRING=>passwd));
Return md5_output;
End;

(5)CAST

The CAST function is used to convert one data type to another data type.

Convert a string to numeric data:

SELECT CAST('123' AS NUMBER) FROM dual;

Convert a date string to date type:

SELECT CAST('2022-04-21' AS DATE) FROM dual;

(6) Query Blob/Clob type fields

DBMS_LOB is a package provided by Oracle database for operating large object (LOB) data. Among them, LOB includes four types: CLOB, NCLOB, BLOB and BFILE.

The DBMS_LOB package provides a series of subroutines that can be used to read, write, truncate, copy, compare and other operations on LOB objects:

DBMS_LOB.READ: used to read data from LOB objects;
DBMS_LOB.WRITE: used to write data to LOB objects;
DBMS_LOB.TRIM: used to truncate data in LOB objects;
DBMS_LOB.COPY: used to copy LOB objects The data in the LOB object is copied to another LOB object;
DBMS_LOB.COMPARE: used to compare whether the data in the two LOB objects are the same.
The DBMS_LOB package has several built-in functions:

dbms_lob.append: Append the LOB value
dbms_lob.substr: Intercept the LOB value
dbms_lob.instr: Find the string position in the LOB value
dbms_lob.getlength: Query the length of the Blob/Clob type field
eg

Select * From table_name Where dbms_lob.instr(Column,utl_raw.cast_to_raw('内容',1,1))>0;

Guess you like

Origin blog.csdn.net/u011397981/article/details/133279884