3

Is there a way to know the number of columns in SQL, something like count()...?

1

5 Answers 5

18

one way

select count(*) from sys.columns 

another

select count(*) from information_schema.columns

The bottom one does not have the system tables

by table

select count(*),table_name from information_schema.COLUMNS
GROUP BY table_name

tables only

select count(*),c.table_name 
from information_schema.COLUMNS c
JOIN information_schema.tables t ON c.TABLE_NAME = t.TABLE_NAME
AND c.TABLE_Schema = t.TABLE_Schema
WHERE TABLE_TYPE = 'base table'  
GROUP BY c.table_name

views only

select count(*),c.table_name 
from information_schema.COLUMNS c
JOIN information_schema.tables t ON c.TABLE_NAME = t.TABLE_NAME
AND c.TABLE_Schema = t.TABLE_Schema
WHERE TABLE_TYPE = 'view'  
GROUP BY c.table_name
1
  • Added the count grouped by table also
    – SQLMenace
    Commented May 5, 2011 at 19:01
9
Select Count(*) From INFORMATION_SCHEMA.COLUMNS Where TABLE_NAME='YourTableName'

or if you need to specify the schema

    Select Count(*) From INFORMATION_SCHEMA.COLUMNS Where TABLE_NAME='YourTableName' and TABLE_SCHEMA = 'YourSchema'
2

This should work across multiple RDBMS's:

select count(*) from INFORMATION_SCHEMA.COLUMNS

And if you want to get fancy:

select TABLE_NAME,
       count(*)
  from INFORMATION_SCHEMA.COLUMNS
group by TABLE_NAME
order by TABLE_NAME
0

For a particular table:

select * from sys.tables
where name = 'mytable';

Get the object_id from this, then use:

select count(*) from sys.columns
where object_id = 831342026;
0
SELECT count(*)
FROM Database_Name.INFORMATION_SCHEMA.COLUMNS
where table_name = 'Table_Name'

to Run 2 steps are needed : 1- choose the database_Name to your database name 2- Change Your Table Name Notes: if you didn't write database_Name like

from INFORMATION_SCHEMA.COLUMNS 

retrieves System database only

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.