# How to select the table with the greatest number of columns in MySQL?

MySQLMySQLi Database

You can use INFORMATION_SCHEMA.COLUMNS to get the table with the greatest number of columns.

The syntax is as follows −

SELECT TABLE_NAME, COUNT(*) AS anyAliasName
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY TABLE_NAME
ORDER BY yourAliasName DESC
LIMIT 1;

Following is the query to select the table that has the greatest number of columns. We are getting this result because we have set the count to DESC and used GROUP BY TABLE_NAME −

mysql> SELECT TABLE_NAME, COUNT(*) as TOTAL_COUNT
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY TABLE_NAME
ORDER BY TOTAL_COUNT DESC
LIMIT 1;

This will produce the following output −

+-----------------------------------+-------------+
| TABLE_NAME                        | TOTAL_COUNT |
+-----------------------------------+-------------+
| table_lock_waits_summary_by_table | 68          |
+-----------------------------------+-------------+
1 row in set (0.12 sec)

You can also get the least number of columns as well using the below query. We are getting this result because we have set the count to ASC and used GROUP BY TABLE_NAME −

mysql> SELECT TABLE_NAME, COUNT(*) as TOTAL_COUNT
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY TABLE_NAME
ORDER BY TOTAL_COUNT ASC
LIMIT 1;

This will produce the following output −

+-----------------------+-------------+
| TABLE_NAME            | TOTAL_COUNT |
+-----------------------+-------------+
| removenullrecordsdemo | 1           |
+-----------------------+-------------+
1 row in set (0.14 sec)
Published on 29-Apr-2019 07:24:21