1

I'm a mobile developer, but I've been doing some server work lately, so please excuse my terminology etc. I've been running into what might (??) be a difference between SQLite (which is what I use on iOS/Android) and PostgreSQL (which I use in APIs).

In SQLite, I could SELECT * from a table and then GROUP BY a single column without any aggregate functions at all. However, in PostgreSQL, it keeps complaining that it needs columns in the group by or an agg function.

Suppose I have a stop_times table which has these columns: stop_id, trip_id, stop_sequence, and departure_time. My trips table has a trip_id column and route_id. In SQLite, I have a query that looks like this:

SELECT * FROM "stop_times" 
  INNER JOIN "trips" ON "stop_times"."trip_id" = "trips"."trip_id" 
  WHERE "stop_times"."stop_id" IN (?, ?, ?) 
  GROUP BY "stop_times"."stop_id", "trips"."route_id"

(I'm trying to determine the stop_sequences of a particular set of stops along any routes that stop at them.) In PostgreSQL, however, this doesn't appear to work, as it complains until I put every column of stop_times into either the group by clause or an aggregate function. When I do, what I get back from the db is useless (in Rails, it's just a bunch of empty objects: #<StopTime >).

How can I achieve the same thing as above, but with Postgres?

1 Answer 1

1

You need to match column list with GROUP BY:

SELECT "stop_times"."stop_id", "trips"."route_id" 
FROM "stop_times" 
INNER JOIN "trips" ON "stop_times"."trip_id" = "trips"."trip_id" 
WHERE "stop_times"."stop_id" IN (?, ?, ?) 
GROUP BY "stop_times"."stop_id", "trips"."route_id"

or distinct on:

SELECT DISTINCT ON("stop_times"."stop_id", "trips"."route_id") *
FROM "stop_times" 
INNER JOIN "trips" ON "stop_times"."trip_id" = "trips"."trip_id" 
WHERE "stop_times"."stop_id" IN (?, ?, ?) 
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.