Search code examples
sqlpostgresqlunionunion-allsql-limit

Selecting two columns in same table multiple times


I am trying to use the below query that shows country and population of second most and second least populous country. I figured out a way to select the population for those countries but I can't find any good way to implement selection of country names.

Select  Max(population) 
From country Where population < (Select max (population) From country)
Union
Select Min(population)
From country where population > (select Min(population) from country) ;

I found a way for selecting country and population for second most/second least populous country but problem is I can't use union on two selects with 2 ORDER BY (one in each select).

Any idea what I can do to solve my problem? Note: Im using Postgres


Solution

  • select *
    from (
        select country, population
        from
            (
                select country, population
                from country
                order by population
                offset 1 limit 1
            ) s
    
        union
    
        select country, population
        from
            (
                select country, population
                from country
                order by population desc
                offset 1 limit 1
            ) q
    ) s