Decode

URL Encoding Reference

The ASCII control characters %00-%1F were originally designed to
control hardware devices.

Control characters have nothing to do inside a URL.

ASCII Character Description URL-encoding
NUL null character %00
SOH start of header %01
STX start of text %02
ETX end of text %03
EOT end of transmission %04
ENQ enquiry %05
ACK acknowledge %06
BEL bell (ring) %07
BS backspace %08
HT horizontal tab %09
LF line feed %0A
VT vertical tab %0B
FF form feed %0C
CR carriage return %0D
SO shift out %0E
SI shift in %0F
DLE data link escape %10
DC1 device control 1 %11
DC2 device control 2 %12
DC3 device control 3 %13
DC4 device control 4 %14
NAK negative acknowledge %15
SYN synchronize %16
ETB end transmission block %17
CAN cancel %18
EM end of medium %19
SUB substitute %1A
ESC escape %1B
FS file separator %1C
GS group separator %1D
RS record separator %1E
US unit separator %1F

❮ Previous
Next ❯

Шифр

   Ойлан

   • «Шифрлау» дегенді қалай түсінесің?   • ​Ертеде адамдар ақпараттың құпиялылығын сақтау үшін қандай құралдарды қолданған (1-сурет)?   • ​Саған «код», «кодтау» ұғымдары таныс па? Ойыңды ортаға сал.


                 Л. Альберти дискісі


                      Скитала құралы


                Шифрлау құрылғысы

   1-сурет. Ежелгі шифрлау құралдары

   Жаңа білім!

   Мәтіндерді шифрлау шамамен 4 мың жыл бұрын пайда болған. Ежелден мемлекеттің саяси, әскери, сауда және т.б. мәселелеріне қатысты құпия ақпараттар қорғау үшін мәтіндерді шифрлау қолданылған.   ​Мәтіндерді шифрлаған адам оны кері қарай өз қалпына қайтару жолын да ойластырып отырған. Шифрланған мәтінді бастапқы қалпына қайтаруды дешифрлау деп атаған.   ​Алфавит – белгілі бір тілде жазылған кез келген ақпаратты құрастырып, кодтау үшін пайдаланылатын символдар.   ​Ақпаратты белгілі бір алфавит арқылы ұсынуды кодтау, ал ақпаратты бір символдар тобынан екінші символдар тобына көшіру ережесі код деп аталады. Кодталған ақпаратты бастапқы қалпына қайтаруды декодтау дейді.

   Сөйлеу тілі – ақпаратты кодтаудың табиғи тәсілі. Адам ақпаратты қабылдап, жадында сақтайды. Адамның қабылдаған кез келген ақпараты есту, көру, иіс сезу, дәм сезу, тактильді түрлерінің бірі арқылы жадында сақталады. Адам осы бес сезім мүшесінің бірінде сақталған ақпаратты мәтін, сан, графика немесе дыбыс түрінде қайта кодтап, басқаларға ұсынады. Мысалы, бала ағашта отырған бір топ құсты көріп, оларды санағаннан кейін, жанындағы балаға айтады.   ​Адамдар ертеден-ақ өз ойларын, сөздерін қағазға түсіру үшін әріптерді ойлап тапқан. Демек, адамдар әріптің көмегімен дыбыс­тарды кодтаған.   ​Шифрлау мен кодтауды ажырата білуіміз керек. Кодтау бары­сында да ақпаратты түрлендіреді. Бірақ бұл түрлендірудің басты мақсаты – ақпаратты шифрлау (құпиялау) емес, оны сақтап, тасымалдауға ыңғайлы 

ету. Кодтау әдісінің қарапайым түрі – Морзе әліппесі (коды). Сонымен бірге компьютерде әріптер мен сандар­ды, тыныс белгілерін және басқа да қажетті символдардың екілік кодын сақтауға арналған ASCІІ кодын атауға болады.   ​ASCІІ коды. Компьютер техникасында ең көп пайдаланылатын код – ASCII (American Standart Codе for Information Interchange). Бұл – америкалық ақпарат алмасудың стандартты коды. ASCII кодтау кестесі 256 кодтан тұрады.

   Шифрлау дегеніміз – құпия ақпаратты бөтен адамдардың оқуына жол бермейтіндей етіп өзгерту.

