I am running a SQL query that inserts a row into a table and then selects data from a view that joins the newly inserted row with other data. Here's the query I'm using:
WITH inserted AS (
INSERT INTO trips (
person_count
) VALUES (
5
) RETURNING id
)
SELECT
trip_id,
person_count,
routes
FROM
joined_trips_json,
inserted
WHERE
trip_id = inserted.id
;
The trips table has a corresponding view called joined_trips_json that joins the trips table with other tables. The WITH clause inserts a new row into the trips table and returns the id of the newly inserted row. The subsequent SELECT statement joins the joined_trips_json view with the inserted temporary result set on the trip_id and id fields.
However, when I execute this query, I don't get any rows back:
trip_id | person_count | routes
---------+--------------+--------
(0 rows)
trips
table definition:
CREATE TABLE IF NOT EXISTS public.trips
(
id integer NOT NULL DEFAULT nextval('trips_id_seq'::regclass),
start_timestamp timestamp with time zone,
person_count integer,
price real,
status text COLLATE pg_catalog."default",
created_at timestamp with time zone DEFAULT now(),
end_timestamp timestamp with time zone,
driver_id integer,
CONSTRAINT trips_pkey PRIMARY KEY (id)
)
joined_trips_json
view definition:
CREATE OR REPLACE VIEW public.joined_trips_json AS
SELECT t.id AS trip_id,
t.created_at,
t.driver_id,
t.status,
t.start_timestamp,
t.end_timestamp,
t.person_count,
t.price,
COALESCE(jsonb_agg(r.*) FILTER (WHERE r.* IS NOT NULL), '[]'::jsonb) AS routes
FROM trips t
LEFT JOIN trip_has_routes thr ON thr.trip_id = t.id
LEFT JOIN joined_trip_routes_json r ON r.route_id = thr.route_id
GROUP BY t.id;
I've verified that the row is indeed inserted into the trips
table, and I'm getting back the row from the joined_pois_json
when i execute the statements separately:
db=# INSERT INTO trips (person_count) VALUES (5) RETURNING id;
id
----
25
(1 row)
INSERT 0 1
db=# SELECT trip_id, person_count, routes FROM joined_trips_json WHERE trip_id = 25;
trip_id | person_count | routes
---------+--------------+--------
25 | 5 | []
(1 row)
I'm not sure why the view is not updating in real-time or why I'm not getting any rows back.
I'm using PostgreSQL 15 as my database system. Any help would be greatly appreciated!