SQL DECODE



  SQL > Advanced SQL > DECODE Function

DECODE is a function in Oracle and is used to provide if-then-else type of logic to SQL. It is not available in MySQL or SQL Server. The syntax for DECODE is:

SELECT DECODE ( "column_name", "search_value_1", "result_1", ["search_value_n", "result_n"], {"default_result"} )

"search_value" is the value to search for, and "result" is the value that is displayed.

In our Table Store_Information example,

Table Store_Information
store_nameSalesDate
Los Angeles$1500Jan-05-1999
San Diego$250Jan-07-1999
San Francisco$300Jan-08-1999
Boston$700Jan-08-1999

if we want to display 'LA' for 'Los Angeles', 'SF' for 'San Francisco', 'SD' for 'San Diego', and 'Others' for all other cities, we would issue the following SQL,

SELECT DECODE (store_name,
  'Los Angeles', 'LA',
  'San Francisco', 'SF',
  'San Diego', 'SD',
  'Others') Area, Sales, Date
FROM Store_Information

"Area" is the name given to the column with the DECODE statement.

Result:

AreaSalesDate
LA$3000Jan-05-1999
San Diego$375Jan-07-1999
San Francisco$300Jan-08-1999
Boston$700Jan-08-1999

To achieve what DECODE does in MySQL and SQL Server, we would use the CASE function.



Next: SQL AUTO INCREMENT




Copyright © 2013 1keydata.com   All Rights Reserved.     Privacy Policy


SQL UNION
SQL UNION ALL
SQL Inline View
SQL INTERSECT
SQL MINUS
SQL LIMIT
SQL TOP
SQL Subquery
SQL EXISTS
SQL CASE
SQL DECODE
SQL AUTO INCREMENT
SQL IDENTITY
SQL SEQUENCE And NEXTVAL
SQL NULL
SQL ISNULL
SQL IFNULL
SQL NVL
SQL COALESCE
SQL NULLIF
SQL Rank
SQL Median
SQL Running Totals
SQL Percent to Total
SQL Cumulative Percent to Total


SQL Video Tutorial
SQL Jobs




Site Map
Resources