Trending November 2023 # How Linux Time Works With Examples? # Suggested December 2023 # Top 20 Popular

You are reading the article How Linux Time Works With Examples? updated in November 2023 on the website Hatcungthantuong.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested December 2023 How Linux Time Works With Examples?

Introduction to Linux Time

In the Linux operating system, the time will run the special program with a specific or compatible input argument. When the command or the job will finish the execution, the time command will give the below timing statistics

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Elapsed Time: It is the passed time between the invocation of the process or job and the termination of the process.

User CPU Time: It is the addition of the tms_utime time and tms_cutime time values.

System CPU Time: It is the addition of the tms_stime time and tms_cstime time values.

Syntax:

time [ OPTION ] [ COMMAND ]

time : We can use the “time” keyword in the syntax or command. It will take different arguments like options and commands. As per the provided arguments, it will print the time options in different types like Elapsed Time, User CPU Time, and System CPU Time.

OPTION : We can provide the different flags as the option that is compatible with the “time” command.

COMMAND: As per the condition or requirement, we can provide or use a different command with the time keyword.

How Linux Time Works?

Linux is a multi-user support operating system. It will support multiple servers or applications. While running these servers or applications, they are generating a huge amount of data. Once the data will generate parallel the time will also increase while doing the reading or writing operations on it. The time command will consider the different compatible options with the command. As per the inputs, it will give the detailed information of time in terms of the Elapsed Time, User CPU Time, and System CPU Time.

Below are the lists of options that are compatible with the time command.

Sr No Option Description

1 C It will give the information of the name and the command line arguments being timed (in terms of the command)

2 D It will give information about the average size of the processes in the unshared data area. The information will be in Kilobytes.

3 E This process will use the wall clock time. It will be in hours: minutes: seconds format.

4 I It will get the Number of file system inputs by the process.

5 K It will consider the average of data, stack, and text memory use of the process. It will be in Kilobytes.

6 M Due to the process lifetime, we can set the maximum resident of the process. It will be in Kilobytes.

7 O The process will consider the number of file system outputs.

8 P It is the addition of user and system time divide by total running time. We will get the percentage of the CPU that the job got.

9 S In terms of process, it will be the total number of CPU-seconds used by the system. The value will be in seconds.

10 U In terms of user mode, the total number of CPU-seconds that the process used. The value will be in seconds.

11 W It will give the memory information of the number of times the process was swapped.

12 X It will give information on the average amount of shared text in the process. The value will be in Kilobytes.

13 Z It will give the system page size information. The value will be in bytes.

14 e It will be the wall clock time used by the process. The value will be in seconds.

15 k It will give the information of the number of signals delivered to the process.

16 p It will give the process information of the average unshared stack size. The value will be in Kilobytes.

17 r The process will receive the number of socket messages.

18 s The process will be sent the number of socket messages.

19 t It will give the information of the average resident set size of the process. The value will be in Kilobytes.

20 x It will give the exit status of the command.

Examples

Lets us discuss examples of Linux time.

Example #1

In the Linux environment, we can run the simple time command and get the basic information of the Elapsed Time, User CPU Time, and System CPU Time.

Command :

time

Explanation :

As per the above command, we are running the simple time command. It will give the basic information of the Elapsed Time, User CPU Time, and System CPU Time.

Output :

Example #2

In the time command, we are having the functionality to use the different Linux commands.

Command :

We are using the wget command with the time command. Time command will calculate the elapsed time, user and CPU time for execution of the command.

Output :

Example #3 – Redirect Time Command Output

In the time command, we are able to redirect the time command output to a different file.

Command :

Explanation :

As per the above command, we are redirecting the time command output to the “time.txt” file. It will use for further analysis.

Output :

Example #4 – With Option “-p”

In time command, we are able to print the time in POSIX format

Command :

Explanation :

In the above command, we are able to print the time command output in POSIX format. As per the requirement, we can use the different options with the time command.

Output :

Conclusion

We have seen the uncut concept of “Linux Time” with the proper example, explanation, and command with different outputs. As per the requirement, we can use the time command with different Linux command and get detail time information in terms of the Elapsed Time, User CPU Time, and System CPU Time.

