Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo

SQL Functions - Math Functions

calculator

  • Please log in to reply
6 replies to this topic

#1 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 02 September 2009 - 05:28 AM

SQL Functions - Math Functions

Just like how programming languages have functions built-in to allow you to do common tasks easily. So does SQL. A lot of these functions are mathematical. Some of them are more useful than others.


ABS Function

The absolute value. The absolute value can be thought of as the distance from 0 on a number line to whatever number you have. So say your number is -5. The distance from 0 to -5 is 5. The distance from 0 to 5 is also 5. This is why the absolute value is simply the argument without any negative sign.

In math we write the absolute value as:

|a|

Now a formula for the absolute function is:

[QUOTE]
|a| = a, a >= 0
a*-1, otherwise
[/QUOTE]

Programmatically, this can be written as

int abs(int a) {
	if (a >= 0) {
		return a;
	}
	return a / -1;
}	

Let us take a look at how the abs function works.

Example:

SELECT ABS(-1) AS absolute;

Output:

[QUOTE]
1
[/QUOTE]

Let us try passing a positive value instead.

SELECT ABS(5) AS absolute;

Output:

[QUOTE]
5
[/QUOTE]

Trig Functions

The available trig functions are:

ACOS
ASIN
ATAN
TAN
COS
SIN

The first three are the inverse functions. So given a tangent value the resulting value is the angle with that tangent. The return value will be an angle in radians.

Example of COS:

SELECT COS(5.5) AS cosine;

Output:

[QUOTE]
0.70866977429126
[/QUOTE]

You can confirm the results by setting your calculator to radians and taking the cosine of 5.5.

While we are looking at cosine, let us look at ACOS. This function is the inverse cosine.

Example of SIN:

SELECT SIN(3.55) AS sine;

The SIN function also takes a parameter representing an angle in radians. The resulting value is then the sine of that angle.

Output:

[QUOTE]
-0.39714816728596
[/QUOTE]


Tangent

This function TAN also takes a parameter being the angle in radians. The output is the tangent of that angle.

Example:

SELECT TAN(3.5553) AS tangent;

Output:

[QUOTE]
0.43904601857096
[/QUOTE]

Granted, I'm not sure why you would need trig functions in a database application but they are there. Perhaps for games?

Rounding Functions

Two functions are CEIL and CEILING. These both take a floating point parameter. These functions return the smallest integer value that is not less than the parameter.

Example:

SELECT CEIL(5.35) AS roundedUp;

Output:

[QUOTE]
6
[/QUOTE]

You can think of this method as round up to the nearest integer. As for whichever you use, CEIL or CEILING they are both same function, so it comes down to personal choice.

Example of CEILING:

SELECT CEILING(5.35) AS roundedUp;

Output:

[QUOTE]
6
[/QUOTE]

These functions might be useful if you have a program that keeps track of how much you send and receive from the internet. However, you want to keep the values to the nearest megabyte. So you use ceiling to get the value to the nearest megabyte.

Floor Function

The floor function allows you to round a number to the largest integer value that is less than the parameter. You can think of this function as "rounding down".

Example:

SELECT FLOOR(5.35) AS roundedDown;

The output:

[QUOTE]
5
[/QUOTE]

Rounding

The function is ROUND.

This function allows you to specify how many digits you want to.

The generic formula is:

ROUND(X,Y)

This states that we are going to round X to Y decimal places.

SELECT ROUND(5.334333,2);

The result is:

[QUOTE]
5.33
[/QUOTE]

Converting Radians to Degrees

For one reason or another all programming languages seem to use radians to represent angles. However, from a young age we are brought up with the concept of degrees. So degrees naturally make more sense to us. To convert from radians to degrees we use the function DEGREES.


Let's say that we have a value in radians of 0.4567 and we want to convert it to degrees.

Example:

SELECT DEGREES(0.4567) AS deg;

Output:

[QUOTE]
26.1669825036247
[/QUOTE]

0.4567 radians is the same as 26.1669825036247 degrees. If we convert 26.1669825036247 back to radians, the resulting value should be 0.4567.

Converting Degrees to Radians

The function to convert to back to radians is RADIANS.

Example:

SELECT RADIANS(26.1669825036247) AS rad;

The output is:

[QUOTE]
0.4567
[/QUOTE]

This confirms that radians and degrees are inverse functions.

So:

SELECT RADIANS(DEGREES(x));

The resulting value is x.

Exponents

An exponent is simply multiplying a number by itself x times. So x^n means to multiply x by itself n times. So 5^3 = 5*5*5. This is what the POW function does for us.

Example:

SELECT POW(5,3) AS pow;

Output:

[QUOTE]
125
[/QUOTE]


Greatest and Max Functions

The greatest function takes a variable number of arguments and returns the largest value in the set.

Example:

SELECT GREATEST(5,3,8.5,9,-2,5,63,323,34,333);

Output:

[QUOTE]
333
[/QUOTE]

If you look at the values, you will have noticed that 333 is the largest value in the set.

To demonstrate the MAX function we actually need to create a table and populate it with some data.

In a database called test, create this table:

CREATE TABLE IF NOT EXISTS `nums` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `age` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

