Vlad Eugen Nitu
Vlad Eugen Nitu

Reputation: 305

t-sql query returns undefined after using ORDER BY

I am currently working with a MS SQL database on Windows 2012 Server I need to query only 1 column from a table that I only have access to read, not make any kind of changes.

Problem is that the name of the column is "Value" My code is this:

SELECT 'Value' FROM table

If I add

`ORDER BY 'Value'` 

The issue is that the query is returning an empty list of results.

Things I've tried already

Upvotes: 0

Views: 1016

Answers (2)

Serkan Arslan
Serkan Arslan

Reputation: 13393

it looks like your table has null values. and because of the order by all null values come first.

try to add filter like this

select Value FROM table 
where Value is not null and Value <> ''
order by Value

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269753

You are claiming that this query:

SELECT 'Value'
FROM table
ORDER BY 'Value'

Is returning no rows. That's not quite correct. It is returning an error because SQL Server does not allow constant expressions as keys for ORDER BY (or GROUP BY for that matter).

Do not use single quotes. In this case:

SELECT 'Value' as val
FROM table
ORDER BY val;

Or, if value is a column in the table:

SELECT t.Value
FROM table t
ORDER BY t.Value;

Value is not a reserved word in SQL Server, but if it were, you could escape it:

SELECT t.[Value]
FROM table t
ORDER BY t.[Value];

Upvotes: 2

Related Questions