Recommended Articles

We hope that this EDUCBA information on “Linux Time” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

You're reading How Linux Time Works With Examples?

How Compareto Works In Java With Examples

Introduction to compareTo Java

compareTo() is a method in Java that compares the string given with the current string in a lexicographical manner. Comparison is done on the basis of the Unicode value of characters available in the string.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Following are the different conditions in the compareTo() method.

If string 1 is lexicographically larger than string 2, a positive number will be returned.

If string 1 is lexicographically smaller than string 2, a negative number will be returned.

If string 1 is lexicographically equal to string 2, ‘0’will be returned.

Below is the syntax of compareTo() method:

public int compareTo(String s2)

Here, s2 is the string that is used for comparison with the current string. An integer value will be returned on calling this method.

How compareTo works in Java?

compareTo() method can be used in three ways.

Examples of compareTo Java

Given below are the examples of compareTo Java:

Example #1

Java program to implement compareTo method that compares two strings.

Code:

public class compareToExample { public static void main(String args[]) { String s1 = "Happiness lies within you"; String s2 = "Happiness LIES WITHIN YOU"; String s3 = "Happiness lies within you"; System.out.println( " Compare s1 and s2 : "+ V1 ) ; System.out.println( " Compare s1 and s3 : "+ v2 ) ; System.out.println(" Compare s2 and s3 : "+ v3 ) ; }}

Output:

In this program, three strings are created s1, s2 and s3. Three variables, v1, v2 and v3, are also created for storing the comparison results of s1&s2, s1&s3, and s2&s3, respectively. It can be seen that a positive number is returned on comparing s1 & s2, and a negative number is returned on comparing s2 &s3. As both s1 and s3 are equal, 0 is returned in the second case.

Example #2

Java program to implement compareTo method that compares a string and an object.

Code:

public class compareToExample { public static void main(String args[]) { String s1 = "Happiness lies within you"; System.out.println( " Compare s1 and argument : "+ v2 ) ; } }

Output:

In this program, a string s1 and variable v1 are created first. Another string is passed as an argument in the compareTo() method, and it can be seen that a positive number is returned on comparing s1 and argument.

Example #3

Java program to find the length of a string using the compareTo method.

Code:

public class compareToExample { public static void main(String args[]) { String s1 = "Happiness lies within you"; String s2 = ""; System.out.println( " Length of s1 : "+ V1 ) ; System.out.println( " Length of s1 : "+ v2 ) ; } }

Output:

In this program, two strings are created, s1 and s2, where s2 is a null string. If the given string is compared with a nullstring, then the length of the non-empty string will be returned. If a comparison is done in reverse order, a negative value of the length will be returned.

Example #4

Java program to implement compareToIgnoreCase method that compares two strings.

Code:

public class compareToExample { public static void main(String args[]) { String s1 = "Happiness lies within you"; String s2 = "Happiness LIES WITHIN YOU"; String s3 = "Happiness lies within you"; System.out.println( " Compare s1 and s2 : "+ V1 ) ; System.out.println( " Compare s1 and s3 : "+ v2 ) ; System.out.println(" Compare s2 and s3 : "+ v3 ) ; } }

As already seen, compareToIgnoreCase ignores the case and compares the strings. As the three strings differ only in cases, 0 will be returned on calling this method.

Example #5

Java program to implement compareToIgnoreCase method that compares a string and an object.

Code:

public class compareToExample { public static void main(String args[]) { String s1 = "Happiness lies within you"; System.out.println( " Compare s1 and argument : "+ v2 ) ; } }

Output:

In this program, a string s1 and variable v1 are created first. Another string is passed as an argument in the compareToIgnoreCase() method, and it can be seen that 0 is returned as the case is ignored.

Conclusion

compareTo() is a Java method that compares the string given with the current string in a lexicographical manner. In this article, different aspects such as syntax, working, and examples of the compareTo() method is seen in detail.

Recommended Articles

This is a guide to compareTo Java. Here we discuss the introduction, how compareTo works in java? Along with examples, respectively. You may also have a look at the following articles to learn more –

How Sha1() Function Works In Php With Examples

