SQL as a calculator. SQL made easy

In previous lessons we were introduced to basic SQL commands. Now, if you wish, you can extract, sort and even find the necessary data in the database. To do this, you just need to remember a few magic words.

In this lesson I will tell you about a somewhat non-standard use of the SQL language, namely using queries as a calculator. Let’s say you need to multiply two fairly large numbers that are difficult to multiply in your head, but you don’t have a calculator at hand. No problem, let’s write a request:

SELECT 123455789 * 987654321;

Let’s fulfill the request Here.

|———————–|
| 123455789 * 987654321 |
|———————–|
| 121931643458314269 |

So, it’s simple. This way you can use the SQL language for calculations. The database can handle more complex calculations just as easily:

SELECT (123455789 * 987654321) / 4 – 999;

Mathematical functions will not be difficult either. Trigonometry familiar from school the formula translated into SQL looks like this:

SELECT POW(SIN(0.5), 2) + POW(COS(0.5), 2)
|————————————-|
| POW(SIN(0.5), 2) + POW(COS(0.5), 2) |
|————————————-|
| 1 |

In addition to operations with numbers, you can operate with dates and strings. Let us give several examples of such operations. For example, let’s find out the day of the week of the first human flight into space:

SELECT DAYOFWEEK(‘1961-04-12’);

By running this request we learn that this significant event took place on Wednesday.

If, out of curiosity, we want to know the length of a string, we will use query with the LENGTH function.

As a summary, I would like to note that I did not set out to list all the functions of the SQL language (you can easily find them in the documentation for the desired database), the purpose of the lesson is to show that SQL is a powerful tool that allows you to easily perform the necessary calculations without resorting to other tools . Remind you that you can experiment with calculations in different databases on online SQL platform SQLize.online.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *