How to extract and sort a string in Oracle?
To extract and sort an Oracle string, you can use the SUBSTR function and ORDER BY clause.
Firstly, use the SUBSTR function to extract a portion of the string. The syntax for the SUBSTR function is:
SUBSTR(字符串, 起始位置, 截取长度)
Among them, the string is the substring to be taken, the starting position is the position where the extraction should begin, and the extraction length is the number of characters to be extracted.
Next, sort the truncated strings using the ORDER BY clause. The syntax for the ORDER BY clause is:
ORDER BY 列名 [ASC|DESC]
The column name is the name of the column to be sorted, with ASC indicating ascending order and DESC indicating descending order.
Here is an example:
Suppose there is a table named “employees” with a column called “full_name” storing employees’ full names. To extract and sort them by last name, you can use the following SQL statement:
SELECT SUBSTR(full_name, INSTR(full_name, ' ')+1) AS last_name
FROM employees
ORDER BY last_name;
In this example, the SUBSTR function is used in conjunction with the INSTR function to extract the surname part. The syntax of the INSTR function is:
INSTR(字符串, 查找字符串)
In this case, the string refers to the string being searched, and the search string is the substring to be found within the string. The INSTR function returns the position of the first occurrence of the search string within the string.
Next, use the SELECT clause to choose the last name part to display and alias it as “last_name”. Finally, use the ORDER BY clause to sort by last name.
You can adjust the table name, column name, and extraction position in the above SQL query according to specific requirements.