0

Here's my code:

SELECT DISTINCT Column 3
FROM [TestTable].[dbo].data

I get an error on "Column 3". The error is Incorrect syntax near '3'.

My table has no column names so I don't know how to run my Select command on the third column.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MrPatterns
  • 4,184
  • 27
  • 65
  • 85
  • A table represents a relation, so should always have a column name. – user353gre3 Apr 04 '14 at 00:52
  • 1
    Possible duplicate http://stackoverflow.com/questions/368505/is-it-possible-to-select-sql-server-data-using-column-ordinal-position – Pablo Romeo Apr 04 '14 at 00:54
  • I upvoted you Pablo, I think you're right. From reading that post, it seems I MUST give my columns a name? – MrPatterns Apr 04 '14 at 00:56
  • But FYI, all table columns will always have names – Pablo Romeo Apr 04 '14 at 00:56
  • Now I am confused. I did not explicitly name any columns. How do I run my select command on the third column given that I just imported some data from a flat file, and did not take any actions to name columns? – MrPatterns Apr 04 '14 at 00:57
  • All tables have column names, except those that are the result of an aggregate like `COUNT`, `SUM`, `MIN`, and so forth. Those columns you can give a name by using an alias in the query (or a sub-query from which you then `SELECT`). If you "imported a flat file", you either have a table into which you imported it, or the "flat file" had a header row that named the columns; in either case, the columns have names. Do a `SELECT TOP 10 * FROM [TestTable].[dbo].data` to determine what you have for names. – Ken White Apr 04 '14 at 01:58

2 Answers2

2

If the name of you third column is indeed 'Column 3', you need to run this query:

SELECT DISTINCT [Column 3]
FROM [TestTable].[dbo].data
Rashmi Pandit
  • 23,230
  • 17
  • 71
  • 111
0

AFAIK it's impossible to have a table with no column names

Run

USE TestTable
GO

select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='data'

to get the column names

DeanOC
  • 7,142
  • 6
  • 42
  • 56
  • The result I got is that Column_NAME is "Column 0", "Column 1", etc...so I still don't get why my code won't work when I used "Column 3" (there are no quotes in all situations, I'm just using them here in my SO reply). – MrPatterns Apr 04 '14 at 01:03
  • 3
    If you got `"Column 0"`, then `Column 0` is the column name, and you simply surround it with square brackets, as in `SELECT [Column 0] FROM [TestTable].[dbo].data`. – Ken White Apr 04 '14 at 02:01