шифр — шифр — cipherдешифр — дешифр — decipher​

Тағы да осы тақырып бойынша

Басқа іс-әрекеттер

  • Сілтемені көшіру
  • Қате туралы хабарлау

Latest From The Blog

How to Decode URI components in Javascript

1 mins

Javascript Url Decoding example. Learn how to decode URI components in Javascript. You can decode URI components in Javascript using the decodeURIComponent() function. It performs the inverse operation of encodeURIComponent(). It uses UTF-8 encoding scheme to decode URI components.

URL Decoding query strings or form parameters in Python

3 mins

Python URL Decoding example. Learn How to decode URLs in Python. URL decoding, as the name suggests, is the inverse operation of URL encoding. It is often needed when you’re reading query strings or form parameters received from a client.

How to perform URL decoding in Golang

3 mins

Golang Url Decoding example. In this article, you’ll learn how to URL decode query strings or form parameters in Golang. URL Decoding is the inverse operation of URL encoding. It converts the encoded characters back to their normal form.

PHP URL Decode example

1 mins

Learn how to URL decode a string in PHP. PHP contains urldecode() and rawurldecode() functions to decode any URL encoded (percent encoded) string back to its normal form.

Miscellaneous Tools

dCode it’s also tons of tools for processing data like finding a difference between two texts, or generate random selections. dCode handles also image processing like RGB channel separation or word processing with the search by regular expressions. dCode also manages databases like the ISBN search, the French departments , tools for finding the IP address of a website etc. Finally there are useless but essential tools, like the upside down writing or the reverse writing. (See )

dCode also has its unclassifiable pages, but very useful tools to complete the list of everything you might need.

Часто задаваемые вопросы

Вопрос:

Один из наших читателей хотел узнать, как использовать функцию DECODE, чтобы сравнить две даты (то есть: date1 и date2), где date1 > date2, функция DECODE должна вернуть date2. В противном случае функция DECODE должна вернуть date1.

Ответ:

Для этого, используйте функцию DECODE следующим образом:

DECODE((date1 — date2) — ABS(date1 — date2), 0, date2, date1)

Приведенная ниже формула будет равна 0, если date1 больше date2:

(date1 — date2) — ABS(date1 — date2)

Полезный совет № 1:

Один из наших читателей предложил объединить функцию SIGN с функцией DECODE следующим образом:

Пример с датами выше, может быть модифицированы следующим образом:

DECODE(SIGN(date1-date2), 1, date2, date1)

Сочетание SIGN / DECODE также полезно для цифровых сравнений например продажа бонусов.

DECODE(SIGN(actual-target), -1, ‘Нет бонусов для тебя’, 0,’Просто сделай это’, 1, ‘Поздравляю, вы победитель’)

Полезный совет № 2:

Один из наших читателей предложил использовать функцию LEAST (вместо функции DECODE) следующим образом:

Пример с датами выше, может быть модифицированы следующим образом:

LEAST(date1, date2)

Вопрос:

Я хотел бы знать, если это возможно, чтобы использовать функцию DECODE для диапазонов чисел, то есть 1-10 = ‘категория 1’, 11-20 = ‘категорию 2’, вместо того, чтобы индивидуально декодировать каждый номер.

Ответ:

К сожалению, вы не можете использовать функцию DECODE для диапазонов чисел. Однако, вы можете попробовать создать формулу, которая будет определять один номер для одного диапазона, и другой номер для другого диапазона, и так далее.

Например:

Oracle PL/SQL

SELECT supplier_id,
DECODE(TRUNC ((supplier_id — 1) / 10), 0, ‘category 1’,
1, ‘category 2’,
2, ‘category 3’,
‘unknown’) result
FROM suppliers;

1
2
3
4
5
6

SELECTsupplier_id,

