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?
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.
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).
SELECT count(*) FROM information_schema.columns WHERE table_name = 'tbl_ifo'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With