How to know the Column position in a table in MS-SQL.
Eg: if a table consists of 3 columns namely column1, column2 and column3.
I should write a query so that i can get the position of column3 as 3

- 619
- 3
- 9
- 22
-
If you want to select the column3 before column1 then you can achieve that using SELECT statement. – Himanshu Sep 23 '13 at 07:29
-
2In SQL, as much as possible, you should be ignorant of the "position" of columns - columns are referenced by *name*, not by position. What *problem* are you trying to solve such that finding the position of the column appears to you to be part of the solution? – Damien_The_Unbeliever Sep 23 '13 at 07:32
4 Answers
You will get all these from information_schema.
select ordinal_position from information_schema.columns
where schema_name = 'databasename'
and table_name = 'tablename'
and column_name = 'column name'

- 7,093
- 10
- 50
- 70
-
2you have to include schema_name in your query, there're could be two tables with name 'tablename' in different schemas – Roman Pekar Sep 23 '13 at 07:36
There're two ways to do this:
select colid
from sys.syscolumns
where id = object_id('schemaname.tablename') and name = 'column3'
and
select ordinal_position
from information_schema.columns
where
schema_name = 'schemaname' and
table_name = 'tablename' and
column_name = 'column3'
Here's an article about why you have to avoid information_schema views - The case against INFORMATION_SCHEMA views, I don't have to write this types of query often, so I don't really care about it, but sys.syscolumns tends to be a bit faster because it doesn't have many redundant joins which you may not need.
OTOH, information_schema views are ISO standard - here's dicussion about this - SQL Server: should I use information_schema tables over sys tables?

- 1
- 1

- 107,110
- 28
- 195
- 197
try :
SELECT ORDINAL_POSITION
FROM information_schema.columns
WHERE table_name = 'YourTableName' AND COLUMN_NAME = 'YourColumnName'

- 11,077
- 4
- 35
- 56

- 21,981
- 30
- 95
- 142
Try the query and check for the result.
select column_name,ordinal_position from information_schema.columns where table_catalog = 'yourdatabasename' and table_schema = 'yourschemaname' and table_name = 'yourtablename'

- 31
- 4