Introduction to PHP sha1()

PHP sha1() function is a very important function as part of PHP as it is a backed server-side scripting language that needs more emphasis on the security terms. PHP sha1() deals with the security and hashing function which calculates and computes a value of SHA-1 of the hash of the string. Internally PHP sha1() makes use of a subtype of the US Secure Hash Algorithm 1. Sha1() function produces a hash string with a value of 160 characters and then when this hash string is given as an input to the function it produces an output which is a highly secured message digest.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax sha1(string, raw)

Explanation: sha1() function makes use of two types of arguments like string and raw which is used for generating the string and calculating the length of the string with some value. raw is another argument or parameter which is optional in the sense if specified with the sha1() function then it passes the parameter with an optional value such as true or false and then it passes the remaining value to specify and describe the hex or binary value output format. If the optional value appears to be Raw 20 then it is a 20-character binary format otherwise it Is Default 40-character hex number with some specific value.

How does sha1() function work in PHP?

The SHA-1() function makes use of the US-Secure hash algorithm1 which is used in a way where the string is given as an input and then a message digest is given as an output. Input is fed to the signature algorithm which checks and verifies for the signature of the message. If a signature message is used as an input rather than the actual message, then it has a high chance of improving the efficiency of the overall algorithm.

This process will optimize and compress the message input and message output functionality compared to the normal hash string message as an input to the signature algorithm. Further if this algorithm is used by the verifier then a digital signature can be used by the creator of the digital signature.

sha_file() function is another subcomponent of the sha1() function which uses the hash of the file function.

This file function of the file name is used to calculate the hash of a file and one raw output will be given to it which will be used to return the message or the string with a value of whether true or false. Md5() algorithm within the function and crc32() with the function will also be used to generate the polynomial of the string. And will help in generating a more secured string with some refined digital signature.

Examples to Implement PHP sha1() Function

Below are mentioned the examples:

Example #1

his program represents the calculation of the SHA-1 hash of the string after passing one string value to get the hash of the string.

Code:

<?php $str = "welcome to educba"; echo sha1($str);

Output:

Example #2

This program represents the calculation of the SHA-1 hash of the string after passing one string value to get the hash of the string and then it prints the value of the sha1 string as shown in the output. The input of the string is given as “Welcome to Educba” and the output shows the string value.

Code:

<?php $str = "Welcome to Educba"; echo "The string: ".$str."n"; echo "TRUE - Represenation of Raw 20 character of binary format: ".sha1($str, TRUE)."n"; echo "FALSE - representation of 40 character of hex number: ".sha1($str)."n";

Output:

Example #3

This program represents the calculation of the SHA-1 hash of the string after passing one string value to get the hash of the string and then it prints the value of the sha1 string as shown in the output. The input of the string is given as “Welcome to Educba” and the output shows the string value. Followed by a test of the input string being fed as an output.

<?php $str = "educba"; echo sha1($str); if (sha1($str) == "49108e13b1505cd6147054cfd07fb52f4c9d2641") { echo "n!educba"; exit; }

Output:

Example #4

This program is also a part of the sha1() function associated function of CRC 32 algorithm which takes a string “Hello World ” as input and then echoes the value without and with the string of % u value as shown in the output.

Code:

<?php $str = crc32("Hello educba!"); echo 'Without %u: '.$str."n"; echo 'With %u: '; printf("%u",$str);

Output:

Example #5

This program makes use of the password_hash function as part of the sha1() function and helps in generating the password_hash with an output value as shown and makes use of hashing function by putting the cost parameter as 12 to get the optimized message digest as the final output to optimize and increase the overall efficiency of the program.

Code:

<?php $options = [ ]; echo password_hash("educba_is_a_laerning_portal", PASSWORD_BCRYPT, $options);

Output:

Example #6

This program makes use of the hash () function to generate the message digest of the given function which will be further used to convert into a digital signature for optimization.

Code:

<?php function lion($data = "", $width=182, $rounds = 4) { return substr( implode( array_map( function ($h) { return str_pad(bin2hex(strrev($h)), 16, "0"); }, str_split(hash("tiger192,$rounds", $data, true), 8) ) ), 0, 48-(192-$width)/4 ); } echo hash('tiger192,3', 'a-string'), PHP_EOL; echo lion('a-string'), PHP_EOL;

