Skip to content
Advertisement

Order by multiple columns in the SELECT query

How can i order the results in my select query to have them like this?

1, 1, 0
1, 2, 0
1, 3, 0
1, 1, 1
1, 2, 1
1, 3, 1
2, 1, 0
2, 2, 0
2, 1, 1
2, 2, 1

I tried this query but the result is not what I’m looking for:

select * from my_table order by col1, col2, col3

In which col1 represents the first number, col2 is the second one and col3 is the last number in the above example.

This query returns:

1, 1, 0
1, 1, 1
1, 2, 0
1, 2, 1
...

Thanks

Advertisement

Answer

Sort should be 1-3-2, I’d say. See line #15.

SQL> with test (c1, c2, c3) as
  2    (select 2, 1, 0 from dual union all
  3     select 1, 3, 1 from dual union all
  4     select 1, 1, 1 from dual union all
  5     select 1, 1, 0 from dual union all
  6     select 1, 2, 0 from dual union all
  7     select 2, 2, 0 from dual union all
  8     select 2, 2, 1 from dual union all
  9     select 2, 1, 1 from dual union all
 10     select 1, 3, 0 from dual union all
 11     select 1, 2, 1 from dual
 12    )
 13  select *
 14  from test
 15  order by c1, c3, c2;

        C1         C2         C3
---------- ---------- ----------
         1          1          0
         1          2          0
         1          3          0
         1          1          1
         1          2          1
         1          3          1
         2          1          0
         2          2          0
         2          1          1
         2          2          1

10 rows selected.

SQL>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement