Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count columns of a table

Tags:

sql

mysql

For example :

tbl_ifo  id | name  | age | gender  ---------------------------- 1  | John  |  15 |  Male 2  | Maria |  18 |  Female 3  | Steph |  19 |  Female 4  | Jay   |  21 |  Male 

How can I count the columns of this table using mysql?

like image 579
rjmcb Avatar asked May 08 '12 03:05

rjmcb


People also ask

Can you count columns in SQL?

SQL COUNT FunctionIf we define a column in the COUNT statement: COUNT ([column_name]), we count the number of rows with non-NULL values in that column. We can specify to count only unique values by adding the DISTINCT keyword to the statement.

How do you count records in a table?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).


2 Answers

SELECT count(*) FROM information_schema.columns WHERE table_name = 'tbl_ifo' 
like image 150
swapnesh Avatar answered Sep 22 '22 15:09

swapnesh


I think you need also to specify the name of the database:

SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'SchemaNameHere'   AND table_name = 'TableNameHere' 

if you don't specify the name of your database, chances are it will count all columns as long as it matches the name of your table. For example, you have two database: DBaseA and DbaseB, In DBaseA, it has two tables: TabA(3 fields), TabB(4 fields). And in DBaseB, it has again two tables: TabA(4 fields), TabC(4 fields).

if you run this query:

SELECT count(*) FROM information_schema.columns WHERE table_name = 'TabA' 

it will return 7 because there are two tables named TabA. But by adding another condition table_schema = 'SchemaNameHere':

SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'DBaseA'   AND table_name = 'TabA' 

then it will only return 3.

like image 35
John Woo Avatar answered Sep 20 '22 15:09

John Woo