cancel
Showing results for 
Search instead for 
Did you mean: 
Subscribe

Is it possible to sort a distinct statement based on another column (rather than the distinced one)?

For Example I have this table:

create or replace table mycities (cityid int, cityname varchar(40));
insert into mycities values
(4, 'Vienna'),
(2, 'Cairo'),
(1, 'Yerevan'),
(2, 'Cairo'),
(3, 'Berlin');

And I want to execute something like this, but I get an error.

select distinct cityname from mycities order by cityid;

View Entire Topic
regdomaratzki
Product and Topic Expert
Product and Topic Expert

If you have a distinct clause in the query, the order by clause can only include columns in the query's select list. From the documentation for the -854 error :

Probable cause You specified a function or column reference in the ORDER BY clause that is semantically invalid. For example, for DISTINCT queries the ORDER BY clause may only refer to items in the query's SELECT list.

Reg

regdomaratzki
Product and Topic Expert
Product and Topic Expert

How could the query below be properly sorted if this restriction did not exist?

create or replace table mycities (cityid int, cityname varchar(40));
insert into mycities values 
(1, 'Cairo'),
(2, 'Vienna'),
(3, 'Cairo'),
select distinct cityname from mycities order by cityid;