The DECODE function in Oracle database is a very commonly used function, which can select from a set of values based on the result value of an expression. The syntax of the DECODE function is as follows:
DECODE(expression, search_value1, result1, search_value2, result2, ..., default_result)
where expression is the expression to be compared, search_value1 is the value to be compared, result1 is the result returned if expression is equal to search_value1, and so on.
The following will introduce some advanced usage and techniques of the DECODE function, and provide specific code examples:
DECODE function can realize multi-condition judgment and combine multiple conditions together for judgment. For example, to determine the employee's level, if the level is 1, "junior" will be returned, if the level is 2, "intermediate" will be returned, if the level is 3, "senior" will be returned, and in other cases, "unknown level" will be returned.
SELECT name, DECODE(level, 1, '初级', 2, '中级', 3, '高级', '未知级别') AS level_name FROM employees;
The DECODE function can process NULL values and convert NULL values into other values. For example, convert NULL values to 0.
SELECT name, DECODE(salary, NULL, 0, salary) AS new_salary FROM employees;
The DECODE function can perform logical calculations and implement functions similar to the IF-ELSE statement. For example, if a field is less than 10, return "small", otherwise return "large".
SELECT name, DECODE(quantity < 10, 1, '小', '大') AS size FROM products;
The DECODE function can also be used for data conversion to convert data from one form to another. For example, convert gender encoding into Chinese character form.
SELECT name, DECODE(gender, 'M', '男', 'F', '女') AS gender_name FROM employees;
The DECODE function can perform range judgment and return different results when the value of the expression is judged to be within a certain range. For example, judging a student's level based on their grades.
SELECT name, DECODE(score, 90, '优秀', 80, '良好', 70, '及格', '不及格') AS level FROM students;
Through the above examples, we can see the powerful function and flexibility of the DECODE function in Oracle database. In actual work, reasonable use of the DECODE function can simplify the writing of SQL statements, improve query efficiency, and also make the code clearer and easier to understand. I hope the above content can help readers better understand and apply the DECODE function.
The above is the detailed content of Advanced usage and skill sharing of Oracle DECODE function. For more information, please follow other related articles on the PHP Chinese website!