DECODE(TRUNC((supplier_id-1)/10),0,’category 1′,

1,’category 2′,

2,’category 3′,

‘unknown’)result

FROMsuppliers;

Этот пример, на основе формулы:

TRUNC((supplier_id — 1) / 10)

Формула будет оценивать 0, если supplier_id находится между 1 и 10. Формула будет оценивать в 1, если supplier_id между 11 и 20. Формула будет оценивать по 2, если supplier_id между 21 и 30.

Вопрос:

Мне нужно написать запрос DECODE, который будет возвращать следующие:

Если yrs_of_service <1, то вернуть 0,04 Если yrs_of_service> = 1 и <5, то вернуть 0,04 Если yrs_of_service> 5 затем вернуть 0,06

Как я могу это сделать?

Ответ:

Вам нужно будет создать формулу, которая рассчитает единичное число для каждого из вашего диапазона.

Например:

Oracle PL/SQL

SELECT emp_name,
DECODE(TRUNC ((yrs_of_service + 3) / 4), 0, 0.04,
1, 0.04,
0.06) as perc_value
FROM employees;

1
2
3
4
5

SELECTemp_name,

DECODE(TRUNC((yrs_of_service+3)/4),0,0.04,

1,0.04,

0.06)asperc_value

FROMemployees;

Вопрос:

Есть ли ограничение на количество аргументов, которые вы можете указать в одном операторе DECODE? Я получаю сообщение об ошибке «ORA-00939: слишком много аргументов для функции«.

Ответ:

Да, максимальное количество компонентов, которые вы можете иметь в функции DECODE 255. Это включая expression, search и result аргументы.

Can You Use The Oracle DECODE Function With Greater Than?

Yes, you can use the DECODE function with greater than, but it’s not neat. Just like using it with a LIKE comparison, it’s better to do with a CASE statement, but still possible with a DECODE.

This can be done using subtraction and a SIGN function.

For example, to check if a value is greater than 1000:

  1. Use 1000 – value to get a result, which will be positive if the value is less than 1000, and negative if the value is greater than 1000.
  2. Add this into a SIGN function, which returns -1 for negative and 1 for positive.
  3. Compare the result to -1, and this will give you the greater than check using DECODE.

Once again, see the example section below for more information on how to do this.

Introduction to Oracle DECODE() function

The Oracle function allows you to add the procedural if-then-else logic to the query.

In the following example, the Oracle function compares the first argument (1) with the second argument (1). Because they are equal, the function returns the third argument which is the string :

It works like the following statement

The following example is slightly different from the one above. The query returns a null value because one does not equal two.

If you want to specify a default value when the first argument is not equal to the second one, you append the default value to the argument list as shown below:

It works like the following if-then-else statement:

What if you want to compare the first argument with a list of arguments? See the following example:

The result is:

In this example, the function compares the first argument (2) with the second one. If the first argument equals the second one, the function returns the third argument (One). Otherwise, it compares the first argument with the fourth argument (2). If they are equal, the function returns the fifth argument (Two).

It works like the following if-then-elsif statement:

If you want to specify a default value when the function does not find any match, you do it as follows:

The query returned:

The query works like the following if-then-elsif-else statement:

Oracle DECODE() function syntax

The following illustrates the syntax of the Oracle function:

e

The first argument e is the value to be searched. The function automatically converts e to the data type of s1 before comparing.

s1, s2, .. sn

The s1, s2, … or sn is an expression to search for. Note that s2, s3, … sn are automatically converted to the data type of s1 before comparing.

Note

You can use expressions for the search (s), the result (r), and default value (d) in the function. The function evaluates each search value (s1, s2, .., or sn) only before comparing it to the first argument (e), rather than evaluating all search values. In other words, the function never evaluates a search (si+1) when a previous search (si) equals e.

Encode a given String

We use the method on the input string, which every string object has.

Format:

input_string.encode(encoding, errors)

This encodes using , where decides the behavior to be followed if, by any chance, the encoding fails on the string.

will result in a sequence of .