Output:

Example #7

This program illustrated the md5 algorithm to be fed as an input string which is also counted as one of the complementary parts of the sha1() algorithm.

Code:

<?php $str = 'apple'; if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') { echo " i want to have a green or red apple?"; }

Output:

Conclusion

sha1() function is a part of PHP string references which includes a lot of security and cryptographic algorithms which is very necessary for the backend services and the servers for continuing the overall security breaches related issues and password and user management related data as secured.

Recommended Articles

This is a guide to PHP sha1(). Here we discuss an introduction, Syntax, and working of sha1() in PHP along with different examples and code implementation. You can also go through our other related articles to learn more –

Apropos Linux Command Explained {With Examples}

If you’re someone who frequently uses Linux, you may have come across term ‘apropos’ while using terminal. Apropos is a very useful Linux command that helps users find commands related to a specific topic or keyword. In this article, we will take a closer look at ‘apropos’ command and explain its usage with several examples.

What is Apropos?

‘Apropos’ is a command-line utility in Linux that searches manual pages for a keyword or topic and returns a list of relevant commands. It is a great tool for quickly finding commands you need, especially if you don’t remember exact command name.

The ‘apropos’ command works by searching ‘man’ pages, which are Linux manual pages that contain documentation for various commands, utilities, and system calls. These manual pages are organized by sections, and ‘apropos’ command searches all of sections for specified keyword.

How to use Apropos?

For example, if you want to search for all commands related to “network”, you can type −

apropos network

This will return a list of all commands related to keyword “network”, along with a brief description of each command.

Examples of Apropos Usage

Let’s take a look at some examples of how ‘apropos’ command can be used in different situations.

Example 1: Finding all Commands Related to a Keyword

As mentioned earlier, most common usage of ‘apropos’ command is to find all commands related to a specific keyword or topic. Let’s say you want to find all commands related to “file”. You can type following command −

apropos file

This will return a list of all commands related to “file”, such as ‘cat’, ‘cp’, ‘ls’, ‘mv’, ‘rm’, and many more. list will also include a brief description of each command, making it easier for you to decide which command to use.

Example 2: Finding a Specific Command

Sometimes, you may know name of command you need, but you may not remember its exact syntax or usage. In such a case, you can use ‘apropos’ command to find command you need.

For example, let’s say you want to use ‘grep’ command, but you don’t remember its syntax. You can type following command −

apropos grep

This will return ‘grep’ command along with a brief description of its usage. You can then use ‘man’ command to learn more about ‘grep’ command and how to use it.

Example 3: Finding a Command by Description

In some cases, you may remember description of a command but not its exact name. In such a case, you can use ‘apropos’ command to search for command by its description.

For example, let’s say you remember that there is a command that can be used to find largest file in a directory, but you don’t remember its name. You can type following command −

apropos "largest file"

This will return ‘du’ command, which can be used to find size of a directory or file. You can then use ‘man’ command to learn more about ‘du’ command and how to use it to find largest file in a directory.

Example 4: Finding all Available Options for a Command

Sometimes, you may want to find all available options for a specific command. You can use ‘apropos’ command to search for command and then use ‘man’ command to see all available options.

For example, let’s say you want to find all available options for ‘ls’ command. You can type following command −

apropos ls

This will return ‘ls’ command along with a brief description of its usage. You can then use ‘man’ command to see all available options for ‘ls’ command. To do this, type −

man ls

This will display manual page for ‘ls’ command, which includes a list of all available options along with their descriptions.

Tips for Using Apropos

Here are a few tips for using ‘apropos’ command more effectively −

Be specific with your search terms − ‘apropos’ command will return a lot of results if your search term is too broad. Try to be as specific as possible when searching for commands.

Use quotes for multiple keywords − If you’re searching for commands related to multiple keywords, enclose them in quotes. For example, to search for commands related to both “network” and “security”, you can type: apropos “network security”

Use -a option for more results − By default, ‘apropos’ command only returns first 10 results. If you want to see more results, you can use ‘-a’ option. For example, apropos -a network will return all commands related to “network”.

