by santiagobasulto · 2y ago · 0 comments
Here are the two tested queries:
Query 1:
SELECT
t.passenger_name,
t.ticket_no,
bp.seat_no
FROM
Flights f
JOIN
Ticket_flights tf ON f.flight_id = tf.flight_id
JOIN
Tickets t ON tf.ticket_no = t.ticket_no
JOIN
Boarding_passes bp ON t.ticket_no = bp.ticket_no AND tf.flight_id = bp.flight_id
WHERE
f.arrival_airport = 'OVB';
Query 2: SELECT
t.passenger_name,
t.ticket_no,
bp.seat_no
FROM
Flights f
JOIN
Ticket_flights tf ON (f.flight_id = tf.flight_id AND f.arrival_airport = 'OVB')
JOIN
Tickets t ON tf.ticket_no = t.ticket_no
JOIN
Boarding_passes bp ON t.ticket_no = bp.ticket_no AND tf.flight_id = bp.flight_id
Then I ran EXPLAIN for both of them and the query plan is THE same. So there's not a big difference at least in Postgres.Here's the GPT conversation: https://i.imgur.com/dIzcfnc.jpeg
It doesn't let me share it because it contains an image
SELECT
t.passenger_name,
t.ticket_no,
bp.seat_no
FROM
Flights f,
Ticket_flights tf,
Tickets t,
Boarding_passes bp
WHERE
f.flight_id = tf.flight_id
AND f.arrival_airport = 'OVB'
AND tf.ticket_no = t.ticket_no
AND t.ticket_no = bp.ticket_no
AND tf.flight_id = bp.flight_id; SELECT
t.passenger_name,
t.ticket_no,
bp.seat_no
FROM Flights f
JOIN Ticket_flights tf USING (flight_id),
JOIN Tickets t USING (ticket_no),
JOIN Boarding_pass bp USING (ticket_no, flight_id)
WHERE f.arrival_airport = 'OVB';That's why it's not a bad idea to include the table name in the id column name: `flight.flight_id` instead of `flight.id`.
But yes, `USING` is convenient and pleasant to the eyes.
Works great in MySQL, PostgreSQL, and SQLite though.
Additionally, putting joins in the where clause breaks the separation of concerns:
FROM: specify tables and their relationships
WHERE: filter rows
SELECT: filter columns
*according to a LLM. Did you verify this?
Postgres is incredibly easy to spin up in a container to test things like this, and the mentioned schema (Postgres Air) is also freely available.
But if you can't infer from the column name which table they will come from, I find having the option to check far more preferable to that of having no way of knowing.
I suppose it depends on your database, one of the ones I work with all the time has crazy long table and view names and aliases make resulting SQL more readable.