Writing a sorting query involving two tables

I have two tables that looks like this:


Name               Type               
------------------ ------------------ 
ID                 NUMBER
Data               DOESN'T_MATTER

Open in new window


Name               Type               
------------------ ------------------ 
ID                 NUMBER
Reference_ID       NUMBER
Order              NUMBER

Open in new window

The values in that Data_table are:

ID		data
1		value_1
2		value_2
3		value_3
4		value_4
5		value_5

Open in new window

The values in the Sort_Table are:

ID		reference_id	order
1		2		2
2		3		1
3		5		3

Open in new window

Where the reference ID refers to the ID in the data_table.

I need a query to get the IDs from the Data_table in the order defined in the sort_table, but if anything from the data_table doesn't show up in the sort_table I want it to show up at the end like this:

1 -- this isn't in sort_table
4 -- this isn't in sort_table

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

  FROM Data_table d
  LEFT JOIN Sort_Table s ON s.reference_id = d.ID
 ORDER BY s.order, d.ID

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
buttonMASTERAuthor Commented:
That worked. Thank you very much!

Please note the NULL value can be sorted differently depending on SQL engine used. If values missing in the Sort_table are at the top you may use different expression in ORDER BY, e.g.:

ORDER BY -s.order DESC, d.ID

Also the [order] column name must be enclosed in brackets in some SQL engines...
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.