-1

The SQL:

select distinct
    h.teacher_id,
    h.last_updated_at,
    c.name
from sometable h 
   inner join class c on h.teacher_id=c.id
   where last_updated_at is not null
   order by last_updated_at desc limit 5;

I'm getting duplicate teacher_id in response. Where am I going wrong? I wanted to return last updated teacher name and id.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Bharat Bittu
  • 525
  • 1
  • 9
  • 26

2 Answers2

0

SELECT DISTINCT * FROM ... returns unique rows. The same teacher can appear many times while other columns differ.

If you want rows to be unique on selected column(s), use DISTINCT ON. Like:

SELECT DISTINCT ON (teacher_id)
       h.teacher_id,
     , h.last_updated_at
     , c.name
FROM   ...
ORDER  BY teacher_id, last_updated_at DESC
LIMIT  5;

Detailed explanation:

If you want a different ORDER BY, see:

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
0

You will probably see that the teacher_id in question has more than one class associated with it. If you need one record per teacher and all classes they lead, you can use something like STRING_AGG(c.name) (depending on your version of PostgreSQL). Alternatively, you can return the number of classes they lead with a COUNT(c.name).

In both cases, you will need to GROUP BY the teacher’s ID and last update.

matigo
  • 1,321
  • 1
  • 6
  • 16