Then populate it with this data:

INSERT INTO `nums` (`id`, `age`) VALUES
(1, 3),
(2, 5);

The result:

SELECT MAX(age) FROM nums;

The output is:

[QUOTE]
5
[/QUOTE]

I wish I knew about this a long time ago. It is more efficient than my method. What I would always do is use ORDER BY to sort the list in descending order and LIMIT 1 would make the result at the top the largest value.

Example:

SELECT age FROM nums ORDER BY age DESC LIMIT 1;

Output:

[QUOTE]
5
[/QUOTE]

You can see the results are the same, but to get my answer I have to sort it. What if they are a lot of values? Granted I'm assuming that MAX also creates a temporary array of sorted values also, but I don't know.

Least and MIN Functions

This functions are very similar to the above functions. The MIN function selects the smallest value in a column. The least function takes a set of values and returns the smallest value in the set.

Example of least:

SELECT LEAST(5.5,3.5,2,4,-1) AS smallest;

Output:

[QUOTE]
-1
[/QUOTE]

Now we can use the table we created above to demonstrate the MIN function.

SELECT MIN(age) FROM nums;

Output:

[QUOTE]
3
[/QUOTE]

Looking at the table, we created, we can confirm that 3 is the smallest value in the list.

I didn't know a whole lot about SQL functions, so what I would do when I needed to do this was:

SELECT age FROM nums ORDER BY age ASC LIMIT 1;

Output:

3

This function sorts the column in ascending order and the first item is the smallest value in the column which is why I use LIMIT 1.

PI

This function simply returns the value of PI.

Example:

SELECT PI();

Output:

[QUOTE]
3.141593
[/QUOTE]

Random Number

This function chooses a random floating point number between 0 and 1. We can then manipulate this number with multiplication and addition to get a seemingly random number in a range.

SELECT RAND()

One possible output:

[QUOTE]
0.234685802119491
[/QUOTE]

Then we can multiply this value by some value and truncate the decimal. This allows us to limit the biggest value possible.

Example:

SELECT FLOOR(10*RAND())

We use FLOOR to truncate the decimal.

One possible output:

[QUOTE]
2
[/QUOTE]

Now by adding a value to the end, allows us to control the smallest possible value generated.

SELECT FLOOR(10*RAND())+1

One possible output:

[QUOTE]
5
[/QUOTE]

This function can be really useful in games.

Total Values

One really useful function is SUM. This function lets you find the total values in a column in a table. Going back to the table we created above, let us find the sum of all the ages.

SELECT SUM(age) FROM nums;

Output:

[QUOTE]
8
[/QUOTE]

Average

Now, say we want to know what the average age is. This is where the AVG function is useful.

SELECT AVG(age) FROM nums;

Output:

[QUOTE]
4.0000
[/QUOTE]

We get this value by adding up all the values in the column and dividing by the number of terms. In our case: (5+3)/2 = 4.

You can see how this function is more efficient than making a query to count the number of items. Then a query to find the sum. Then dividing them yourself. That is how I would have done it because I didn't know about this function.

Example:

SELECT SUM(age) / (SELECT COUNT(age) FROM nums) FROM nums;

Output:

[QUOTE]
4.0000
[/QUOTE]

My method isn't wrong, it is just a bad way to do it. Why iterate twice, when you can iterate and count at the same time? I don't have that kind of control with my method. I never actually did use that code above but it is a functional but poor way of doing it.

Modulus Function

This function simply returns the remainder of integer division.

We know that 5/2 = 2. This is because with integers there is no decimal point.

If we want the remainder, wecan use the mod function to determine the remainder.

Example:

SELECT MOD(5,2);

Result:

[QUOTE]
1
[/QUOTE]

Final notes

These are a lot that I didn't know about SQL. When I started my first project, I didn't know there was functions so I used other (possibly less efficient) methods to do what I wanted.

If I could, I would go back and change my program to use these functions. Granted, a lot of the functions I see no purpose for. Then again, my program was a database manager not a game or anything highly mathematical. The most math I did was adding and subtracting values. However, now I see how I could cut out a lot of queries from my program with these simple functions.

Another day we will look at inverse trigonometric functions and a more practical application of these functions.
  • 1

#2 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 02 September 2009 - 07:07 AM

There are a ton of functions in SQL, all useful. :) +Rep
  • 0

#3 BlaineSch

BlaineSch

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1559 posts

Posted 02 September 2009 - 08:02 AM

Good Job! +Rep!

In "Total Values" you forgot to replace the output with the correct output.

You must spread some Reputation around before giving it to chili5 again.


  • 0

#4 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 02 September 2009 - 08:03 AM

Oops. I fixed that. :) Thanks! :)
  • 0

#5 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 02 September 2009 - 12:44 PM

Nice list. Something worth noting is that these types of functions will vary slightly from one database to the next. Firebird doesn't have a sin() function by default, for example. +rep
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#6 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 02 September 2009 - 01:10 PM

So you can create your own functions then?

I'll looking into that. I wonder how that would work.
  • 0

#7 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 02 September 2009 - 01:11 PM

Firebird lets you call C (or maybe C++) functions.
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/