views:

56

answers:

1

Is it possible to query a MySQL database to get the column names of a table in alphabetical order? I know that

SHOW COLUMNS `table_name`;

or

DESCRIBE `table_name`;

will give me a list of the columns in a table (along with other info), but is it possible to alter the query in order to get the columns sorted alphabetically. Adding ORDER BY 'Field' didn't work, it gave a syntax error.

+2  A: 

The ANSI INFORMATION_SCHEMA tables (in this case, INFORMATION_SCHEMA.COLUMNS) provide more flexibility in MySQL:

SELECT c.column_name
  FROM INFORMATION_SCHEMA.COLUMNS c
 WHERE c.table_name = 'tbl_name'
-- AND c.table_schema = 'db_name'    
ORDER BY c.column_name
OMG Ponies
Worked great, would use again. Can you tell me why the c.table_schema condition is there though because it seemed to work without it.
John Scipione
@John Scipione: The double dash "--" is a comment in SQL; the table_schema is commented out from the query. Remove the double dash for it to be evaluated in the statement.
OMG Ponies