First / Last Letter of a Column
Posted: May 4th, 2009 | Author: Troy | Filed under: MySQL | Tags: MySQL | No Comments »Will return if you have a record beginning with a distinct letter. sort them and count the records.
Useful for alphabetical lists.
For Left (First character):
SELECT DISTINCT LEFT(title. 1) AS letter. COUNT(*) as count FROM table GROUP BY letter ORDER BY count DESC;
For Left (Last character):
SELECT DISTINCT RIGHT(title. 1) AS letter. COUNT(*) as count FROM movies GROUP BY letter ORDER BY count DESC;
(Remember MySQL is optimized for count(*). count(*) actually being faster than count(id))