Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Count number of columns in all tables, excluding views

I am creating a query that returns the number of columns in each table, but I want to exclude Views.

The following works but returns View results:

SELECT COUNT(*), table_name
FROM INFORMATION_SCHEMA.COLUMNS
Group By table_name

Any suggestions?

NOTE: MSSQL 2005+

like image 908
Remus Avatar asked Mar 01 '11 17:03

Remus


People also ask

How do I count the number of columns in a SQL table?

mysql> SELECT COUNT(*) AS NUMBEROFCOLUMNS FROM INFORMATION_SCHEMA. COLUMNS -> WHERE table_schema = 'business' AND table_name = 'NumberOfColumns'; The output displays the number of columns.

How do I get a list of all columns of a table in SQL?

USE db_name; DESCRIBE table_name; it'll give you column names with the type.


2 Answers

This assumes SQL 2005 or higher

SELECT 
    t.name,
    count(c.name)
FROM 

    sys.tables t 
    inner join sys.columns c
    ON t.object_id = c.object_id


group by t.name
like image 161
Conrad Frix Avatar answered Nov 15 '22 17:11

Conrad Frix


Something like this:

SELECT COUNT(col.column_name), col.table_name
FROM information_schema.columns col
  JOIN information_schema.tables tbl 
       ON tbl.table_name = col.table_name 
          AND tbl.table_schema = col.table_schema
          AND tbl.table_catalog = col.table_catalog
          AND tbl.table_type <> 'VIEW'
GROUP BY col.table_name
like image 31
a_horse_with_no_name Avatar answered Nov 15 '22 16:11

a_horse_with_no_name