skip to Main Content

Suppose I have a table with column position and 10 rows with values:
[1, 2, 3, 1, 1, 1, 2, 4, 3, 2].

How do I select * from that table with only 1 row for each position?

I use Postgresql, and If I use limit 1 it returns only 1 value (obviously) and I need 1 value of each position with order by create_date field.

2

Answers


  1. How do I select * from that table with only 1 row for each position? I
    use Postgresql, and If I use limit 1 it returns only 1 value
    (obviously) and I need 1 value of each position with order by
    create_date field.

    You can do it using DISTINCT Keyword.

    SELECT DISTINCT ON (position) *
    FROM your_table
    ORDER BY position, create_date DESC;
    

    This will select one row per unique value in the position column with the most recent create_date

    Login or Signup to reply.
  2. It can be done using GROUP BY of position Column and then ORDER BY of position and create_date.

    SELECT * 
    FROM table_name 
    GROUP BY position 
    ORDER BY position, create_date;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search