Databases 7 min read

Optimizing PostgreSQL Queries for Flight Data Retrieval at Qunar

The article analyzes a slow PostgreSQL query that joins multiple tables to fetch flight numbers, compares several alternative query formulations with their execution plans, and presents a final solution using array aggregation to achieve sub‑millisecond performance despite existing indexes.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Optimizing PostgreSQL Queries for Flight Data Retrieval at Qunar

The author reports that a query selecting f.flight_no from tables btm m, bft f, and ptm i with several join conditions takes about 70 ms, even though the involved indexes appear normal.

By simplifying the query to select flight_no from bft where tm_id is in a static list (e.g., (1334090,1334091,1334093)), the execution time drops to roughly 0.17 ms, demonstrating the potential speed gain.

Further experiments show that using a sub‑query with an equality condition ( tm_id = (select item_id ...)) yields a fast runtime of about 0.055 ms, whereas using IN (select item_id ...) results in a slower nested‑loop plan with a runtime near 0.09 ms.

The final solution aggregates the relevant item_id values into an array and joins on that array:

select f.flight_no from btm m, bft f, (select array_agg(item_id) team_ids from ptm where product_id=3683170 and type=2 and status=1) i where m.id = f.traffic_main_id and m.id = any(i.team_ids);

This approach achieves a runtime of about 0.104 ms (≈2.8 ms total), effectively leveraging index scans.

The key insight is to rewrite the condition so that the planner can treat the comparison as an array operation, allowing it to use the existing index on bft.tm_id efficiently.

Author: He Weiping, a search and database researcher at Qunar, former Yahoo China search engineer, and translator of the PostgreSQL Chinese manual and Programming Perl 3rd edition.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

SQLquery optimizationPostgreSQLindexesDatabase Performance
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.