The DECODE function is used to evaluate different values based on conditional expressions, similar to the IF-ELSE syntax. Its usage includes: replacing NULL values, converting data types, and returning different values based on conditions.
Usage of DECODE function in SQL
Overview of DECODE function
## The #DECODE function is a SQL function that evaluates different values based on a conditional expression. It is similar to the IF-ELSE construct, but allows for a more concise syntax.Syntax
<code class="sql">DECODE(expression, value1, result1, value2, result2, ..., default_result)</code>
Parameters
Usage
DECODE function has the following usage:<code class="sql">SELECT DECODE(name, NULL, 'Unknown', name) FROM customers;</code>
<code class="sql">SELECT DECODE(age, NULL, 0, age) FROM employees;</code>
<code class="sql">SELECT DECODE(gender, 'M', 'Male', 'F', 'Female', 'Other') FROM students;</code>
Example
The following example demonstrates the use of the DECODE function:<code class="sql">CREATE TABLE sales ( product_id INT, product_name VARCHAR(50), category VARCHAR(20), sales_amount DECIMAL(10, 2) ); INSERT INTO sales (product_id, product_name, category, sales_amount) VALUES (1, 'Smart TV', 'Electronics', 2000.00), (2, 'iPhone', 'Electronics', 1500.00), (3, 'Coffee Maker', 'Appliances', 300.00), (4, 'Microwave', 'Appliances', 450.00); SELECT product_name, category, DECODE(sales_amount, NULL, 'No Sales', 2000.00, 'High Sales', 1500.00, 'Medium Sales', 'Low Sales') AS sales_category FROM sales;</code>
Output:
<code>product_name | category | sales_category Smart TV | Electronics | High Sales iPhone | Electronics | Medium Sales Coffee Maker | Appliances | Low Sales Microwave | Appliances | Low Sales</code>
The above is the detailed content of Usage of decode in sql. For more information, please follow other related articles on the PHP Chinese website!