Simple question.. just can\'t get the result set in the order I need :p
I have a table \"categories\"
id | name | parent
1 apple 0
If those with no parents had null in their parent column, your statement would be very simple:
SELECT id, name, parent FROM categories order by coalesce(parent, id), id;
If you insist on 0 representing no parent, you can use more verbose CASE WHEN ... THEN ... statement.
Edit:
-- Sorting by name instead
select a.id, a.name, a.parent
from categories a left join categories b on a.parent=b.id
order by coalesce(b.name, a.name), a.name