November 17 2014

Order by day of the week from Monday to Sunday

Tagged Under :

MySQL
A lot of people may be will ask how to sort day of the week with SQL query. Because Monday to Sunday it was string and MySQL cannot differentiate it was day or string inside the table.

But you are allow define inside the query how order the query with ORDER BY FIELD().

ORDER BY FIELD([fieldname], 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');

ORDER BY FIELD actually is custom ORDER BY in MySQL. It easy to let you sort the results needed by you.

November 14 2014

Getting the number of rows with a GROUP BY query in MySQL

Tagged Under :

MySQL
If you use the COUNT() function with GROUP BY. It will count the number of rows within each group, not the total number of rows. If you want count the number of rows with the groups, you are not allow use GROUP BY inside the query.

Instead of use GROUP BY you may use DISTINCT inside the query. The DISTINCT function similar with GROUP BY, but it can put inside the COUNT() function.

SELECT COUNT( DISTINCT(id) ) FROM table