1

I am trying to convert the following bit of code to work with PostgreSQL.

After doing some digging around I realized that PostgreSQL is much stricter (in a good way) with the GROUP BY than MySQL but for the life of me I cannot figure out how to rewrite this statement to satisfy Postgres.

def show
  show! do
    @recent_tasks = resource.jobs.group(:task).order(:created_at).limit(5)
  end
end

PG::Error: ERROR:  column "jobs.created_at" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: ...ND "jobs"."project_id" = 1 GROUP BY task ORDER BY created_at...
                                                         ^
: SELECT  COUNT(*) AS count_all, task AS task FROM "jobs"  WHERE "jobs"."deleted_at" IS NULL AND "jobs"."project_id" = 1 GROUP BY task ORDER BY created_at DESC, created_at LIMIT 5

1 Answer 1

1

You cannot use column in order which is not in group by.
You can do something like

@recent_tasks = resource.jobs.group(:task, :created_at).order(:created_at).limit(5)

but it will change result

You can also

@recent_tasks = resource.jobs.group(:task).order(:task).limit(5)

or

@recent_tasks = resource.jobs.group(:task).order('count(*) desc').limit(5)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.