0

I have a table in SQL server with two columns, Name and Order. Name is a varchar column which contains student names, Order is an int column which contains the number in ascending order corresponding to the Name column in alphabetical order.

For example, the expected result should be like below

Names - Order

ABC - 2
AAA - 1
CCC - 3
XZZ - 5
XYZ - 4

Is there any option to generate the order column automatically whenever a new name gets inserted into the table?

8
  • 2
    Tables have column, not fields. Commented Nov 16, 2020 at 9:11
  • Which dbms are you using? Commented Nov 16, 2020 at 9:11
  • Specify the expected result as well. Commented Nov 16, 2020 at 9:12
  • I am using SQL DB Commented Nov 16, 2020 at 9:12
  • 1
    Why do you need an order column? SQL Server will allow you to order alphabetically by the name column? And if you want a row number, us the row_number function. You don't need to store anything. Commented Nov 16, 2020 at 9:16

1 Answer 1

2

Order is an int column which contains the number in ascending order corresponding to the Name column in alphabetical order.

Just use row_number(). You should not be storing this derived information - instead, you can use a view:

create view myview as
select t.*, row_number() over(order by name) as rn
from mytable t

Note: order is a language keyword (as in order by ...), hence not a good choice for a column name; I used rn instead.

Sign up to request clarification or add additional context in comments.

Comments

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.