1

 I was wondering if there is a way to get rows ordered NOT by a column in the table(so no simple option to use ORDER BY or something like that).
 I tried both

SELECT *
FROM table
WHERE column IN ('A', 'B', 'C')

 and

SELECT *
FROM table
WHERE column = 'A' OR column = 'B' OR column = 'C'

 Then, the SqlDataReader in my C# application shows the rows in order like 'C', 'A', 'B' which is (probably) in sequence of the date written in the database.
 What I meant is not an alphabetical order but the order the each variable itself shows in the query.

  It isn't easy for me to search for the syntax in detail as a beginner of SQL Server. Also, I'm quite new here stack overflow, so let me know if I'm making any mistake. I would appreciate it if you do.
  Thank you in advance.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

 My bad. The given example was kind of ambiguous. Let me provide a clearer one.

SELECT *
FROM table
WHERE column IN ('r2', 'r4', 'r3', 'r1')

 And I want my SqlDataReader object to read 'r2' first, 'r4' next, 'r3' and then 'r1'.
 The application used to do it by querying for each single row using a loop and I was afraid that would harm the performance.

4
  • Sorry, what order do you want your data to be in? Commented Jun 14, 2013 at 3:18
  • 1
    you have to add a sorting column , such as creation date , id , etc , and sort by that column Commented Jun 14, 2013 at 3:18
  • Where are you getting this new order from and what are you doing that you require arbitrary order? Commented Jun 14, 2013 at 4:57
  • @ScottChamberlain I'm writing a 'Sentence analyzer' for natural language. the table is a kind of a "dictionary" and 'r1' to 'r4' represent different words. That's why I had to keep the sequence. Commented Jun 14, 2013 at 5:23

3 Answers 3

3
SELECT *
FROM table
WHERE (...expression...)
order by
case
when column='r2' then 1
when column='r4' then 2
when column='r3' then 3
when column='r1' then 4
else 9 end,column
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. This is the answer I've been looking forward to. I'm sorry that I can't upvote this due to the reputation limit.
2

In most cases SQL Server will return results based on clustered index if no "order by" clause is specified. So you may want to check the primary key or clustered index on your table.

Another option is you can add a running sequence number column & make it primary key.

Comments

0

Try:

SELECT *
FROM table
WHERE column IN ('A', 'B', 'C')
ORDER BY column DESC

To get it in C, B, A order.

1 Comment

O, I didn't meat that. I edited my question more clearly, so check it out again please.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.