Hudzilla.org - the homepage of Paul Hudson
Contents > Databases > SQL Wish List | Report Bug | About Me ]

9.3.15     MySQL functions

This is NOT the latest copy of this book; click here for the latest version.

MySQL has a large collection of functions you can use to make your SQL queries more powerful. While some of these can be done in PHP code once you have extracted the results of a MySQL query, doing them inside MySQL is often much faster, and also allows you to use the calculated value as part of a WHERE clause. These functions are MIN(), MAX(), COUNT(), SUM(), AVG(), UNIX_TIMESTAMP(), NOW(), and CONCAT(). These can be split into two distinct groups: query modifiers and field modifiers.

9.3.15.1 Query modifiers

These functions change the number of rows returned by your query, and therefore cannot usually be mixed with a normal query. If you find MySQL outputting the following error message, you know you have tried to mix these functions in where they should not be:

ERROR 1140: Mixing of GROUP columns (MIN(), MAX(), COUNT()...) with no GROUP columns is illegal if there is no GROUP BY clause.

MIN() and MAX() return the minimum and maximum values of a field you specify respectively. For example, to find the oldest person in usertable, you would use SELECT MAX(age) FROM usertable;. If the field chosen is a character field, MIN() and MAX() work alphabetically, so MIN() would return "Alex" before "Becky".

COUNT() returns the number of rows which match your query. For example, "SELECT COUNT(*) FROM usertable WHERE Age > 22;" would return the number of people in your table who are aged 23 or above.

SUM() adds up all the values in the attributes you select. Viz: SELECT SUM(Age) FROM usertable would return the ages of all the people in your table, added up.

AVG() adds up all the values in the attributes you select and divides that result by the number of values, giving the mean average. Viz: SELECT SUM(Avg) FROM usertable would return the average age of all members.

Going back to our golfscores example, we can use these functions to make better use of the GROUP BY clause. If you recall, MySQL was using the first value for the Score field for each MemberID rather than something helpful. Now that we've looked at MySQL functions, we can see how to get more useful values out of MySQL.

The most obvious example is, "what is the average score of this member?" To get that we need to use GROUP BY with the AVG() function, like this:

mysql> SELECT ID, MemberID, AVG(Score), DateEntered from golfscores GROUP BY MemberID;
+----+----------+------------+-------------+
| ID | MemberID | AVG(Score) | DateEntered |
+----+----------+------------+-------------+
|  1 |        1 |    71.2500 |  1089448558 |
|  4 |       13 |    78.5000 |  1089448576 |
|  3 |       43 |    69.0000 |  1089448569 |
+----+----------+------------+-------------+

Similarly, you can find the best score a player has returned (remember, in golf a lower score is better!):

mysql> SELECT ID, MemberID, MIN(Score), DateEntered from golfscores GROUP BY MemberID;
+----+----------+------------+-------------+
| ID | MemberID | MIN(Score) | DateEntered |
+----+----------+------------+-------------+
|  1 |        1 |         69 |  1089448558 |
|  4 |       13 |         77 |  1089448576 |
|  3 |       43 |         69 |  1089448569 |
+----+----------+------------+-------------+

Of course, many of these functions work fine without the GROUP BY clause. For example, to get the overall average score of all members, use this query:

mysql> SELECT AVG(Score) from golfscores;
+------------+
| AVG(Score) |
+------------+
|    73.0000 |
+------------+

9.3.15.2 Field modifiers

These functions affect one field only, changing the value it returns with the rest of the row. These functions can be used freely in all SELECT queries.

UNIX_TIMESTAMP() takes a MySQL time as a parameter, and returns the corresponding Unix timestamp. As PHP uses Unix timestamps, this is a very helpful function, especially when combined with NOW().

NOW() returns the current MySQL time. You'll need to combine it with UNIX_TIMESTAMP() to get a helpful number. If we had a table which stored a last login time for each person, we could use NOW() and UNIX_TIMESTAMP() combined like this:

SELECT * FROM Users WHERE LastLogonTime > UNIX_TIMESTAMP(NOW()) - 86400;

That query would return all users who have logged on in the last 24 hours. 86400 is the number of seconds in a day, so it searches for people who's last logon time is greater than (more recent than) the current time - 86400.

Finally, CONCAT() can take any number of parameters, and it returns them combined. So, to combine first name and second name with a space in the middle, you would use this query:

SELECT CONCAT(FirstName, ' ', LastName) FROM usertable;




<< 9.3.14 Grouping rows together with GROUP BY   9.3.16 Managing indexes >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Russ - 30 Aug 2008

the mean value does not equal the middle value. Two common terms used in statistics are mean and median. Mean refers to average. Median refers to middle number if all numbers in a dataset are ordered from greatest to lowest (or vice versa)

A PHP&MySQL User - 30 Aug 2008

"AVG() adds up all the values in the attributes you select and divides that result by the number of values, giving the mean average"

AVG() gives you the average of all values not the mean (middle) value. Please correct your statement.

M3Ali_103@hotmail.com - 30 Aug 2008

what about using user defined PHP functions in MYSQL? can me define make a function say somefunction in PHP and use this function in PHP statements like this
"SELECT somefunction(somefiled) from sometable;"?
Where somefield is a field in sometable

A PHP User - 30 Aug 2008

Why not include information about the GROUP_CONCAT-function of MySQL, is it 4.1 maybe? It is a great function that finally makes it possible to debug what data is chosen when there is many different matching records for a field in a group.

singpolyma AT gmail.com - 30 Aug 2008

MS SQL is VERY picky, and you're right I do believe that it requires something like requiring that all displayed fields be contained in the GROUP BY clause or something like that...

Rohit Sant/rohit_sant@hotmail.com - 30 Aug 2008

I have a doubt regarding the query and its subsequent query in the page.

mysql> SELECT ID, MemberID, AVG(Score), DateEntered from golfscores GROUP BY MemberID;

Does Mysql ask for the ID & DateEntered to be part of Group by clause as they are also to be displayed in the select query. I think this would work for Mysql but will it work for MS SQL Server. This is the basic doubt i have when it comes to "Group by". Please clarify this doubt of mine at your convenience.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is four plus ten?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow