6/10/2015 MySQL :: MySQL 5.0 Reference Manual :: 12.6.2 Mathematical Functions https://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html 1/28 « 12.6.1 Arithmetic Operators 12.7 Date and Time Functions » Section Navigation [Toggle ] 12.6 Numeric Functions and Operators 12.6.1 Arithmetic Operators 12.6.2 Mathematical Functions MySQL 5.0 Reference Manual :: 12 Functions and Operators :: 12.6 Numeric Functions and Operators :: 12.6.2 Mathematical Functions 12.6.2 Mathematical Functions Table 12.12 Mathematical Functions Name Description ABS() Return the absolute value ACOS() Return the arc cosine ASIN() Return the arc sine ATAN2() , ATAN() Return the arc tangent of the two arguments ATAN() Return the arc tangent CEIL() Return the smallest integer value not less than the argument CEILING() Return the smallest integer value not less than the argument CONV() Convert numbers between different number bases COS() Return the cosine COT() Return the cotangent CRC32() Compute a cyclic redundancy check value DEGREES() Convert radians to degrees EXP() Raise to the power of FLOOR() Return the largest integer value not greater than the argument LN() Return the natural logarithm of the argument LOG10() Return the base-10 logarithm of the argument LOG2() Return the base-2 logarithm of the argument LOG() Return the natural logarithm of the first argument MOD() Return the remainder PI() Return the value of pi POW() Return the argument raised to the specified power POWER() Return the argument raised to the specified power RADIANS() Return argument converted to radians RAND() Return a random floating-point value ROUND() Round the argument SIGN() Return the sign of the argument SIN() Return the sine of the argument
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
6/10/2015 MySQL :: MySQL 5.0 Reference Manual :: 12.6.2 Mathematical Functions
MySQL 5.0 Reference Manual :: 12 Functions and Operators :: 12.6 Numeric Functions and Operators :: 12.6.2 Mathematical Functions
12.6.2 Mathematical Functions
Table 12.12 Mathematical Functions
Name DescriptionABS() Return the absolute valueACOS() Return the arc cosineASIN() Return the arc sineATAN2(), ATAN() Return the arc tangent of the two argumentsATAN() Return the arc tangentCEIL() Return the smallest integer value not less than the argumentCEILING() Return the smallest integer value not less than the argumentCONV() Convert numbers between different number basesCOS() Return the cosineCOT() Return the cotangentCRC32() Compute a cyclic redundancy check valueDEGREES() Convert radians to degreesEXP() Raise to the power ofFLOOR() Return the largest integer value not greater than the argumentLN() Return the natural logarithm of the argumentLOG10() Return the base-10 logarithm of the argumentLOG2() Return the base-2 logarithm of the argumentLOG() Return the natural logarithm of the first argumentMOD() Return the remainderPI() Return the value of piPOW() Return the argument raised to the specified powerPOWER() Return the argument raised to the specified powerRADIANS() Return argument converted to radiansRAND() Return a random floating-point valueROUND() Round the argumentSIGN() Return the sign of the argumentSIN() Return the sine of the argument
6/10/2015 MySQL :: MySQL 5.0 Reference Manual :: 12.6.2 Mathematical Functions
Returns the arc tangent of X, that is, the value whose tangent is X.
mysql> SELECT ATAN(2);
> 1.1071487177941
mysql> SELECT ATAN(2);
> 1.1071487177941
ATAN(Y,X), ATAN2(Y,X)
Returns the arc tangent of the two variables X and Y. It is similar to calculating the arc tangent of Y / X, exceptthat the signs of both arguments are used to determine the quadrant of the result.
mysql> SELECT ATAN(2,2);
> 0.78539816339745
mysql> SELECT ATAN2(PI(),0);
> 1.5707963267949
CEIL(X)
CEIL() is a synonym for CEILING().
CEILING(X)
6/10/2015 MySQL :: MySQL 5.0 Reference Manual :: 12.6.2 Mathematical Functions
Computes a cyclic redundancy check value and returns a 32-bit unsigned value. The result is NULL if the argumentis NULL. The argument is expected to be a string and (if possible) is treated as one if it is not.
Returns the value of e (the base of natural logarithms) raised to the power of X. The inverse of this function is LOG()(using a single argument only) or LN().
For exact-value numeric arguments, the return value has an exact-value numeric type. For string or floating-pointarguments, the return value has a floating-point type.
FORMAT(X,D)
Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns the result as astring. For details, see Section 12.5, “String Functions”.
HEX(N_or_S)
This function can be used to obtain a hexadecimal representation of a decimal number or a string; the manner inwhich it does so varies according to the argument's type. See this function's description in Section 12.5, “StringFunctions”, for details.
LN(X)
Returns the natural logarithm of X; that is, the base-e logarithm of X. If X is less than or equal to 0, then NULL isreturned.
If called with two parameters, this function returns the logarithm of X to the base B. If X is less than or equal to 0, orif B is less than or equal to 1, then NULL is returned.
Returns the argument X, converted from degrees to radians. (Note that π radians equals 180 degrees.)
mysql> SELECT RADIANS(90);
> 1.5707963267949
RAND(), RAND(N)
Returns a random floating-point value v in the range 0 <= v < 1.0. If a constant integer argument N is specified, itis used as the seed value, which produces a repeatable sequence of column values. In the following example, notethat the sequences of values produced by RAND(3) is the same both places where it occurs.
mysql> CREATE TABLE t (i INT);
Query OK, 0 rows affected (0.42 sec)
mysql> INSERT INTO t VALUES(1),(2),(3);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT i, RAND() FROM t;
+++
| i | RAND() |
+++
| 1 | 0.61914388706828 |
| 2 | 0.93845168309142 |
| 3 | 0.83482678498591 |
+++
6/10/2015 MySQL :: MySQL 5.0 Reference Manual :: 12.6.2 Mathematical Functions
User CommentsPosted by [name withheld] on November 28 2002 12:27am [Delete] [Edit]
My brother had a case where he wanted to sort randomly but ALSO use LIMIT so he could page results - of course random will be different each time.
He wanted a random order that was not random for the same session; so here is the idea:
In the web-side code calculate a numeric value which is likely to stay the same for a session, perhaps based on some session id, or timed-expiring cookie value, etc, or from short-term stable HTTP headers.
Also require a numeric and well distributed value for each record (doesn't have to be unique but works
6/10/2015 MySQL :: MySQL 5.0 Reference Manual :: 12.6.2 Mathematical Functions
... order by rand(numeric_field + session_value) LIMIT blah;
So we see the ordering is preserved as numeric_field+session_value will be the same for a session, and numeric_field + session value are NOT the same from row to row so we still get random ordering.
Sam Liddicott
Posted by Hyungjin Ahn on January 9 2003 5:17pm [Delete] [Edit]
I might be caused by compiler ability to count to upto 30 places under zero. Win32 mysql probably mighe be compiled with 32bit compiler ratherthan 64bit. -- Hyungjin Ahn([email protected])
Posted by Girish Kshirsagar on November 27 2003 8:06pm [Delete] [Edit]
You may need to compare columns in databases after converting say a string column to a numeric column. These comparisons are automatic
Examplein the WHERE clause you may have to do something like this
oem.oem_id=substring(sku,5,3)
Here sku is a string who substring starting from location 5 from left and then having total length of 3 is compared with a numeric value of oem_idto satisfy the WHERE clause.
For more details seehttp://www.bitmechanic.com/mail-archives/mysql/May1997/0494.html
Posted by [name withheld] on December 8 2003 1:01pm [Delete] [Edit]
I wanted to round to the nearest 0 or 5 cents in currency and this query worked:select round((((cost*100) - (cost*100)%5) /100), 2) from SessionCost;
Posted by [name withheld] on December 22 2003 4:27am [Delete] [Edit]
6/10/2015 MySQL :: MySQL 5.0 Reference Manual :: 12.6.2 Mathematical Functions
If "SELECT * FROM tab ORDER BY RAND()" doesn't work for you. Try to put a random value between the brackets.
Posted by Justin Laing on January 6 2005 9:45am [Delete] [Edit]
Here is my work around for MySQL rounding issues (On most systems it rounds to the nearest even number on 5). This mess of a calculation willround up always in mysql, which is how most people in the united states think about rounding:
This example rounds to 2 decimal places. If you want to round to three decimals just switch out the 2s for 3s and the 1000s for 10000s, etc.
It basically works by replacing all the fives beyond the two decimal places with sixes, which will always round up. Then calling the round function.
Posted by Joel Maxson on January 22 2005 5:38pm [Delete] [Edit]
Another way to round up to two decimals is using the following formula:floor(num * 100 + .55)/100
Posted by Tim White on February 18 2005 7:48pm [Delete] [Edit]
This may be self-evident but:In a list where some elements had priority and others not I needed to randomise the prioritised items and not the rest. The prioritised entries allhad a value of 1 in a field called 'enhanced' and all entries had an abbreviated name ('abbrev') that they were otherwise sorted by. Using ORDER BY (RAND() * enhanced) desc, abbrevI could change the order of the enhanced listings yet maintain an alphabetical listing thereafter.
Posted by Alejandro Vargas on September 27 2005 11:53am [Delete] [Edit]
WARNING WITH ROUND AND FORMAT FUNCTIONS:
As mentioned in the manual, ROUND function has problems with values near to the limit values. The same prblem is found in the format functionLet's see it:
round(1.15,1)=1.2 OKround(1.25,1)=1.2 BAD, sould be 1.3round(1.35,1)=1.4 OKround(1.45,1)=1.4 BAD, sould be 1.5round(1.55,1)=1.6 OK
And so on...
6/10/2015 MySQL :: MySQL 5.0 Reference Manual :: 12.6.2 Mathematical Functions
Of corse, if you want to use more than one digit, you should add as many 0 as you need to de value added in the truncate function. Note that in
case of using 2 digits, the result of format is correct but round stills failing. It is more reliable to do the calculation using your own formula, with
Posted by James Puddicombe on February 1 2007 2:44am [Delete] [Edit]
Simple but effective function for rounding to two decimals correctly (eg. 0.625 rounds to 0.63), unlike with the broken 'round' function
CREATE FUNCTION `v_round`(round_me DOUBLE)RETURNS decimal(10,2)DETERMINISTICSQL SECURITY DEFINERCOMMENT ''BEGINreturn round_me;END;
Posted by michael brenden on February 13 2007 9:50pm [Delete] [Edit]
Since using MySQL's RAND() function on a large rowset is notoriously slow:
To quickly select a random row, basically, do it in two SELECTS:
1. first SELECT finds out number of rows available, usnig a WHERE clause if desired.
2. web code chooses a random row from the number of rows (from step 1.) and saves this number in $x.
3. second SELECT (using the same WHERE clause in step 1.) uses LIMIT 1,$x.
Posted by József Rekedt-Nagy on March 28 2007 5:49am [Delete] [Edit]
Actually Order by Rand() Limit(1,X) won't work on larger sets, as it has to read through X-1 records to return the 1 you need.In avarage it means reading through <NumberOfRecords>/2 records every time, thus it's slow.
Posted by Nate Wiger on April 8 2007 7:12pm [Delete] [Edit]
Yes, using limit is a silly way of doing that. Why not just select with id = the random id you picked?
6/10/2015 MySQL :: MySQL 5.0 Reference Manual :: 12.6.2 Mathematical Functions
max = dbh.query("select max(id) from table").fetch_row.firstrand_id = rand(max)row = dbh.query("select * from table where id = #rand_id").fetch_hashputs "Fetched: #row['id']"
Posted by Hero Ulster Magoncia on April 13 2007 8:11am [Delete] [Edit]
Nate:Doing it that way doesn't work for everyone, some id values less than the max id might no longer exist in the table due to deletes.
Here's a simple solution (in php):
mysql_query('START TRANSACTION');
$count=mysql_fetch_row(mysql_query('SELECT COUNT(*) FROM table'));
$randomRow=mysql_fetch_row(mysql_query('SELECT * FROM table LIMIT '.(mt_rand(0,$count[0]-1)).',1'));
mysql_query('ROLLBACK');
Haven't really tested it, but you'd get the idea.It's similar to michael's idea (posted above), only he had the limit parameters in the wrong order.
Posted by Mike McKee on February 11 2008 7:40am [Delete] [Edit]
Instead of using RAND and LIMIT tricks for randomness, with their limitations on speed, if you have a primary key that's an auto-incrementer, youcould do it with these two SELECT like so:
SELECT MAX(pkey) FROM articles;
...then grab a random number (shown as $r below) between 1 and max in your code. Now return back to SQL like so:
SELECT * FROM articles where pkey > $r LIMIT $limit;
...where $limit is the number of rows you want to likely return.
...Then, to create the illusion of more randomness, just use an ORDER BY clause on the second SELECT above based on something arbitrary.For instance, if 'articles' has a column like author name and another like category, you could change the SELECT statement above like:
6/10/2015 MySQL :: MySQL 5.0 Reference Manual :: 12.6.2 Mathematical Functions
SELECT * FROM articles where pkey > $r ORDER BY category, name LIMIT $limit;
...So, by using this strategy, it's faster than having to randomly determine your pkeys and selecting only one record at a time.
In my case, I wanted to sort classified listings with some close approximation of randomness in order to rotate the listings, and this strategy hasworked for me.
Posted by Gerhard Wolkerstorfer on April 4 2008 9:55am [Delete] [Edit]
After I had problems with the ROUND() function in an accounting application where i need commercial rounding I wrote this stored function thatworks very well for my needs:
Posted by Szot Kamil on September 23 2008 12:03pm [Delete] [Edit]
If you want to select more records randomly you can use following method:
SET @toGet=10; SET @left=(SELECT COUNT(*) FROM tableName)+1;
SELECT *, @toGet:=@toGet-1FROM tableName WHERE (@left:=@left-1)>0 AND RAND()<@toGet/@left;
It's much faster than ORDER BY RAND() LIMIT 10 (especially if you want to fetch small random subset of rows stored in table) but if it happensto return same set of rows, it returns them always in same order. If you want them to have random order then you have to scramble them afterfetching using subquery:
SET @toGet=10; SET @left=(SELECT COUNT(*) FROM tableName)+1; SELECT * FROM (SELECT *, @toGet:=@toGet-1FROM tableNameWHERE (@left:=@left-1)>0 AND RAND()<@toGet/@left) t ORDER BY RAND()
or on client side.
Posted by Dave Turner on February 2 2009 9:39pm [Delete] [Edit]
Oddly truncate produces 2 different results for the same mathematical function with variations in placement of truncate in relation to a conditional:
6/10/2015 MySQL :: MySQL 5.0 Reference Manual :: 12.6.2 Mathematical Functions
Posted by Matthew Flaschen on March 28 2009 7:52am [Delete] [Edit]
Nearest even rounding is not bad. In fact, it results in less statistically biased results than always rounding up.
Posted by Guy Gordon on April 18 2009 6:38pm [Delete] [Edit]
If you reached this page looking for functions like MIN(a,b,...) and MAX(a,b,...) they are named LEAST()and GREATEST(), and are in section11.2.3. Comparison Functions and Operators.
Posted by Mike N on January 29 2011 1:12am [Delete] [Edit]
For those of you who need to implement banker's rounding in MySQL (handy if you're doing invoice reports and the numbers need to match upwith accounting software like Simply Accounting that use banker's rounding), this is what I use:
CREATE DEFINER=`root`@`%` FUNCTION `BROUND`( value DECIMAL(65,30), places TINYINT(3) UNSIGNED ) RETURNS decimal(65,30)COMMENT 'WARNING over decimal(65,30) will round normally!'DETERMINISTICRETURN CASE WHEN LOCATE( '.', value ) >= 1AND LENGTH( SUBSTRING( value, LOCATE( '.', value ) +1 ) ) < 31AND places > -1AND LENGTH( value ) - LOCATE( '.', value ) > placesAND SUBSTRING( value, LOCATE( '.', value ) + places + 1, 1 ) = 5
6/10/2015 MySQL :: MySQL 5.0 Reference Manual :: 12.6.2 Mathematical Functions
AND SUBSTRING( value, LOCATE( '.', value ) + places + 2 ) = 0AND SUBSTRING( value, LOCATE( '.', value ) + places + (CASE WHEN places = 0 THEN -1 ELSE 0 END ), 1 ) % 2 = 1
THENSUBSTRING( value, 1, LOCATE( '.', value ) + places + (CASE WHEN places = 0 THEN -1 ELSE 0 END ) )ELSE ROUND( value, places )END;
WARNINGS:
- The old function I had posted here before today was wrong, to anyone who used it I am deeply sorry.
- Also do not use Felipe's function below as it is broken because a correct BROUND(6.434503,3) function should indeed return 6.435, NOT6.434, as there is a 3 to the right of the 5. However BROUND(6.434500,3) WILL return 6.434. In banker's rounding, the only difference betweenregular rounding occurs when what is being rounded either ends in a 5, or ends in a 5 with a few zeroes after it. If however you do want thisincorrect behaviour for some reason, you can remove "AND SUBSTRING( value, LOCATE( '.', value ) + places + 2 ) = 0" from this or use Felipe'sfunction instead.
- Note that if you pass a value greater than 29 into my second parameter you will get regular rounding, because the DECIMAL data type has aprecision of 30, and to pass anything larger than 29 in the second parameter would mean you would have gone over that limit. To avoid getting afatal error when doing this, and for simplicity, I used strings in this function, and made it fail over to ROUND() in this instance.
- Do your own testing first of course
Posted by Felipe Loredo on November 13 2010 8:38pm [Delete] [Edit]
The BROUND posted by Mike N on March 9 2010 4:47pm doesn't works with bround(6.434503,3). The correct result is 6,435 but the functionreturns 6.434000000000000000000000000000.
Posted by Felipe Loredo on March 5 2011 10:17pm [Delete] [Edit]