inp_string = 'Hello'
bytes_encoded = inp_string.encode()
print(type(bytes_encoded))

This results in an object of , as expected:

<class 'bytes'>

The type of encoding to be followed is shown by the parameter. There are various types of character encoding schemes, out of which the scheme UTF-8 is used in Python by default.

Let us look at the parameter using an example.

a = 'This is a simple sentence.'

print('Original string:', a)

# Decodes to utf-8 by default
a_utf = a.encode()

print('Encoded string:', a_utf)

Output

Original string: This is a simple sentence.
Encoded string: b'This is a simple sentence.'

NOTE: As you can observe, we have encoded the input string in the UTF-8 format. Although there is not much of a difference, you can observe that the string is prefixed with a . This means that the string is converted to a stream of bytes, which is how it is stored on any computer. As bytes!

This is actually not human-readable and is only represented as the original string for readability, prefixed with a , to denote that it is not a string, but a sequence of bytes.

Handling errors

There are various types of , some of which are mentioned below:

Type of Error Behavior
Default behavior which raises on failure.
Ignores the un-encodable Unicode from the result.
Replaces all un-encodable Unicode characters with a question mark ()
Inserts a backslash escape sequence () instead of un-encodable Unicode characters.

Let us look at the above concepts using a simple example. We will consider an input string where not all characters are encodable (such as ),

a = 'This is a bit möre cömplex sentence.'

print('Original string:', a)

print('Encoding with errors=ignore:', a.encode(encoding='ascii', errors='ignore'))
print('Encoding with errors=replace:', a.encode(encoding='ascii', errors='replace'))

Output

Original string: This is a möre cömplex sentence.
Encoding with errors=ignore: b'This is a bit mre cmplex sentence.'
Encoding with errors=replace: b'This is a bit m?re c?mplex sentence.'

What is URL encoding?

URL encoding stands for encoding certain characters in a URL by replacing them with one or more character triplets that consist of the

percent character «» followed by two hexadecimal digits. The two hexadecimal digits of the triplet(s) represent the

numeric value of the replaced character.

The term URL encoding is a bit inexact because the encoding procedure is not limited to

URLs (Uniform Resource Locators), but can also be applied to any

other URIs (Uniform Resource Identifiers)

such as URNs (Uniform Resource Names).

Therefore, the term percent-encoding should be preferred.

Which Characters Are Allowed in a URL?

The characters allowed in a URI are either reserved or unreserved (or a percent character as part of a percent-encoding).

Reserved characters are those characters that sometimes have special meaning, while unreserved characters have no such

meaning. Using percent-encoding, characters which otherwise would not be allowed are represented using allowed characters.

The sets of reserved and unreserved characters and the circumstances under which certain reserved characters have special meaning

have changed slightly with each revision of specifications that govern URIs and URI schemes.

According to RFC 3986, the characters in a URL have to

be taken from a defined set of unreserved and reserved ASCII characters.

Any other characters are not allowed in a URL.

The unreserved characters can be encoded, but should not be encoded. The unreserved characters are:

The reserved characters have to be encoded only under certain circumstances. The reserved characters are:

Encoding/Decoding a Piece of Text

RFC 3986 does not define according to which character

encoding table non-ASCII characters (e.g. the umlauts ä, ö, ü) should

be encoded. As URL encoding involves a pair of hexadecimal digits and as a pair of hexadecimal digits is equivalent to 8 bits, it would

theoretically be possible to use one of the 8-bit code pages for non-ASCII characters (e.g. ISO-8859-1 for umlauts).

On the other hand, as many languages have their own 8-bit code page, handling all these different 8-bit code pages would be a quite

cumbersome thing to do. Some languages do not even fit into an 8-bit code page (e.g. Chinese). Therefore,

RFC 3629 proposes to use the

UTF-8 character encoding table for non-ASCII characters.

The following tool takes this into account and offers to choose between the ASCII character encoding table and the UTF-8 character

encoding table. If you opt for the ASCII character encoding table, a warning message will pop up if the URL encoded/decoded text

contains non-ASCII characters.

