HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Why do sys.columns and INFORMATION_SCHEMA.COLUMNS display different number of columns

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
whynumbercolumnsinformation_schemadifferentsysanddisplay

Problem

I am trying two methods to display the columns with a particular name:

-
INFORMATION_SCHEMA.COLUMNS

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME='SUPPLIER_NAME';


-
SYS.COLUMNS

SELECT *
FROM SYS.COLUMNS
WHERE NAME='SUPPLIER_NAME'


Why do the queries display different output?

Solution

The difference between INFORMATION_SCHEMA.COLUMNS and sys.columns is the object types they cover. INFORMATION_SCHEMA.COLUMNS is restricted to tables and views. You can take a look at the code behind it by doing this:

EXEC sp_helptext [INFORMATION_SCHEMA.COLUMNS]


If you look at the bottom in the where clause you will see

o.type IN ('U', 'V')


This is where it is restricted to the tables and views only.

If you then go look at the definition of sys.columns you will see that it includes columns for a number of other objects:

  • Table-valued assembly functions (FT)



  • Inline table-valued SQL functions (IF)



  • Internal tables (IT)



  • System tables (S)



  • Table-valued SQL functions (TF)



Run this and you will be able to see what the extra object is and what type it is.

SELECT OBJECT_SCHEMA_NAME(object_id), OBJECT_NAME(object_id), 
    OBJECTPROPERTYEX(object_id, 'BASETYPE'), *
FROM sys.columns

Code Snippets

EXEC sp_helptext [INFORMATION_SCHEMA.COLUMNS]
o.type IN ('U', 'V')
SELECT OBJECT_SCHEMA_NAME(object_id), OBJECT_NAME(object_id), 
    OBJECTPROPERTYEX(object_id, 'BASETYPE'), *
FROM sys.columns

Context

StackExchange Database Administrators Q#72742, answer score: 18

Revisions (0)

No revisions yet.