Get the number of columns in a MySQL table?

MySQLMySQLi Database

To get the number of columns, use the aggregate function count(*) with information_schema table from MySQL. The syntax is as follows to find the number of columns −

SELECT COUNT(*) as anyVariableName from INFORMATION_SCHEMA.COLUMNS where table_schema = ’yourDatabaseName’ and table_name = ’yourTableName’;

To understand the above syntax, let us create a table with some columns. The following is the query to create a table −

mysql> create table CountColumns
−> (
   −> Bookid int,
   −> BookName varchar(200),
   −> BookAuthorName varchar(200),
   −> BookPublishedDate datetime
−> );
Query OK, 0 rows affected (0.69 sec)

Now, we have total 4 columns in my table ‘CountColumns’. You can apply the above syntax to count the number of columns. The query is as follows −

mysql> SELECT COUNT(*) as NumberofColumns FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'business'
−> and table_name = 'CountColumns';

The output displays the count of columns −

| NumberofColumns |
| 4               |
1 row in set (0.00 sec)
Published on 10-Jan-2019 11:04:17