External Links

  • More information about percent-encoding (Wikipedia)
  • URL encoding with Java (UTF-8 character encoding, source code available)

Introduction

Direct interaction with the ENCODE DCC metadata database is typically done through scripts you write and execute on your own Mac, PC or server. Your scripts interact with the database through an industry-standard, Hypertext-Transfer-Protocol-(HTTP)-based, Representational-state-transfer (RESTful) application programming interface (API). Data objects exchanged with the server conform to the standard JavaScript Object Notation (JSON) format. JSON is a defined data interchange format that is used web-wide. If you’re familiar with JavaScript’s object literal notation or Python’s dictionary datatype, then JSON-formatted text will look familiar. You will almost certainly use libraries for your language of choice to handle the network connection and parse the objects returned (requests and json for Python, for example). We have written example scripts you can look at here.

Importance of encoding

Since encoding and decoding an input string depends on the format, we must be careful when encoding/decoding. If we use the wrong format, it will result in the wrong output and can give rise to errors.

The below snippet shows the importance of encoding and decoding.

The first decoding is incorrect, as it tries to decode an input string which is encoded in the UTF-8 format. The second one is correct since the encoding and decoding formats are the same.

a = 'This is a bit möre cömplex sentence.'

print('Original string:', a)

# Encoding in UTF-8
encoded_bytes = a.encode('utf-8', 'replace')

# Trying to decode via ASCII, which is incorrect
decoded_incorrect = encoded_bytes.decode('ascii', 'replace')
decoded_correct = encoded_bytes.decode('utf-8', 'replace')

print('Incorrectly Decoded string:', decoded_incorrect)
print('Correctly Decoded string:', decoded_correct)

Output

Original string: This is a bit möre cömplex sentence.
Incorrectly Decoded string: This is a bit m��re c��mplex sentence.
Correctly Decoded string: This is a bit möre cömplex sentence.

ASCII Encoding Reference

Your browser will encode input, according to
the character-set used in your page.

The default character-set in HTML5 is UTF-8.

Character From Windows-1252 From UTF-8
space %20 %20
! %21 %21
« %22 %22
# %23 %23
$ %24 %24
% %25 %25
& %26 %26
%27 %27
( %28 %28
) %29 %29
* %2A %2A
+ %2B %2B
, %2C %2C
%2D %2D
. %2E %2E
%2F %2F
%30 %30
1 %31 %31
2 %32 %32
3 %33 %33
4 %34 %34
5 %35 %35
6 %36 %36
7 %37 %37
8 %38 %38
9 %39 %39
%3A %3A
; %3B %3B
< %3C %3C
= %3D %3D
> %3E %3E
? %3F %3F
@ %40 %40
A %41 %41
B %42 %42
C %43 %43
D %44 %44
E %45 %45
F %46 %46
G %47 %47
H %48 %48
I %49 %49
J %4A %4A
K %4B %4B
L %4C %4C
M %4D %4D
N %4E %4E
O %4F %4F
P %50 %50
Q %51 %51
R %52 %52
S %53 %53
T %54 %54
U %55 %55
V %56 %56
W %57 %57
X %58 %58
Y %59 %59
Z %5A %5A
%5B %5B
\ %5C %5C
%5D %5D
^ %5E %5E
_ %5F %5F
` %60 %60
a %61 %61
b %62 %62
c %63 %63
d %64 %64
e %65 %65
f %66 %66
g %67 %67
h %68 %68
i %69 %69
j %6A %6A
k %6B %6B
l %6C %6C
m %6D %6D
n %6E %6E
o %6F %6F
p %70 %70
q %71 %71
r %72 %72
s %73 %73
t %74 %74
u %75 %75
v %76 %76
w %77 %77
x %78 %78
y %79 %79
z %7A %7A
{ %7B %7B
| %7C %7C
} %7D %7D
~ %7E %7E
  %7F %7F
` %80 %E2%82%AC
%81 %81
%82 %E2%80%9A
ƒ %83 %C6%92
%84 %E2%80%9E
%85 %E2%80%A6
%86 %E2%80%A0
%87 %E2%80%A1
ˆ %88 %CB%86
%89 %E2%80%B0
Š %8A %C5%A0
%8B %E2%80%B9
Π%8C %C5%92
%8D %C5%8D
Ž %8E %C5%BD
%8F %8F
%90 %C2%90
%91 %E2%80%98
%92 %E2%80%99
%93 %E2%80%9C
%94 %E2%80%9D
%95 %E2%80%A2
%96 %E2%80%93
%97 %E2%80%94
˜ %98 %CB%9C
%99 %E2%84
š %9A %C5%A1
%9B %E2%80
œ %9C %C5%93
%9D %9D
ž %9E %C5%BE
Ÿ %9F %C5%B8
  %A0 %C2%A0