Use -w option for exact matches − If you want to search for commands that match your search term exactly, use ‘-w’ option. For example, apropos -w grep will only return ‘grep’ command and not other commands that contain word “grep”.

Use -k option for keyword search − If you’re not sure about exact command name but know a keyword that might be used in command, you can use ‘-k’ option. For example, apropos -k “search pattern” will return all commands related to searching for patterns.

Apropos in Shell Scripting

The ‘apropos’ command can also be used in shell scripting. In a shell script, you can use ‘apropos’ command to find command you need and then use it in your script.

For example, let’s say you’re writing a shell script that needs to search for a specific pattern in a file. You can use ‘apropos’ command to find ‘grep’ command and then use it in your script.

#!/bin/bash # Find 'grep' command # Use 'grep' command to search for a pattern in a file $GREP_COMMAND "pattern" file.txt

In this example, ‘apropos’ command is used to find ‘grep’ command, which is then assigned to ‘GREP_COMMAND’ variable. ‘grep’ command is then used to search for a pattern in a file.

Apropos vs. Man

While ‘apropos’ command is a useful tool for finding commands related to a specific topic, it’s important to note that it’s not a replacement for ‘man’ command. ‘man’ command provides detailed documentation for each command, including usage examples, options, and syntax.

The ‘apropos’ command, on other hand, only provides a brief description of each command and its purpose. It’s a useful tool for finding commands, but it doesn’t provide same level of detail as ‘man’ command.

Apropos Alternatives

While ‘apropos’ command is a useful tool for finding commands related to a specific topic, there are some alternative tools you can use as well.

One alternative is ‘whatis’ command, which provides a brief description of a specific command. For example, if you want to know what ‘ls’ command does, you can type −

whatis ls

This will return a brief description of ‘ls’ command, such as “list directory contents”.

Another alternative is ‘man -k’ command, which works in a similar way to ‘apropos’ command. To search for commands related to a specific topic, you can type −

This will return a list of all commands related to specified keyword, along with a brief description of each command.

Apropos in Conjunction with Wildcards

The ‘apropos’ command can also be used in conjunction with wildcards to find commands related to a specific pattern. This can be particularly useful when you want to find all commands related to a certain type of file or operation.

For example, to find all commands related to file compression, you can use following command −

apropos "*compress*"

This will return all commands related to file compression, such as ‘gzip’, ‘bzip2’, ‘zip’, and many others.

Similarly, you can use ‘apropos’ command to find all commands related to a specific type of file. For example, to find all commands related to image files, you can use following command −

apropos "*image*"

This will return all commands related to image files, such as ‘convert’, ‘identify’, ‘mogrify’, and others.

Conclusion

The ‘apropos’ command is a powerful and versatile tool that can help you find commands you need quickly and easily. Whether you’re searching for a specific command, trying to find all available options for a command, or looking for commands related to a specific topic, ‘apropos’ command can help you get job done. So, next time you’re working in Linux terminal and need help finding a command, remember to use ‘apropos’ command!

How Calc() Function Works In Css? Examples

Introduction to CSS calc()

The calc() function contains a calculation that should be used as the property’s value. This function makes it easy to position an object with a set margin. The calc() function takes a specific expression as its argument, with the output of the expression being used as the value. The calc() is a native CSS method for doing basic maths correctly in CSS as a substitute for any longitudinal value or almost any number. This has four basic operators in math: add (+), subtract (-), multiply (*), and divide (/). Another case for the calc() function is to help ensure that form fields fit into the space available without extruding beyond the edge of the container while maintaining an acceptable margin.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

property_name: calc(expression) How does the calc() Function works in CSS?

The calc() function is better than the pre-processor, which can mix any unit. The calc() function makes simple calculations to specify the CSS property values. Users can multiply pixels by percentage.

To make the layout more versatile, it offers two key features such as:

Mixing percentages and absolute values.

Units of mixing sizes.

Examples of CSS calc()

Given below are the examples of CSS calc():

Example #1

Code:

