SQL Tip: Getting Available Letters
Wednesday, July 11th, 2007I’m in the middle of writing a glossary application with a table full of terms and definitions. Part of the requirements was to have an “index” of letters as the navigation at the top. Each letter would then browse the glossary for entrees beginning with that letter.
The SQL to get a list of all available letters is quite simple:
SELECT DISTINCT SUBSTR(`term`, 1, 1) AS `letter` FROM `terms`;
If you’re familiar with PHP’s substr
function, you will notice that the syntax is exactly the same:
substr(’string’, start_position, length)
Be sure to check up on the SUBSTR function in the MySQL manual for more information.