¡ %A1 %C2%A1
¢ %A2 %C2%A2
£ %A3 %C2%A3
¤ %A4 %C2%A4
¥ %A5 %C2%A5
¦ %A6 %C2%A6
§ %A7 %C2%A7
¨ %A8 %C2%A8
%A9 %C2%A9
ª %AA %C2%AA
%AB %C2%AB
¬ %AC %C2%AC
­ %AD %C2%AD
%AE %C2%AE
¯ %AF %C2%AF
° %B0 %C2%B0
± %B1 %C2%B1
² %B2 %C2%B2
³ %B3 %C2%B3
´ %B4 %C2%B4
µ %B5 %C2%B5
%B6 %C2%B6
· %B7 %C2%B7
¸ %B8 %C2%B8
¹ %B9 %C2%B9
º %BA %C2%BA
%BB %C2%BB
¼ %BC %C2%BC
½ %BD %C2%BD
¾ %BE %C2%BE
¿ %BF %C2%BF
À %C0 %C3%80
Á %C1 %C3%81
 %C2 %C3%82
à %C3 %C3%83
Ä %C4 %C3%84
Å %C5 %C3%85
Æ %C6 %C3%86
Ç %C7 %C3%87
È %C8 %C3%88
É %C9 %C3%89
Ê %CA %C3%8A
Ë %CB %C3%8B
Ì %CC %C3%8C
Í %CD %C3%8D
Î %CE %C3%8E
Ï %CF %C3%8F
Ð %D0 %C3%90
Ñ %D1 %C3%91
Ò %D2 %C3%92
Ó %D3 %C3%93
Ô %D4 %C3%94
Õ %D5 %C3%95
Ö %D6 %C3%96
× %D7 %C3%97
Ø %D8 %C3%98
Ù %D9 %C3%99
Ú %DA %C3%9A
Û %DB %C3%9B
Ü %DC %C3%9C
Ý %DD %C3%9D
Þ %DE %C3%9E
ß %DF %C3%9F
à %E0 %C3%A0
á %E1 %C3%A1
â %E2 %C3%A2
ã %E3 %C3%A3
ä %E4 %C3%A4
å %E5 %C3%A5
æ %E6 %C3%A6
ç %E7 %C3%A7
è %E8 %C3%A8
é %E9 %C3%A9
ê %EA %C3%AA
ë %EB %C3%AB
ì %EC %C3%AC
í %ED %C3%AD
î %EE %C3%AE
ï %EF %C3%AF
ð %F0 %C3%B0
ñ %F1 %C3%B1
ò %F2 %C3%B2
ó %F3 %C3%B3
ô %F4 %C3%B4
õ %F5 %C3%B5
ö %F6 %C3%B6
÷ %F7 %C3%B7
ø %F8 %C3%B8
ù %F9 %C3%B9
ú %FA %C3%BA
û %FB %C3%BB
ü %FC %C3%BC
ý %FD %C3%BD
þ %FE %C3%BE
ÿ %FF %C3%BF

Source code

