I need a query in sql to get total columns in a table.Can anybody help?
Select Table_Name, Count(*) As ColumnCount
From Information_Schema.Columns
Group By Table_Name
Order By Table_Name
This code show a list of tables with a number of columns present in that table for a database.
If you want to know the number of column for a particular table in a database
then simply use where
clause e.g. where Table_Name='name_your_table'
This query gets the columns name
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'
And this one gets the count
SELECT Count(*) FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'
SELECT COUNT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'table'
It can be done using:-
SELECT COUNT(COLUMN_NAME) 'NO OF COLUMN' FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Address'
The below query will display all the tables and corresponding column count in a database schema
SELECT Table_Name, count(*) as [No.of Columns]
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'dbo' -- schema name
group by table_name
Correction to top query above, to allow to run from any database
SELECT COUNT(COLUMN_NAME) FROM [*database*].INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'table'