ตัวอย่างการทดสอบประสิทธิภาพจริงบน PostgreSQL ด้วยข้อมูลจำลอง 1,000,000 แถว เพื่อหาช่วงเวลาที่คาบเกี่ยว (Overlap) ระหว่างวันที่ 2024-06-01 ถึง 2024-06-15
ชุดข้อมูลทดสอบ (1,000,000 แถว)
SQL
CREATE TABLE reservations (
id SERIAL PRIMARY KEY,
start_date DATE NOT NULL,
date_end DATE NOT NULL,
period DATERANGE GENERATED ALWAYS AS (daterange(start_date, date_end, '[]')) STORED
);
-- สุ่มช่วงเวลาจำลอง 1 ล้านแถว ในช่วงปี 2020 ถึง 2026 (ระยะเวลางาน 3-30 วัน)
INSERT INTO reservations (start_date, date_end)
SELECT
d AS start_date,
d + (floor(random() * 28) + 3)::int AS date_end
FROM (
SELECT DATE '2020-01-01' + (random() * 2500)::int AS d
FROM generate_series(1, 1000000)
) s;
-- สร้าง Index ทั้งสองแบบ
CREATE INDEX idx_btree_dates ON reservations (start_date, date_end);
CREATE INDEX idx_gist_period ON reservations USING GIST (period);
VACUUM ANALYZE reservations;