dCode retains ownership of the online ‘dCode.xyz’ tool source code. Except explicit open source licence (indicated CC / Creative Commons / free), any algorithm, applet or snippet (converter, solver, encryption / decryption, encoding / decoding, ciphering / deciphering, translator), or any function (convert, solve, decrypt / encrypt, decipher / cipher, decode / encode, translate) written in any informatic language (PHP, Java, C#, Python, Javascript, Matlab, etc.) no data, script or API access will be for free, same for dCode.xyz download for offline use on PC, tablet, iPhone or Android !

URL Encoding Reference

The ASCII control characters %00-%1F were originally designed to
control hardware devices.

Control characters have nothing to do inside a URL.

ASCII Character Description URL-encoding
NUL null character %00
SOH start of header %01
STX start of text %02
ETX end of text %03
EOT end of transmission %04
ENQ enquiry %05
ACK acknowledge %06
BEL bell (ring) %07
BS backspace %08
HT horizontal tab %09
LF line feed %0A
VT vertical tab %0B
FF form feed %0C
CR carriage return %0D
SO shift out %0E
SI shift in %0F
DLE data link escape %10
DC1 device control 1 %11
DC2 device control 2 %12
DC3 device control 3 %13
DC4 device control 4 %14
NAK negative acknowledge %15
SYN synchronize %16
ETB end transmission block %17
CAN cancel %18
EM end of medium %19
SUB substitute %1A
ESC escape %1B
FS file separator %1C
GS group separator %1D
RS record separator %1E
US unit separator %1F

Frequently Asked Questions

Question: One of our viewers wanted to know how to use the DECODE function to compare two dates (ie: date1 and date2), where if date1 > date2, the DECODE function should return date2. Otherwise, the DECODE function should return date1.

Answer: To accomplish this, use the DECODE function as follows:

DECODE((date1 - date2) - ABS(date1 - date2), 0, date2, date1)

The formula below would equal 0, if date1 is greater than date2:

(date1 - date2) - ABS(date1 - date2)

Helpful Tip #1: One of our viewers suggested combining the SIGN function with the DECODE function as follows:

The date example above could be modified as follows:

DECODE(SIGN(date1-date2), 1, date2, date1)

The SIGN/DECODE combination is also helpful for numeric comparisons e.g. Sales Bonuses

DECODE(SIGN(actual-target), -1, 'NO Bonus for you', 0,'Just made it', 1, 'Congrats, you are a winner')

Helpful Tip #2: One of our viewers suggested using the LEAST function (instead of the DECODE function) as follows:

The date example above could be modified as follows:

LEAST(date1, date2)

Question: I would like to know if it’s possible to use the DECODE function for ranges of numbers, ie 1-10 = ‘category 1’, 11-20 = ‘category 2’, rather than having to individually decode each number.

Answer: Unfortunately, you can not use the DECODE function for ranges of numbers. However, you can try to create a formula that will evaluate to one number for a given range, and another number for the next range, and so on.

For example:

SELECT supplier_id,
DECODE(TRUNC ((supplier_id - 1) / 10), 0, 'category 1',
                                       1, 'category 2',
                                       2, 'category 3',
                                       'unknown') result
FROM suppliers;

In this example, based on the formula:

TRUNC ((supplier_id - 1) / 10

The formula will evaluate to 0, if the supplier_id is between 1 and 10.
The formula will evaluate to 1, if the supplier_id is between 11 and 20.
The formula will evaluate to 2, if the supplier_id is between 21 and 30.

and so on…

Question: I need to write a DECODE statement that will return the following:

If yrs_of_service < 1 then return 0.04
If yrs_of_service >= 1 and < 5 then return 0.04
If yrs_of_service > 5 then return 0.06

How can I do this?

Answer: You will need to create a formula that will evaluate to a single number for each one of your ranges.

For example:

SELECT emp_name,
DECODE(TRUNC (( yrs_of_service + 3) / 4), 0, 0.04,
                                          1, 0.04,
                                          0.06) as perc_value
FROM employees;

Question: Is there a limit to the number of arguments that you can have in one DECODE statement? I’m getting an error, «ORA-00939: too many arguments for function».

Answer: Yes, the maximum number of components that you can have in a DECODE function is 255. This includes the expression, search, and result arguments.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *