Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Relevant SQL Fiddle (postgres 9.2)

How do I state a SELECT .. ORDER BY .. that avoids having repeated values for a column?

That is, for rows of the column "rank" (1,3,3,1) how do I get a result so that rows of that column are ordered as (1,3,1,3), garuanteeing that a row with column value 1 is never follow by a row with column value 1, and similar for other rows values.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

You cannot avoid in it in all cases (if more than 50% of the rows have the same value in the column.) One way to achieve a "shuffle" result, similar to what you want is by using window function:

WITH cte AS
  ( SELECT *,
           ROW_NUMBER() OVER (PARTITION BY colX) AS rn
    FROM tableX 
  )
SELECT *
FROM cte
ORDER BY rn, colX ;

The above will not avoid all cases though. If for example, the values in the column are 1,1,1,1,2,2,3, you'll get:

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

and not the (better):

1,2,1,3,1,2,1
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.