.heading { position: absolute; left: 30px; width: calc(50% – 20%); height:calc(200px – 100px); background-color: #5E9BC6; padding-top:20px; text-align: center; } h2 { color:#F1DBED; }

Output:

We apply the calc() function to the height and width attributes, setting the width to 30% and the height to 100px. We are referring to the heading class for defining styles for the content.

Example #2

Code:

img { width: 100%; display: block; } .box { float: left; padding: 5px; box-sizing: border-box; width: calc(100% / 5); } @media (max-width: 900px) { .box { width: calc(100% / 4); } } @media (max-width: 550px) { .box { width: calc(100% / 3); } } @media (max-width: 400px) { .box { width: 100%; } }

Output:

The program explains how the boxes will get displayed in different screen resolutions. We have taken maximum widths as 900px, 550px, and 400px. When the screen gets smaller than 900px, 550px, and 400px, each box will have a specified width, as provided in the example.

Example #3

Code:

.heading { position: absolute; left: 40px; width: calc(300px – 50px); border: 2px dotted red; background-color: #5E9BC6; padding: 3px; text-align: center; }

Output:

The calc() function is applied to the width attribute, where the width will be set to 250px. The heading class is referred to for defining the styles for the content display.

Example #4

.input_txt { padding: 5px; display: block; width: calc(50% – 2em); } #box { width: calc(200% / 8); border: 1px dotted #5E9BC6; padding: 5px; }

Output:

Here, we are using the input type element of the HTML form. We apply the calc() function to the div and input elements. The width of the input type will be decreased to 2 times the size of the current width.

Example #5

Code:

img { display: block; } section { width: 250px; height: 150px; position: relative; background-color: #5E9BC6; } .box { position: absolute; } .box-horizontal { top: 15px; left: calc(50% – 20px); } .box-vertical { left: 15px; top: calc(50% – 20px); } .box-middle { left: calc(50% – 20px); top: calc(50% – 20px); }

Output:

The output shows a horizontal box, a vertical box, and middlebox. The horizontal box will be displayed on the left side by decreasing 20px from 50% with the help of the calc() function. The same scenario will be applied to vertical and middle elements.

Example #6

Code:

*{ box-sizing: border-box; } html, body{ height: 100%; padding: 50px; background: #00174f; } body{ }

Output:

Here, we are using a background image for the HTML body page. We position the image on the left side with a 10px decrease from 50% and a 10px decrease from 50% on the top side.

Example #7

Code:

.heading { margin: 0 auto; outline: solid 1px; width: 250px; height: 250px; background: linear-gradient(to left bottom, transparent calc(75% – 1em), #000 0, #000 calc(75% + 1em), transparent 0); }

Output:

The program creates a line with a gradient background for the HTML page on the left side of the bottom. It provides the inner background to the element and the opacity level for the element by using the calc() function.

Example #8

Code:

.heading { width: calc(200% / 8); border: 1px dotted #5E9BC6; padding: 5px; } .demo{ background:grey; font-size: 15px; }

Output:

We define the div element with a heading class. This class will use 1/8 of the available window width and specified styles.

Conclusion

In this article, we have seen some helpful featufeaturesSS. The calc() function will operate as a value across all places where a number value with or without specific units works. It seems time to use our examples to learn more about the CSS calc() function.

Recommended Articles

We hope that this EDUCBA information on “CSS calc()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Decode() Function Works In Sql? Examples

Introduction to SQL DECODE()

DECODE function in Standard Query Language (SQL) is used to add procedural IF – THEN – ELSE like statements to a query. It compares a given expression with each search value one by one and returns a result on the basis of outcomes received from the comparison. A decode function basically performs the task of CASE statements. However, we should keep in mind that DECODE is a built-in function in ORACLE SQL databases and hence it is supported only in ORACLE 9i and above versions of ORACLE/ PL SQL. It is not recognized and supported in other database management servers such as PostgreSQL, SQL Server, MySQL etc. So, now we can use CASE statements to perform IF-THEN-ELSE logic in these databases.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax and Parameters:

The basic syntax for writing DECODE function in SQL is as follows:

DECODE (expression , search_1, result_1[, search_2, result_2], ...,[,search_n,result_n] [, default]);

expression: expression argument is the value which is to be searched and compared with.

search_1, search_2, …. search_n: These are the values to be searched for and then compared with the expression argument.

result_1, result_2, … , result_n: These arguments hold the result to be returned when the given comparison returns true. For example, if expression = search_1 then result will be result_1.

default: default argument holds the default value. It is more or less like the ELSE statement in IF-THEN-ELSE.

We can use the DECODE function as a part of the SELECT statement, ORDER BY etc.

How DECODE() Function works in SQL?

The first step is comparison of expression and search_1, if the expression = search_1 is TRUE then result_1 is returned. If it’s FALSE then DEFAULT value is returned. The DECODE function automatically converts or casts the expression to the data type of the first search argument or search_1. And it finally converts back the data_type of result to the data_type of the expression.

The functionality of DECODE in ORACLE with following flowchart.

Example:

Code:

SELECT DECODE(1, 1, 'One') FROM dual;

Output:

The simple illustration of the above mentioned decode function is as follows:

Code:

IF 1 = 1 THEN result = 'One' ENDIF; Examples of SQL DECODE()

Given below are the examples mentioned:

Let us first create a ‘college_details’ table which contains college id, college name, location and fees for demonstration purposes.

We can use the following SQL CREATE TABLE statement to perform the task.

Code:

CREATE TABLE college_details( college_id integer NOT NULL, college_name character varying(255) NOT NULL, college_location character varying(255) NOT NULL, fees numeric NOT NULL );

Output:

Having created the table, let us now input some random data in it to work with in the subsequent exercises. We can use the following insert statements.

Code:

INSERT INTO college_details VALUES (10001, 'Indian Institute of Technology Roorkee', 'Roorkee,India', 10000); INSERT INTO college_details VALUES (10002, 'Indian Institute of Technology Bombay', 'Mumbai,India', 10000); INSERT INTO college_details VALUES (10004, 'California Institute of Technology', 'California ,USA', 60520); INSERT INTO college_details VALUES (10003, 'Massachusetts  Institute of Technology', 'Massachusetts,India', 51520); select * from college_details;

The data in the “college_details” table after performing the above mentioned INSERT operations looks something as shown below:

Output:

Example #1

Simple SQL query to illustrate use of DECODE function.

Code:

SELECT college_id, DECODE (college_id,   10003,'Massachusetts, USA', 10004, 'California, USA', 'India') FROM college_details;

Output:

In this example, we have performed a simple SQL task for categorizing colleges based on their location.

Simple illustration of above mentioned DECODE function is as follows:

Code:

IF college_id = 10003 THEN result = 'Massachusetts' ELSE IF college_id = 10004 THEN result = 'California' ELSE result = 'India' ENDIF; Example #2

SQL query to illustrate abbreviation of college names based on the available data using DECODE function.

SELECT college_id, DECODE(college_name,'Massachusetts  Institute of Technology', 'MIT','California Institute of Technology','CalTech','IIT') as college_name FROM college_details ORDER BY college_id;

Output:

In the above example, we have performed the following IF-THEN-ELSE logic statements and then ordered the entire result set by college_id.

Code:

IF college_name = 'Massachusetts  Institute of Technology' THEN result = 'MIT' ELSE IF college_name = 'California Institute of Technology' THEN result = 'Caltech' ELSE result = 'IIT' ENDIF; Example #3

SQL query to categories college fees into affordable and expensive for an Indian student, considering everything above $ 10000 as expensive.

Code:

SELECT college_id,fees, DECODE(fees,10000,'Affordable','Expensive') FROM college_details ORDER BY college_id;

Output:

In the above example, we have performed the following task using the DECODE function and have then ordered the result set by college_id.

Code:

IF fees = '10000' THEN result = 'Affordable' ELSE result = 'Expensive' ENDIF; Conclusion

DECODE function is used to perform procedural IF-THEN-ELSE logic in SQL. The function is a close relative of CASE statements. It is a built-in function in ORACLE / PL SQL database management servers.

Recommended Articles

We hope that this EDUCBA information on “SQL DECODE()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Update the detailed information about How Linux Time Works With Examples? on the Hatcungthantuong.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!