Skip to content

SQL Queries & Indexes Cheatsheet ​

مثال‌های کاربردی GROUP BY و HAVING، ترتیب index مرکب، ORDER BY بدون مرتب‌سازی و تشخیص استفاده از index در PostgreSQL 17/18 و MySQL 8.4 LTS (InnoDB).

این صفحه را چطور بخوانید ​

  • شکل پرس‌وجو (Query) را در نقشهٔ صفحه یا ماتریس پیدا کنید؛ هر مثال موقعیت، SQL، index، خط تعیین‌کنندهٔ برنامهٔ اجرا (Plan) و حکم (Verdict) را نشان می‌دهد.
  • همهٔ مثال‌ها از یک ساختار (Schema) استفاده می‌کنند. مبانی را در Indexing، Query planning و Pagination بخوانید؛ دستورها در Cheatsheetهای PostgreSQL و MySQL هستند.
  • پیش از ساختن یا حذف index، حکم را با EXPLAIN روی داده‌های خودتان بررسی کنید. آمار، اندازهٔ جدول و نسخه می‌توانند انتخاب برنامه‌ریز (Planner) را تغییر دهند.

خطوط Plan از مستندات پیش‌بینی شده‌اند و اجرا نشده‌اند. فقط گره یا خط key / Extra تعیین‌کنندهٔ حکم آمده است؛ هزینه‌ها و تعداد ردیف‌ها عمداً حذف شده‌اند.

نقشهٔ صفحه ​

بخش (Section)چه پرسشی را پاسخ می‌دهد؟موتور (Engine)
ساختار (Schema)مثال‌ها چه جدول‌ها و indexهایی را فرض می‌کنند؟PG, MySQL
خواندن Planکدام خط Plan نشان می‌دهد چه اتفاقی افتاده است؟PG, MySQL
GROUP BY و HAVINGشرط کجا قرار می‌گیرد و index چطور به گروه‌بندی کمک می‌کند؟PG, MySQL
Indexهای مرکب (Composite indexes)(tenant_id, status, created_at) به چه queryهایی پاسخ می‌دهد؟PG, MySQL
مسیرهای مرتب‌سازی (Sort paths)چه وقت ORDER BY بدون هزینهٔ sort است و چه وقت مرتب‌سازی می‌کند؟PG, MySQL
آیا index استفاده می‌شود؟چرا query از index ساخته‌شده استفاده نمی‌کند؟PG, MySQL
پیوند و زیرپرس‌وجو (Joins and subqueries)EXISTS، IN یا JOIN؟ کدام ستون‌ها index لازم دارند؟PG, MySQL
صفحه‌بندی (Pagination)OFFSET یا keyset، و با چه indexی؟PG, MySQL
پرس‌وجوهای تشخیصیکدام indexها بلااستفاده‌اند یا کم داریم؟PG, MySQL
چک‌لیستپیش از CREATE INDEX چه چیزهایی را بررسی کنم؟هر دو
خطاهای رایجاین کد خطا چه معنایی دارد؟PG, MySQL
از Go و Laravelچطور Plan را از کد برنامه ببینم؟Go, PHP

ساختار مشترک مثال‌ها (Schema) ​

هر مثال سه جدول دارد: مشتری‌ها، سفارش‌هایشان و اقلام سفارش. ستون tenant_id در orders قرار دارد چون تقریباً همهٔ queryهای چندمستاجری (Multi-tenant) از آن شروع می‌شوند.

sql
-- PostgreSQL 17/18
CREATE TABLE customers (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email      text        NOT NULL,
  country    text        NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE orders (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tenant_id   bigint        NOT NULL,
  customer_id bigint        NOT NULL REFERENCES customers (id),
  status      text          NOT NULL,          -- 'pending' | 'paid' | 'refunded'
  total       numeric(12,2) NOT NULL,
  created_at  timestamptz   NOT NULL DEFAULT now()
);
CREATE TABLE order_items (
  id       bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  order_id bigint        NOT NULL REFERENCES orders (id),
  sku      text          NOT NULL,
  qty      int           NOT NULL,
  price    numeric(12,2) NOT NULL
);
CREATE INDEX orders_tenant_status_created ON orders (tenant_id, status, created_at);
CREATE INDEX orders_customer_id          ON orders (customer_id);      -- FKs are not indexed for you
CREATE INDEX order_items_order_id        ON order_items (order_id);
sql
-- MySQL 8.4 (InnoDB): the same three tables; only the column types differ. Runs alone in an empty database.
CREATE TABLE customers (
  id         bigint       NOT NULL AUTO_INCREMENT PRIMARY KEY,
  email      varchar(255) NOT NULL,
  country    varchar(2)   NOT NULL,
  created_at datetime(6)  NOT NULL DEFAULT CURRENT_TIMESTAMP(6)
) ENGINE=InnoDB;
CREATE TABLE orders (
  id          bigint        NOT NULL AUTO_INCREMENT PRIMARY KEY,
  tenant_id   bigint        NOT NULL,
  customer_id bigint        NOT NULL,
  status      varchar(16)   NOT NULL,
  total       decimal(12,2) NOT NULL,
  created_at  datetime(6)   NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  KEY orders_tenant_status_created (tenant_id, status, created_at),
  KEY orders_customer_id (customer_id),
  CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (id)
) ENGINE=InnoDB;
CREATE TABLE order_items (
  id       bigint        NOT NULL AUTO_INCREMENT PRIMARY KEY,
  order_id bigint        NOT NULL,
  sku      varchar(64)   NOT NULL,
  qty      int           NOT NULL,
  price    decimal(12,2) NOT NULL,
  KEY order_items_order_id (order_id),
  CONSTRAINT fk_items_order FOREIGN KEY (order_id) REFERENCES orders (id)
) ENGINE=InnoDB;

دادهٔ اولیه (Seed data) شامل 4 مشتری است (ann@x.io و ANN@x.io یک نفرند) و 12 سفارش در اکتبر و نوامبر ۲۰۲۶ برای مستاجرهای 1 و 2. ساختار، دادهٔ اولیه و همهٔ queryهای قابل‌انتقال این صفحه با sqlite3 :memory: نسخهٔ 3.54.0 اجرا شده‌اند؛ همهٔ نتیجه‌های نمایش‌داده‌شده با آن اجرا مطابقت دارند. این بررسی SQL و نتیجه‌ها را تأیید می‌کند، اما چیزی دربارهٔ Plan اثبات نمی‌کند.

خواندن برنامهٔ اجرا (Plan) در 60 ثانیه ​

PostgreSQL. دستور EXPLAIN (ANALYZE, BUFFERS) <query> را اجرا کنید. ANALYZE واقعاً دستور را اجرا می‌کند؛ پس DML را داخل BEGIN … ROLLBACK قرار دهید. در PostgreSQL 18: "The ANALYZE option implicitly enables the BUFFERS option". درخت را از عمیق‌ترین گره به سمت بالا بخوانید.

خط Planمعنانشانهٔ خوب یا بد
Seq Scan on orders + Filter:همهٔ صفحه‌ها را می‌خواند و تک‌تک ردیف‌ها را بررسی می‌کندبرای جدول کوچک یا تطبیق بیشتر ردیف‌ها مناسب است؛ وقتی تعداد کمی باقی می‌مانند بد است
Index Scan using … on orders + Index Cond:index را طی می‌کند و سپس هر ردیف را از heap می‌گیردبرای ردیف‌های کم مناسب است؛ می‌تواند نتیجه را به ترتیب index بدهد
Index Only Scan using …پاسخ از index؛ مراجعه به heap فقط برای صفحه‌هایی که تمام ردیف‌هایشان قابل‌رؤیت (All-visible) نیستندبهترین حالت؛ Heap Fetches را بررسی کنید
Bitmap Index Scan → Bitmap Heap Scanنشانی ردیف‌ها را جمع می‌کند، سپس صفحه‌ها را به ترتیب فیزیکی می‌خواندبرای گزینش‌پذیری (Selectivity) متوسط؛ BitmapAnd/BitmapOr چند index را ترکیب می‌کنند
Sort / Incremental Sortمرتب‌سازی کل ورودی / مرتب‌سازی درون پیشوند ازپیش‌مرتب‌شدهوجود Sort زیر Limit یعنی index ترتیب موردنیاز را نداده است
HashAggregate / تجمیع مرتب (Sorted aggregate)گروه‌بندی با hash / پیمایش ورودی مرتب‌شده بر اساس کلید گروهSorted aggregate درست بالای index scan یعنی ترتیب از index آمده؛ نام دقیق گره متفاوت است، نامی را بخوانید که سرور خودتان چاپ می‌کند
Limit → پیمایش معکوس indexindex را از انتها می‌خواند ("The index can also be scanned backward") و زود متوقف می‌شودORDER BY … DESC LIMIT n بدون sort؛ برچسب دقیق گره متفاوت است
Nested Loop / Hash Join / Merge Joinالگوریتم پیوند (Join)Joinها را ببینید

MySQL. دستور EXPLAIN <query> برای هر جدول یک ردیف چاپ می‌کند. ستون‌های مهم:

ستون (Column)چطور بخوانید
typeروش دسترسی (Access method)، از بهترین تا بدترین: const → eq_ref → ref → range → index → ALL
keyindex واقعاً انتخاب‌شده؛ possible_keys نامزدها را فهرست می‌کند
key_lenتعداد بخش‌های کلید استفاده‌شده: "enables you to determine how many parts of a multiple-part key MySQL actually uses"
rows"the number of rows MySQL believes it must examine"؛ در InnoDB تخمین است
filteredدرصد تخمینی ردیف‌هایی که از شرط جدول عبور می‌کنند
ExtraUsing index یعنی پوشاننده (Covering)، Using index condition یعنی ICP؛ همچنین Using filesort، Using temporary، Using index for group-by، Using index for skip scan، Backward index scan

توصیهٔ مستندات: "If you want to make your queries as fast as possible, look out for Extra column values of Using filesort and Using temporary". دستور EXPLAIN FORMAT=TREE درخت پیمایشگرها (Iterators) را چاپ می‌کند. EXPLAIN ANALYZE از نسخهٔ 8.0.18: "runs a statement and produces EXPLAIN output along with timing" و "always uses the TREE output format". توضیح بیشتر: Query planning → MySQL.

GROUP BY و HAVING ​

WHERE ردیف‌ها را فیلتر می‌کند، HAVING گروه‌ها را ​

موقعیت (Situation): درآمد پرداخت‌شدهٔ هر مشتری را می‌خواهید، فقط برای مشتری‌هایی که درآمدشان بالاتر از 110 است.

sql
SELECT customer_id, sum(total) AS revenue
FROM orders
WHERE status = 'paid'            -- row filter: runs before grouping
GROUP BY customer_id
HAVING sum(total) > 110          -- group filter: needs the aggregate
ORDER BY customer_id;
-- result: (1, 112) (3, 195)

حکم (Verdict): شرطی که تجمیع (Aggregate) لازم ندارد باید در WHERE باشد. PostgreSQL: "WHERE selects input rows before groups and aggregates are computed … whereas HAVING selects group rows after groups and aggregates are computed"؛ قرار دادن محدودیت در WHERE هم "is more efficient". MySQL: "Do not use HAVING for items that should be in the WHERE clause". همچنین می‌گوید HAVING "is applied nearly last, just before items are sent to the client, with no optimization" و فقط "if you do not use GROUP BY or aggregate functions" آن را در WHERE ادغام می‌کند. روی جابه‌جایی شرط به‌دست موتور حساب نکنید.

مشتری با حداقل 3 سفارش پرداخت‌شده در 30 روز ​

موقعیت (Situation): گزارش وفاداری مشتری؛ بازهٔ 30 روزه از ۲۰۲۶-۱۱-۲۹ به عقب محاسبه می‌شود.

sql
SELECT customer_id, count(*) AS paid_orders
FROM orders
WHERE status = 'paid' AND created_at >= '2026-10-30'
GROUP BY customer_id
HAVING count(*) >= 3;
-- result: (1, 3) (3, 3)
CREATE INDEX orders_status_created_cust ON orders (status, created_at, customer_id);  -- optional
text
PG     Index Only Scan using orders_status_created_cust on orders      (then HashAggregate)
MySQL  type: range   key: orders_status_created_cust   Extra: Using where; Using index; Using temporary

حکم (Verdict): index محدودهٔ WHERE را کوچک می‌کند؛ ابتدا برابری روی status، سپس بازه روی created_at. اما مرحلهٔ گروه‌بندی (Grouping) را حذف نمی‌کند، چون ردیف‌ها به ترتیب created_at بیرون می‌آیند، نه customer_id. MySQL: "The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive".

یافتن مقدارهای تکراری ​

موقعیت (Situation): ایمیل‌هایی را پیدا کنید که با تفاوت حروف بزرگ و کوچک دو بار ذخیره شده‌اند.

sql
SELECT lower(email) AS email_norm, count(*) AS n
FROM customers
GROUP BY lower(email)
HAVING count(*) > 1;
-- result: (ann@x.io, 2)

حکم (Verdict): خواندن کل جدول اینجا عمدی است. جلوی ایجاد تکرار را بگیرید: در PG با CREATE UNIQUE INDEX ON customers (lower(email)) و در MySQL با UNIQUE KEY ((lower(email))). بخش index عبارتی (Expression index) را ببینید.

درآمد روزانه: تابع روی ستون ​

موقعیت (Situation): درآمد روزانهٔ هفتهٔ اول نوامبر را می‌خواهید.

sql
-- kills the index on created_at: the WHERE wraps the column in a function
WHERE date(created_at) = '2026-11-05'                 -- MySQL DATE(); PG created_at::date

-- keeps it: a half-open range on the bare column, the function only in GROUP BY
SELECT date(created_at) AS day, sum(total) AS revenue  -- PG: date_trunc('day', created_at)
FROM orders
WHERE status = 'paid' AND created_at >= '2026-11-01' AND created_at < '2026-11-08'
GROUP BY date(created_at)
ORDER BY day;
-- result: (2026-11-01, 50) (2026-11-02, 99) (2026-11-05, 100)

حکم (Verdict): وقتی در WHERE تابعی دور ستون قرار بگیرد، B-tree سادهٔ آن ستون قابل‌استفاده نیست؛ بازه روی خود ستون قابل‌استفاده است. PostgreSQL جست‌وجوی B-tree را روی ستون indexشده فقط برای "< <= = >= >" می‌سازد؛ به‌علاوهٔ BETWEEN، IN و IS NULL. تنها راه دیگر index عبارتی (Expression index) است، با این شرط: "All functions and operators used in an index definition must be 'immutable'". تابع date_trunc روی timestamptz این شرط را ندارد: "By default, truncation is done with respect to the current TimeZone setting".

شمارش شرطی: FILTER در برابر SUM(CASE) ​

موقعیت (Situation): داشبورد تعداد سفارش‌های پرداخت‌شده و کل سفارش‌های هر مستاجر را در یک query می‌خواهد.

sql
SELECT tenant_id,
       count(*) FILTER (WHERE status = 'paid')          AS paid_filter,  -- PostgreSQL
       sum(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_case,    -- both engines
       count(*)                                         AS all_orders
FROM orders GROUP BY tenant_id;
-- result: (1, 6, 6, 8) (2, 4, 4, 4)

حکم (Verdict): پاسخ یکسان است، با یک بار عبور از ردیف‌ها. PostgreSQL: "If FILTER is specified, then only the input rows for which the filter_clause evaluates to true are fed to the aggregate function". شکل قابل‌انتقال بین دو موتور SUM(CASE …) است.

ستون‌های بدون تجمیع (Aggregate): خطاهای 42803 و 1055 ​

موقعیت (Situation): گزارش هر مشتری ایمیل او را هم نشان می‌دهد؛ ویرایشی بی‌دقت گروه‌بندی را به کشور تغییر داده است.

sql
SELECT c.id, c.email, count(o.id) AS orders     -- legal: email depends on the PK c.id
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id;
-- result: (1, ann@x.io, 5) (2, bob@x.io, 3) (3, cy@x.io, 4) (4, ANN@x.io, 0)

SELECT c.country, c.email, count(*) FROM customers c GROUP BY c.country;  -- illegal in both

حکم (Verdict): اگر بر اساس کلید اصلی (Primary key) گروه‌بندی کنید، می‌توانید هر ستون همان جدول را انتخاب کنید. PostgreSQL: "A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column". در غیر این صورت PostgreSQL خطای 42803 grouping_error می‌دهد. MySQL با ONLY_FULL_GROUP_BY که پیش‌فرض فعال است، چنین queryهایی را با ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column … رد می‌کند. اگر می‌دانید مقدار در هر گروه یکتا است، ANY_VALUE(col) بنویسید.

count(DISTINCT) ​

موقعیت (Situation): چند مشتری متفاوت در هر مستاجر خرید کرده‌اند؟

sql
SELECT tenant_id, count(DISTINCT customer_id) AS buyers
FROM orders WHERE status = 'paid' GROUP BY tenant_id;
-- result: (1, 2) (2, 1)

حکم (Verdict): پاسخ دقیق است، اما باید همهٔ ردیف‌های واجد شرط دیده شوند. پیمایش سست index (Loose Index Scan) در MySQL فقط وقتی از COUNT(DISTINCT) پشتیبانی می‌کند که خود query دارای GROUP BY یا DISTINCT نباشد؛ بقیهٔ محدودیت‌ها نیز برقرارند (پایین‌تر).

HashAggregate در برابر تجمیع مرتب (Sorted aggregate) ​

موقعیت (Situation): صفحهٔ مدیریت تعداد سفارش‌ها را به تفکیک مستاجر و وضعیت نشان می‌دهد.

sql
SELECT tenant_id, status, count(*) FROM orders GROUP BY tenant_id, status;
-- result: (1, paid, 6) (1, pending, 1) (1, refunded, 1) (2, paid, 4)
text
PG     sorted aggregate (no Sort node)  ->  Index Only Scan using orders_tenant_status_created on orders
       (or HashAggregate  ->  Seq Scan on orders, when hashing all rows is cheaper)
MySQL  type: index   key: orders_tenant_status_created   Extra: Using index

حکم (Verdict): B-treeای که ستون‌های ابتدایی‌اش کلیدهای GROUP BY باشند می‌تواند ردیف‌ها را از قبل گروه‌بندی‌شده تحویل دهد. تنظیم enable_group_by_reordering در PostgreSQL به Planner اجازه می‌دهد: "GROUP BY keys sorted in the order of keys of a child node of the plan, such as an index scan". همچنان HashAggregate انتخاب معتبری است ("hashed aggregation plan types"). شرط MySQL این است: "all GROUP BY columns reference attributes from the same index, and that the index stores its keys in order". مبانی: تجمیع‌ها (Aggregates).

پیمایش سست index (Loose index scan) در MySQL: Using index for group-by ​

موقعیت (Situation): زمان آخرین سفارش هر مستاجر و هر وضعیت را در MySQL می‌خواهید.

sql
SELECT tenant_id, status, max(created_at) AS last_at
FROM orders GROUP BY tenant_id, status;
-- result: (1, paid, 2026-11-25 14:00) (1, pending, 2026-11-28 16:00) (1, refunded, 2026-11-21 08:00) (2, paid, 2026-11-12 10:00)
text
MySQL  type: range   key: orders_tenant_status_created   Extra: Using index for group-by

حکم (Verdict): برای هر گروه فقط چند کلید خوانده می‌شود، نه همهٔ ردیف‌ها. شرط‌ها: تنها یک جدول؛ GROUP BY باید "names only columns that form a leftmost prefix of the index"؛ تنها تجمیع‌ها (Aggregates) باید MIN()/MAX() روی یک ستون باشند که "must immediately follow the columns in the GROUP BY"؛ دیگر بخش‌های index شرط برابری با ثابت داشته باشند؛ و مقدار کامل ستون‌ها index شود، نه فقط پیشوندشان. افزودن sum(total) این شکل را از بین می‌برد.

آخرین ردیف هر گروه: تابع پنجره‌ای (Window) یا DISTINCT ON ​

موقعیت (Situation): تازه‌ترین سفارش هر مشتری را نشان دهید.

sql
-- both engines
SELECT customer_id, id, created_at
FROM (
  SELECT customer_id, id, created_at,
         row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC, id DESC) AS rn
  FROM orders
) t
WHERE rn = 1;
-- result: (1, 4, 2026-11-21 08:00) (2, 7, 2026-11-28 16:00) (3, 10, 2026-11-12 10:00)

-- PostgreSQL only
SELECT DISTINCT ON (customer_id) customer_id, id, created_at
FROM orders
ORDER BY customer_id, created_at DESC, id DESC;
CREATE INDEX orders_cust_created ON orders (customer_id, created_at DESC, id DESC);

حکم (Verdict): index منطبق با PARTITION BY / ORDER BY می‌تواند جای sort را بگیرد. PostgreSQL: "The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s)". «ردیف اول» هر مجموعه قابل‌پیش‌بینی نیست مگر ORDER BY ردیف مطلوب را اول قرار دهد. برای تعیین ترتیب هنگام برابری مقدارها، id را هم اضافه کنید.

indexهای مرکب (Composite indexes): ترتیب، پیشوند، بازه ​

قاعدهٔ بخش 11.3 مستندات PostgreSQL: "equality constraints on leading columns, plus any inequality constraints on the first column that does not have an equality constraint, will always be used to limit the portion of the index that is scanned". ستون‌های سمت راست‌تر "are checked in the index". MySQL هم همین را می‌گوید: "If the operator is >, <, >=, <=, !=, <>, BETWEEN, or LIKE, the optimizer uses it but considers no more key parts" و "MySQL cannot use the index to perform lookups if the columns do not form a leftmost prefix of the index". جزئیات: Indexing → composite.

ماتریس پیشوند چپ (Leftmost prefix) برای INDEX (tenant_id, status, created_at):

شکل queryمحدودهٔ پیمایش (Scan) را کم می‌کند؟دلیلراه‌حل (Fix)
tenant_id = 7بله، 1 ستونپیشوند چپ (Leftmost prefix)لازم نیست
tenant_id = 7 AND status = 'paid'بله، 2 ستوندو شرط برابری در ابتدای indexلازم نیست
tenant_id = 7 AND status = 'paid' AND created_at BETWEEN a AND bبله، هر 3 ستونبرابری، برابری، سپس یک بازه (Range)لازم نیست
tenant_id = 7 AND status IN ('paid','pending')بله، 2 ستونIN فهرستی از برابری‌هاست؛ MySQL: "equality range comparisons"لازم نیست
tenant_id = 7 AND created_at > Xهمیشه tenant_id؛ PG 18 ممکن است با پیمایش پرشی (Skip scan) از created_at هم استفاده کندstatus محدود نشده؛ پیش از PG 18 و در MySQL فقط created_at هر ورودی بررسی می‌شود؛ ICP در MySQL: Using index condition(tenant_id, created_at)
tenant_id = 7 AND status > 'p' AND created_at = Xtenant_id و status؛ PG 18 ممکن است داخل بازه پرش کندبازه روی status پایان محدودسازی تضمینی است؛ MySQL و PG 17 بعد از آن created_at را فقط بررسی (Check) می‌کنند، نه پیمایشاگر شکل غالب query همین است، ترتیب را به (tenant_id, created_at, status) تغییر دهید
فقط status = 'paid'خیرپیشوند چپ نیست؛ پیمایش کامل index یا Skip scanSkip scan فقط با تعداد کم مقدارهای tenant_id؛ در غیر این صورت (status, …)
فقط created_at > Xخیردو ستون ابتدایی محدود نشده‌اندindex مستقل روی created_at
tenant_id = 7 ORDER BY created_atمحدوده با tenant_id کم می‌شود، اما sort لازم استstatus وسط قرار دارد؛ ترتیب خروجی created_at نیست(tenant_id, created_at)؛ مسیرهای sort
tenant_id = 7 ORDER BY status, created_at LIMIT 20بله، بدون sortترتیب index با ترتیب درخواستی برابر استلازم نیست

اول برابری، بعد بازه ​

موقعیت (Situation): query سفارش‌های پرداخت‌شدهٔ مستاجر 7 از دوشنبه به بعد، با INDEX (tenant_id, created_at, status) کند است.

sql
SELECT id, total FROM orders
WHERE tenant_id = 7 AND status = 'paid' AND created_at >= '2026-11-23';
CREATE INDEX orders_t_s_c ON orders (tenant_id, status, created_at);   -- equality, equality, range
text
PG 17  wrong order (tenant_id, created_at, status):  Index Cond: tenant_id and created_at; status only checked inside the range
PG 18  wrong order: may skip-scan over status values inside the range (planner's choice)
       right order (tenant_id, status, created_at):  Index Cond: all three, one contiguous slice
MySQL  wrong order: key_len covers tenant_id + created_at;   right order: key_len covers all three

حکم (Verdict): ستون‌های برابری را پیش از ستون بازه قرار دهید. وقتی بازه در وسط باشد، MySQL و PostgreSQL 17 همهٔ ورودی‌های پرداخت‌نشدهٔ آن بازهٔ زمانی را هم می‌خوانند. با key_len تعداد بخش‌های کلید استفاده‌شده در MySQL را ببینید. PostgreSQL 18 با پیمایش پرشی (Skip scan) داخل بازه می‌تواند این هزینه را کمتر کند: "The skip scan optimization can also be applied selectively, during B-tree scans that have at least some useful constraints from the query predicate"؛ سپس "Index entries with c >= 77 will never need to be filtered at the table level, but it may or may not be profitable to skip over them within the index". Planner ممکن است این کار را بکند یا نکند؛ پس index با برابری در ابتدا همچنان انتخاب قابل‌اتکاست.

پیمایش پرشی (Skip scan) وقتی ستون ابتدایی در شرط نیست ​

موقعیت (Situation): گزارش فقط روی created_at شرط دارد، ولی تنها index با status شروع می‌شود که تعداد مقدارهای متمایزش کم است (Low cardinality).

sql
CREATE INDEX orders_status_created ON orders (status, created_at);   -- status has 3 values
SELECT status, created_at FROM orders WHERE created_at >= '2026-11-23';
text
PG 18  Index Only Scan using orders_status_created on orders  (skip scan: one descent per status value)
MySQL  type: range   key: orders_status_created   Extra: Using where; Using index for skip scan

حکم (Verdict): این روش فقط وقتی به‌صرفه است که ستون ابتدایی مقدارهای متمایز کمی داشته باشد. در یادداشت انتشار PostgreSQL 18 آمده: "Allow skip scans of btree indexes"؛ شرط انتخاب آن: "This approach is generally only taken when there are so few distinct x values that the planner expects the scan to skip over most of the index". MySQL 8.4 شرط‌های سخت‌گیرانه‌تری دارد: "The query references only one table"، "The query does not use GROUP BY or DISTINCT"، "The query references only columns in the index" و "There must be a range condition on C". نوشتن SELECT * روی این جدول امکان Skip scan در MySQL را از بین می‌برد. ببینید: Indexing → skip scan.

پوشاندن query (Covering): INCLUDE یا ستون انتهایی ​

موقعیت (Situation): فهرست سفارش‌های مستاجر فقط created_at و total را می‌خواهد، اما بیشتر هزینه صرف مراجعه به heap می‌شود.

sql
-- PostgreSQL: payload column, not part of the search key
CREATE INDEX orders_tenant_created_inc ON orders (tenant_id, created_at) INCLUDE (total);
-- MySQL: add it as a trailing key part (InnoDB already stores the PK in every secondary index)
CREATE INDEX orders_tenant_created_total ON orders (tenant_id, created_at, total);

SELECT created_at, total FROM orders WHERE tenant_id = 7 AND created_at >= '2026-11-01';
text
PG     Index Only Scan using orders_tenant_created_inc on orders
MySQL  type: range   key: orders_tenant_created_total   Extra: Using where; Using index

حکم (Verdict): query پوشانده شده است: InnoDB به جست‌وجوی index خوشه‌ای (Clustered index) نیاز ندارد؛ PostgreSQL فقط برای صفحه‌های تماماً قابل‌رؤیت (All-visible) از heap صرف‌نظر می‌کند. شرط query در PostgreSQL: "must reference only columns stored in the index". سپس برای هر ردیف نقشهٔ رؤیت‌پذیری (Visibility map) بررسی می‌شود: "If it's set, the row is known visible and so the data can be returned with no further work. If it's not set, the heap entry must be visited to find out whether it's visible". پس این پیمایش "will be a win only if a significant fraction of the table's heap pages have their all-visible map bits set". مقدار Heap Fetches را در EXPLAIN ANALYZE ببینید و بگذارید (auto)VACUUM نقشه را به‌روز نگه دارد. معنای Using index در MySQL: "retrieved from the table using only information in the index tree". در InnoDB، "each record in a secondary index contains the primary key columns for the row"؛ بنابراین id بدون هزینهٔ اضافی پوشانده می‌شود. ببینید: Indexing → covering.

کدام index برنده است و کدام اضافی؟ ​

  • چند نامزد: MySQL "normally uses the index that finds the smallest number of rows (the most selective index)". PostgreSQL هزینه‌های تخمینی حاصل از آمار را مقایسه می‌کند؛ ببینید گزینش‌پذیری (Selectivity).
  • (a) کنار (a, b) اضافی است. با (col1, col2, col3)، "you have indexed search capabilities on (col1), (col1, col2), and (col1, col2, col3)". (a) را حذف کنید مگر یکتا باشد یا برای query پرتکرارِ فقط-index به‌مراتب کوچک‌تر باشد.
  • (b, a) کنار (a, b) اضافی نیست. برای جست‌وجوی b = کاربرد دارد؛ (a, b) نمی‌تواند محدودهٔ این جست‌وجو را کم کند.
  • MySQL نامزدها را در sys.schema_redundant_indexes فهرست می‌کند؛ تشخیص را ببینید.

مسیرهای مرتب‌سازی (Sort paths): چه وقت ORDER BY رایگان است؟ ​

تازه‌ترین 20 سفارش ​

موقعیت (Situation): جریان سفارش‌ها در صفحهٔ مدیریت، 20 سفارش تازه را نشان می‌دهد.

sql
SELECT id, created_at FROM orders ORDER BY created_at DESC LIMIT 20;
CREATE INDEX orders_created ON orders (created_at);
text
no index   PG: Limit -> Sort -> Seq Scan            MySQL: type: ALL   Extra: Using filesort
index      PG: Limit -> index scan on orders_created, read backward (no Sort node)
           MySQL: type: index  key: orders_created  Extra: Backward index scan; Using index

حکم (Verdict): با index، مرتب‌سازی (Sort) هزینه‌ای ندارد و پیمایش بعد از 20 ردیف متوقف می‌شود. PostgreSQL: "if there is an index matching the ORDER BY, the first n rows can be retrieved directly, without scanning the remainder at all". بدون آن: "an explicit sort will have to process all the data to identify the first n rows". MySQL: "If ordering is done by using an index, this is very fast. If a filesort must be done, all rows that match the query without the LIMIT clause are selected". اینجا SELECT فقط ستون‌های indexشده را می‌خواهد. دربارهٔ Backward index scan در MySQL آمده: "Shown together with Using index".

فیلتر روی یک ستون، مرتب‌سازی روی ستون دیگر ​

موقعیت (Situation): 20 سفارش تازهٔ یک مستاجر را می‌خواهید و تنها index مرکب (Composite index)، (tenant_id, status, created_at) است.

sql
SELECT id, created_at, total FROM orders
WHERE tenant_id = 7 ORDER BY created_at DESC LIMIT 20;
CREATE INDEX orders_tenant_created ON orders (tenant_id, created_at);
text
only (tenant_id, status, created_at)   PG: Limit -> Sort -> Index Scan using orders_tenant_status_created
                                       MySQL: type: ref  key: orders_tenant_status_created  Extra: Using filesort
with (tenant_id, created_at)           PG: Limit -> index scan on orders_tenant_created, read backward (no Sort)
                                       MySQL: type: ref  key: orders_tenant_created  (no Using filesort)

حکم (Verdict): (tenant_id, created_at) ترتیب لازم را می‌دهد، اما (tenant_id, status, created_at) نمی‌دهد، چون status میان آن دو قرار دارد. MySQL: "key_part1 is constant, so all rows accessed through the index are in key_part2 order". بخش‌های استفاده‌نشدهٔ index باید "constants in the WHERE clause" باشند. استفاده از یک index برای WHERE و دیگری برای ORDER BY به Using filesort می‌انجامد: "The index used to fetch the rows differs from the one used in the ORDER BY".

جهت‌های ترکیبی ​

موقعیت (Situation): در نمای مستاجر، سفارش‌ها به ترتیب صعودی وضعیت و داخل هر وضعیت از تازه به قدیمی نمایش داده می‌شوند.

sql
SELECT id FROM orders WHERE tenant_id = 7 ORDER BY status ASC, created_at DESC;
CREATE INDEX orders_t_status_cdesc ON orders (tenant_id, status, created_at DESC);  -- PG and MySQL 8.4
text
plain (tenant_id, status, created_at)   PG: Sort or Incremental Sort    MySQL: Extra: Using filesort
mixed (…, status, created_at DESC)      PG: Index Scan using orders_t_status_cdesc (no Sort)
                                        MySQL: key: orders_t_status_cdesc, no Using filesort

حکم (Verdict): ترکیب ASC/DESC به index با همان ترکیب یا معکوس دقیق آن نیاز دارد. PostgreSQL: "no way to get that ordering from a plain index, but it is possible if the index is defined as (x ASC, y DESC) or (x DESC, y ASC)". MySQL 8.4: "DESC in an index definition is no longer ignored but causes storage of key values in descending order" و "the index must have the same homogeneity, but need not have the same actual direction".

مرتب‌سازی تدریجی (Incremental Sort) در PostgreSQL ​

موقعیت (Situation): سفارش‌ها باید اول بر اساس مشتری و بعد تاریخ مرتب شوند؛ فقط index تک‌ستونی customer_id موجود است.

sql
SELECT id FROM orders ORDER BY customer_id, created_at LIMIT 50;   -- only orders_customer_id exists
text
PG     Limit -> Incremental Sort (Presorted Key: customer_id) -> Index Scan using orders_customer_id
MySQL  Extra: Using filesort

حکم (Verdict): بخشی از کار کم می‌شود: index کلید اول را مرتب می‌دهد و فقط ردیف‌های داخل هر گروه sort می‌شوند. "sorting incrementally allows returning tuples before the entire result set has been sorted, which particularly enables optimizations with LIMIT queries"؛ تنظیم enable_incremental_sort پیش‌فرض فعال است. index روی (customer_id, created_at) مرتب‌سازی را کاملاً حذف می‌کند.

جای NULLها ​

موتور (Engine)پیش‌فرض B-tree صعودی / ORDER BY xچه چیزی sort رایگان را از بین می‌برد؟
PostgreSQL"ascending order with nulls last"؛ پیمایش معکوس DESC NULLS FIRST می‌دهدORDER BY x NULLS FIRST روی index پیش‌فرض؛ آن را با (x NULLS FIRST) تعریف کنید
MySQL"NULL values are presented first if you do ORDER BY ... ASC and last if you do ORDER BY ... DESC"انتقال NULLها به انتها با ORDER BY x IS NULL, x یک عبارت است؛ پس Using filesort: "ORDER BY with an expression that includes terms other than the index column name"

DISTINCT و GROUP BY از ترتیب استفاده می‌کنند؛ عبارت‌ها آن را می‌شکنند ​

  • SELECT DISTINCT tenant_id, status FROM orders می‌تواند index مرکب (Composite index) را به ترتیب بخواند. MySQL: "In most cases, a DISTINCT clause can be considered as a special case of GROUP BY"، اما "DISTINCT combined with ORDER BY needs a temporary table in many cases".
  • ORDER BY lower(email)، ORDER BY total * 1.2 یا نام مستعار (Alias) که عبارتی را پنهان کند، باعث sort می‌شوند. در MySQL نام مستعار a برای ABS(a) یعنی "the index on t1.a cannot be used".
  • ترتیب تطبیق متفاوت (Collation) انطباق را از بین می‌برد. PostgreSQL: "An index can support only one collation per index column"؛ index بر مبنای Collation ستون "cannot accelerate queries that involve some other collation". (email COLLATE "C") بسازید یا از کلاس عملگر (Operator class) استفاده کنید.
  • ORDER BY random() همیشه همهٔ ردیف‌ها را مرتب می‌کند؛ هیچ indexی این ترتیب را ذخیره نکرده است.

آیا index استفاده می‌شود؟ ماتریس تصمیم ​

در هر ردیف، یک B-tree ساده روی ستون موردبحث و Schema بالا فرض شده است. هر مورد را با EXPLAIN روی دادهٔ خودتان بررسی کنید.

شکل queryB-tree ستون استفاده می‌شود؟دلیلراه‌حل (Fix)
lower(email) = 'ann@x.io'خیرindex مقدار email را ذخیره می‌کند؛ query مقدار lower(email) را مقایسه می‌کندindex عبارتی (Expression index) روی lower(email)؛ در MySQL: ((lower(email)))
date(created_at) = '2026-11-05'خیرتابع روی ستونبازهٔ نیمه‌باز روی خود ستون
created_at + interval '1 day' > now()خیرمحاسبه در سمت ستونمحاسبه را منتقل کنید: created_at > now() - interval '1 day'
total * 1.1 > 100خیرهمان مسئله: عبارت است، نه خود ستونtotal > 100 / 1.1
PG bigint_col = '42'بلهمقدار ثابت داخل کوتیشن نوع unknown دارد و به‌صورت bigint گرفته می‌شودلازم نیست
MySQL varchar_col = 42خیر"For comparisons of a string column with a number, MySQL cannot use an index on the column"با '42' مقایسه کنید
email LIKE 'ann%'بله، بازه (Range)الگوی ثابت از ابتدای رشته شروع می‌شودPG در locale غیر C: text_pattern_ops
email LIKE '%x.io'خیرنویسهٔ جایگزین (Wildcard) در ابتدا؛ پیشوندی برای جست‌وجو نیسترشتهٔ معکوس را index و پیشوند را جست‌وجو کنید؛ Expression index در PG، ستون تولیدشده (Generated column) در MySQL؛ در PG همچنین GIN با pg_trgm
tenant_id = 1 OR customer_id = 3ترکیب دو indexیک index نمی‌تواند OR بین ستون‌ها را پاسخ دهدPG: BitmapOr؛ MySQL: index_merge و Using union(...)
status IN ('paid','pending')بلهIN مجموعه‌ای از شرط‌های برابری استلازم نیست
status <> 'paid' / NOT IN (…)معمولاً خیردر PG، <> عملگر جست‌وجوی B-tree نیست؛ MySQL می‌تواند "two intervals" بسازد، اما بیشتر ردیف‌ها را می‌پوشانندindex جزئی (Partial index) روی مقدارهای نادر
shipped_at IS NULLبلههر دو موتور NULL را index می‌کنند؛ MySQL همان بهینه‌سازی = constant را دارداگر نادر است، Partial index در PG با WHERE shipped_at IS NULL
status = 'paid' روی 90% ردیف‌هاخیر، و درست استخواندن ترتیبی بیشتر جدول ارزان‌تر استلازم نیست؛ مقدارهای نادر را index کنید
هر شرط روی جدول 100 ردیفیخیر، و درست استخواندن یک صفحه از پایین‌رفتن در درخت index ارزان‌تر استلازم نیست
بارگذاری انبوه تازه، آمار قدیمیاحتمال Plan نادرستتخمین‌ها از ANALYZE می‌آیندANALYZE orders; / ANALYZE TABLE orders;
Expression index روی lower(email)، شرط upper(email) =خیرعبارت باید منطبق باشدعبارت یکسان در query و index
Partial index با WHERE status = 'pending'، شرط status = $1خیر، در برنامهٔ عمومی (Generic plan)"parameterized query clauses do not work with a partial index"مقدار ثابت در SQL یا index کامل
OFFSET 100000 LIMIT 20بله، اما 100,020 ورودی می‌خواندردیف‌های ردشده هم محاسبه می‌شوندKeyset
بررسی شمول (Containment) در JSONB با @>فقط با GINGIN از @> پشتیبانی می‌کند، B-tree نمی‌کندUSING GIN (doc) یا jsonb_path_ops
JSONB doc ->> 'sku' = 'A'با GIN روی doc خیرعملگر روی خود ستون indexشده نیستExpression index روی (doc ->> 'sku')
Join ستون utf8mb4 به ستون latin1 در MySQLخیرمجموعه‌نویسه‌های متفاوت: "precludes use of an index"charset و Collation یکسان در دو طرف
id::text = $1؛ تبدیل نوع (Cast) روی ستونخیرCast تابعی روی ستون استپارامتر را Cast کنید: id = $1::bigint
ORDER BY random() LIMIT 1خیرsort روی مقداری که هیچ indexی ذخیره نمی‌کندنمونه‌گیری با بازهٔ کلید یا TABLESAMPLE
sql
-- PostgreSQL fixes for the matrix rows above
CREATE INDEX customers_email_lower ON customers (lower(email));
CREATE INDEX customers_email_pattern ON customers (email text_pattern_ops);        -- LIKE 'abc%' in a non-C locale
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX customers_email_trgm ON customers USING gin (email gin_trgm_ops);    -- LIKE '%abc'
CREATE INDEX orders_pending ON orders (created_at) WHERE status = 'pending';      -- rare value only
CREATE INDEX customers_email_rev ON customers (reverse(email) text_pattern_ops);   -- suffix search as a prefix
SELECT id FROM customers WHERE reverse(email) LIKE reverse('x.io') || '%';      -- matches the indexed expression
-- MySQL 8.4
CREATE INDEX customers_email_lower ON customers ((lower(email)));
ALTER TABLE customers
  ADD COLUMN email_rev varchar(255) AS (REVERSE(email)) VIRTUAL,
  ADD INDEX customers_email_rev (email_rev);                                     -- index on a virtual generated column
SELECT id FROM customers WHERE email_rev LIKE CONCAT(REVERSE('x.io'), '%');

چرا جست‌وجوی پسوند (Suffix search) جواب می‌دهد؟ در PostgreSQL، reverse چنین عمل می‌کند: "Reverses the order of the characters in the string". در MySQL، REVERSE(str): "Returns the string str with the order of the characters reversed". پسوند معکوس‌شده به پیشوندی متصل به ابتدای رشته تبدیل می‌شود و B-tree آن را پاسخ می‌دهد: "anchored to the beginning of the string"؛ در MySQL آرگومان LIKE باید "does not start with a wildcard character" باشد. همچنین در MySQL: "InnoDB supports secondary indexes on virtual generated columns". اینجا سراغ FULLTEXT نروید؛ کلمه را تطبیق می‌دهد، نه پسوند را. تجزیه‌گر آن رشته را در جداکننده‌هایی مثل ". (period)" می‌شکند؛ ضمن اینکه "The default minimum length of words that are found by full-text searches is three characters for InnoDB search indexes". پس x و io اصلاً index نمی‌شوند.

sql
-- JSONB (PostgreSQL): containment uses GIN, a key extraction needs its own expression index
CREATE INDEX events_doc_gin ON events USING gin (doc);
SELECT id FROM events WHERE doc @> '{"sku": "A"}';           -- Bitmap Index Scan on events_doc_gin
CREATE INDEX events_doc_sku ON events ((doc ->> 'sku'));
SELECT id FROM events WHERE doc ->> 'sku' = 'A';              -- Index Scan using events_doc_sku

عبارت‌های مستندات که مبنای ماتریس‌اند:

  • تطبیق الگو (Pattern match) در PG: B-tree برای LIKE کاربرد دارد "if the pattern is a constant and is anchored to the beginning of the string — for example, col LIKE 'foo%' or col ~ '^foo', but not col LIKE '%bar'". در MySQL شرط بازه به آرگومان LIKE نیاز دارد که "does not start with a wildcard character". indexهای pg_trgm نیز "support trigram-based index searches for LIKE, ILIKE, ~, ~* and = queries".
  • OR در PG: "a query like WHERE a = 5 OR b = 6 could not directly use the index"، اما سیستم "can form AND and OR conditions across several index scans". ادغام indexها (Index Merge) در MySQL: "retrieves rows with multiple range scans and merges their results into one".
  • جدول‌های کوچک، بخش 11.12 مستندات PG: "the 100 rows probably fit within a single disk page, and there is no plan that can beat sequentially fetching 1 disk page". MySQL: "When a query needs to access most of the rows, reading sequentially is faster than working through an index".
  • آمار (Statistics): ورودی‌های pg_statistic، "are always approximate even when freshly updated". توصیه این است: "Always run ANALYZE first". دستور ANALYZE TABLE در MySQL، "performs a key distribution analysis".
  • index جزئی (Partial index): "a partial index can be used in a query only if the system can recognize that the WHERE condition of the query mathematically implies the predicate of the index".
  • JSONB: "The default GIN operator class for jsonb supports queries with … the containment operator @>". دربارهٔ jdoc -> 'tags' ? 'qui': "the index could not be used … because though the operator ? is indexable, it is not applied directly to the indexed column".

پیوندها و زیرپرس‌وجوها (Joins and subqueries) ​

EXISTS، IN، JOIN ​

موقعیت (Situation): مشتری‌هایی را فهرست کنید که دست‌کم یک سفارش پرداخت‌شده دارند.

sql
SELECT c.id FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.status = 'paid');
SELECT id FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE status = 'paid');
-- both: 1, 2, 3   (a plain JOIN returns customer 1 four times, once per paid order, unless you add DISTINCT)
SELECT id FROM customers WHERE id NOT IN (1, NULL);   -- returns nothing

حکم (Verdict): EXISTS و IN (subquery) نیم‌پیوند (Semi-join) هستند: یک ردیف به‌ازای هر مشتری؛ هر دو موتور هم برایشان Plan مبتنی بر Join می‌سازند. MySQL: "A semijoin is a preparation-time transformation that enables multiple execution strategies such as table pullout, duplicate weedout, first match, loose scan, and materialization"؛ از صفحهٔ مستندات 8.0. NOT EXISTS را به NOT IN ترجیح دهید. PostgreSQL می‌گوید اگر "at least one right-hand row yields null, the result of the NOT IN construct will be null, not true".

روی کلید خارجی (Foreign key) index بسازید ​

موقعیت (Situation): حذف یک مشتری یا اجرای JOIN orders ON orders.customer_id = c.id باعث پیمایش orders می‌شود.

حکم (Verdict): PostgreSQL برای ستون ارجاع‌دهنده خودکار index نمی‌سازد: "the declaration of a foreign key constraint does not automatically create an index on the referencing columns"؛ اجرای DELETE روی والد هم "will require a scan of the referencing table". MySQL آن را می‌سازد: "Such an index is created on the referencing table automatically if it does not exist." در PostgreSQL روی orders (customer_id) index بسازید. Query تشخیصی موارد فاقد index را فهرست می‌کند.

N+1 در برابر یک query ​

موقعیت (Situation): صفحهٔ سفارش، اقلام هر سفارش را با یک درخواست جداگانه بارگذاری می‌کند.

sql
-- N+1: the app runs this once per order on the page
SELECT * FROM order_items WHERE order_id = $1;
-- one round trip instead
SELECT * FROM order_items WHERE order_id = ANY($1);           -- PG, $1 = bigint[]
SELECT * FROM order_items WHERE order_id IN (?, ?, ?);         -- MySQL / Laravel ->with('items')
-- top 3 lines per order (LATERAL)
SELECT o.id, i.sku FROM orders o
CROSS JOIN LATERAL (SELECT sku FROM order_items WHERE order_id = o.id ORDER BY price DESC LIMIT 3) i
WHERE o.tenant_id = 7;

حکم (Verdict): هر شکل به order_items (order_id) نیاز دارد؛ بدون آن هر جست‌وجو یک پیمایش کامل (Full scan) است. توضیح بیشتر: ORM pitfalls → N+1.

الگوریتم‌های پیوند (Join algorithms) ​

الگوریتم (Algorithm)PostgreSQLMySQL 8.4index مفید
حلقهٔ تودرتو (Nested loop)Nested Loop؛ برای هر ردیف بیرونی، سمت داخلی جست‌وجو می‌شودبا index قابل‌استفاده روی ستون Join، انتخاب پیش‌فرض استindex روی ستون Join سمت داخلی
پیوند هش (Hash join)Hash Join به‌همراه فرزند Hashبرای Join برابری بدون index قابل‌استفاده: "employs hash joins whenever possible"نیازی ندارد؛ indexهای شرط‌های تک‌جدولی همچنان کمک می‌کنند
پیوند ادغامی (Merge join)Merge Join؛ "requires its input data to be sorted on the join keys"ارائه نمی‌شود؛ Query planning → joinsB-tree روی هر دو کلید Join
حلقهٔ تودرتوی بلوکی (Block nested loop)نداردحذف شده: "Beginning with MySQL 8.0.20, support for block nested loop is removed"؛ Hash join از 8.0.18ندارد

مبانی: Query planning → joins.

صفحه‌بندی (Pagination) ​

موقعیت (Situation): فهرست سفارش‌های مستاجر 1، هر صفحه 3 سفارش، از تازه به قدیمی؛ صفحهٔ 2 پس از سفارش 4 در تاریخ ۲۰۲۶-۱۱-۲۱ ساعت 08:00 شروع می‌شود.

sql
-- OFFSET: page 2 of tenant 1, 3 per page
SELECT id, created_at FROM orders WHERE tenant_id = 1
ORDER BY created_at DESC, id DESC LIMIT 3 OFFSET 3;
-- result: (3, 2026-11-20 12:00) (2, 2026-11-10 09:00) (5, 2026-11-02 11:00)

-- keyset, PostgreSQL: row-value comparison after the last row of page 1 (2026-11-21 08:00, id 4)
SELECT id, created_at FROM orders
WHERE tenant_id = 1 AND (created_at, id) < ('2026-11-21 08:00:00', 4)
ORDER BY created_at DESC, id DESC LIMIT 3;
-- same 3 rows

-- keyset, MySQL: the expanded form
SELECT id, created_at FROM orders
WHERE tenant_id = 1
  AND (created_at < '2026-11-21 08:00:00' OR (created_at = '2026-11-21 08:00:00' AND id < 4))
ORDER BY created_at DESC, id DESC LIMIT 3;
-- same 3 rows

CREATE INDEX orders_tenant_created_id ON orders (tenant_id, created_at, id);
text
PG     Limit -> index scan on orders_tenant_created_id, read backward   Index Cond: tenant_id and ROW(created_at, id) < ROW(...)
MySQL  type: range   key: orders_tenant_created_id   Extra: Using where; Backward index scan; Using index

حکم (Verdict): صفحه‌بندی کلیدمحور (Keyset) فقط ردیف‌های همان صفحه را می‌خواند؛ OFFSET همهٔ ردیف‌های ردشده را می‌خواند و دور می‌ریزد. PostgreSQL: "The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET might be inefficient". دربارهٔ مقدارهای ردیفی (Row values): "the row elements are compared left-to-right, stopping as soon as an unequal or null pair of elements is found". در MySQL با WHERE c1=1 AND (c2,c3) > (1,1)، "the optimizer uses only c1 (key_len=4…)"؛ شکل بازشده از هر سه ستون استفاده می‌کند. بنابراین: "avoid mixing row constructors with AND/OR expressions. Use one or the other". همیشه ORDER BY را با ستون یکتا تمام کنید. در MySQL ترتیب ردیف‌هایی که مقدار sort برابر دارند "is nondeterministic with respect to the nonordered columns". بیشتر بخوانید: Pagination → keyset، مقدارهای ردیفی.

پرس‌وجوهای تشخیصی (Diagnostic queries) ​

sql
-- PostgreSQL: indexes never scanned since the last stats reset (keep unique/PK ones)
SELECT s.schemaname, s.relname AS table_name, s.indexrelname AS index_name,
       pg_size_pretty(pg_relation_size(s.indexrelid)) AS size, s.idx_scan, s.last_idx_scan
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0 AND NOT i.indisunique
ORDER BY pg_relation_size(s.indexrelid) DESC;
sql
-- PostgreSQL: foreign keys whose first column is not the first column of any index
SELECT c.conrelid::regclass AS table_name, c.conname, a.attname AS fk_column
FROM pg_constraint c
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
WHERE c.contype = 'f'
  AND NOT EXISTS (SELECT 1 FROM pg_index i
                  WHERE i.indrelid = c.conrelid AND i.indkey[0] = c.conkey[1]);
sql
-- PostgreSQL: top 10 statements by total execution time (needs pg_stat_statements)
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time::numeric, 2) AS mean_ms,
       rows, left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
sql
-- PostgreSQL: what the planner knows about one column
SELECT n_distinct, null_frac, most_common_vals, most_common_freqs, correlation
FROM pg_stats
WHERE tablename = 'orders' AND attname = 'status';
sql
-- MySQL 8.4 (sys schema / performance_schema)
SELECT * FROM sys.schema_unused_indexes WHERE object_schema = 'shop';
SELECT table_name, redundant_index_name, redundant_index_columns,
       dominant_index_name, sql_drop_index
FROM sys.schema_redundant_indexes WHERE table_schema = 'shop';
SELECT query, exec_count, no_index_used_count
FROM sys.statements_with_full_table_scans LIMIT 10;
SELECT object_name, index_name, count_star, count_read, count_write
FROM performance_schema.table_io_waits_summary_by_index_usage
WHERE object_schema = 'shop' ORDER BY count_star DESC;

نمای sys.schema_unused_indexes زمانی بیشترین فایده را دارد که بار نماینده‌ای از کار واقعی دیده باشد: "is most useful when the server has been up and processing long enough that its workload is representative". در table_io_waits_summary_by_index_usage: "A value of NULL means that table I/O used no index". جزئیات: Indexing → indexهای بلااستفاده، indexهای تکراری.

پیش از افزودن index ​

  • EXPLAIN (ANALYZE, BUFFERS) / EXPLAIN ANALYZE را روی دادهٔ واقعی اجرا کنید. دادهٔ آزمایشی خیلی کم، همهٔ Planها را به Seq Scan تبدیل می‌کند.
  • ابتدا ANALYZE را اجرا کنید: "Examining an application's index usage without having run ANALYZE is therefore a lost cause".
  • می‌توان به‌جای index جدید، یکی از indexهای موجود را گسترش داد؛ با افزودن ستون انتهایی یا INCLUDE؟
  • ترتیب ستون‌ها: ستون‌های برابری، بعد یک ستون بازه یا sort. بدون دلیل از سه ستون فراتر نروید: "Indexes with more than three columns are unlikely to be helpful unless the usage of the table is extremely stylized".
  • آیا در WHERE تابع، تبدیل نوع (Cast) یا محاسبه‌ای دور ستون قرار گرفته؟ پیش از افزودن index، query را اصلاح کنید.
  • مقدار نادر است؟ فقط مقدارهای نادر را index کنید؛ index جزئی (Partial index) در PG.
  • آیا ORDER BY … LIMIT با ترتیب و جهت index، از جمله جای NULLها، منطبق است؟
  • هزینهٔ نوشتن: هر index با هر نوشتن نگه‌داری می‌شود؛ "Index expressions are relatively expensive to maintain". ببینید تقویت نوشتن (Write amplification).
  • روی جدول در حال استفاده، آنلاین بسازید: در PG با CREATE INDEX CONCURRENTLY؛ گزینه‌های MySQL در Indexing → جدول زنده.
  • پس از یک هفته ترافیک، نماهای indexهای بلااستفاده را بررسی و مواردی را که هیچ query استفاده نمی‌کند حذف کنید.

خطاهای رایج (Common errors) ​

کد (Code)پیام (Message)علت (Cause)راه‌حل (Fix)
PG 42803grouping_errorستون گروه‌بندی‌نشده در SELECT/HAVINGبر اساس کلید اصلی (PK) گروه‌بندی کنید، ستون را تجمیع (Aggregate) کنید یا به GROUP BY اضافه کنید
PG 42702ambiguous_columnنام ستون یکسان در دو جدول Joinشدهنام را با جدول مشخص کنید: o.id
PG 42P01undefined_tableنام، Schema یا search_path نادرستنام Schema را بیاورید؛ \dt را بررسی کنید
PG 42883undefined_functionتابع یا عملگری برای این نوع آرگومان‌ها وجود ندارد؛ اغلب ناسازگاری نوع استمقدار ثابت یا پارامتر را تبدیل نوع (Cast) کنید، نه ستون را
PG 0A000feature_not_supportedاین ساختار در این زمینه پشتیبانی نمی‌شوددستور را بازنویسی کنید
MySQL 1055Expression #N of SELECT list is not in GROUP BY clause … only_full_group_byستون بدون Aggregate، وابستگی تابعی (Functional dependency) نداردگروه‌بندی بر اساس PK یا ANY_VALUE()
MySQL 1052Column '…' in … is ambiguousستون Join بدون نام جدول آمده استنام مستعار (Alias) جدول را اضافه کنید
MySQL 1064… near '…' at line Nخطای نحو؛ اغلب کپی نحو مخصوص PostgreSQL در MySQLنحو MySQL: SUM(CASE …) و ORDER BY x IS NULL, x
MySQL 1176Key '…' doesn't exist in table '…'FORCE INDEX / USE INDEX به index ناموجود اشاره می‌کندنام را درست کنید یا Hint را بردارید
MySQL 3065Expression #N of ORDER BY clause is not in SELECT list …SELECT DISTINCT با ORDER BY روی ستون انتخاب‌نشدهستون را به فهرست SELECT اضافه کنید یا DISTINCT را بردارید

از Go و Laravel ​

محافظ برنامهٔ اجرا (Plan guard) در تست Go با pgx؛ آن را روی دیتابیسی با آمار واقع‌بینانه اجرا کنید. الگو از Indexing → plan guard است.

go
func TestRecentOrdersUsesIndex(t *testing.T) {
	ctx := context.Background()
	pool := testPool(t) // *pgxpool.Pool against a seeded, ANALYZEd database
	var plan string
	err := pool.QueryRow(ctx,
		`EXPLAIN (FORMAT JSON) SELECT id, created_at FROM orders
		  WHERE tenant_id = $1 ORDER BY created_at DESC LIMIT 20`, int64(7)).Scan(&plan)
	if err != nil {
		t.Fatal(err)
	}
	if strings.Contains(plan, `"Node Type": "Seq Scan"`) {
		t.Fatalf("hot query lost its index path:\n%s", plan)
	}
}
php
// Laravel: print SQL, show the plan, group with HAVING, log every query
$q = DB::table('orders')
    ->select('customer_id', DB::raw('count(*) as paid_orders'))
    ->where('status', 'paid')
    ->where('created_at', '>=', now()->subDays(30))
    ->groupBy('customer_id')
    ->having('paid_orders', '>=', 3);          // or ->havingRaw('count(*) >= ?', [3])

$q->toSql();            // "Get the SQL representation of the query." (? placeholders)
$q->dumpRawSql();       // the SQL "with all parameter bindings properly substituted"
dump($q->explain());    // explain(): "Explains the query." (returns a Collection of plan rows)

DB::enableQueryLog();   // "Enable the query log on the connection."
DB::table('order_items')->whereIn('order_id', $orderIds)->get();   // one IN (...) query, not N+1
dump(DB::getQueryLog()); // "Get the connection query log."

having('paid_orders', …) از نام مستعار (Alias) در select استفاده می‌کند و MySQL آن را می‌پذیرد. PostgreSQL نام ستون خروجی را در HAVING نمی‌پذیرد: "not in the WHERE or HAVING clauses; there you must write out the expression instead"؛ پس آنجا havingRaw('count(*) >= ?', [3]) بنویسید.

منابع (References) ​

مستندات PostgreSQL 18، ذخیره‌شده در ۲۰۲۶-۱۱-۲۹: 11.3 Multicolumn Indexes · 11.4 Indexes and ORDER BY · 11.5 Combining Multiple Indexes · 11.6 Unique Indexes · 11.7 Indexes on Expressions · 11.8 Partial Indexes · 11.9 Index-Only Scans · 11.10 Operator Classes · 11.2 Index Types · 11.12 Examining Index Usage · 14.1 Using EXPLAIN · EXPLAIN · 14.2 Statistics Used by the Planner · 7.2 Table Expressions · 7.6 LIMIT and OFFSET · SELECT · 4.2 Value Expressions · 9.21 Aggregate Functions · 2.7 Aggregate Functions (tutorial) · Release 18 · 19.7 Query Planning · 9.25 Row and Array Comparisons · 9.24 Subquery Expressions · Appendix A Error Codes · pg_stat_statements · 27.2 Cumulative Statistics · pg_stats · pg_trgm · 8.14 JSON Types · 5.5 Constraints · 10.2 Operators (type conversion) · CREATE INDEX · 9.9 Date/Time Functions · 36.7 Function Volatility · 9.7 Pattern Matching · 7.5 Sorting Rows · 7.3 Select Lists · 11.11 Indexes and Collations · 9.4 String Functions

راهنمای مرجع MySQL 8.4، ذخیره‌شده در ۲۰۲۶-۱۱-۲۹: 10.3 Optimization and Indexes · 10.3.1 How MySQL Uses Indexes · 10.3.6 Multiple-Column Indexes · 10.2.1.3 Index Merge · 10.2.1.2 Range Optimization · 10.2.1.16 ORDER BY Optimization · 10.2.1.17 GROUP BY Optimization · 10.2.1.18 DISTINCT Optimization · 10.2.1.19 LIMIT Optimization · 10.2.1.22 Row Constructor Expression Optimization · 10.2.1.15 IS NULL Optimization · 10.2.1.6 Index Condition Pushdown · 10.2.1.1 WHERE Clause Optimization · 10.2.1.4 Hash Join · 10.2.1.7 Nested-Loop Joins · 10.3.13 Descending Indexes · 10.8.2 EXPLAIN Output Format · 15.8.2 EXPLAIN Statement · 15.2.13 SELECT · 14.19.3 MySQL Handling of GROUP BY · 14.19.4 Functional Dependence · 14.3 Type Conversion · 17.6.2.1 Clustered and Secondary Indexes · 15.1.15 CREATE INDEX · 14.9 Full-Text Search · 15.7.3.1 ANALYZE TABLE · 5.3.4.6 Working with NULL Values · 14.20.2 Window Functions · sys.schema_unused_indexes · sys.schema_redundant_indexes · sys.statements_with_full_table_scans · 29.12.20.8 Table I/O Wait Summary Tables · Server Error Message Reference · 15.1.20.5 FOREIGN KEY Constraints · 14.9.1 Natural Language Full-Text Searches · 12.8.4 Collation Coercibility · 15.1.20.9 Secondary Indexes and Generated Columns · 14.8 String Functions

Go و Laravel، ذخیره‌شده در ۲۰۲۶-۱۱-۲۹: pgx v5 pgxpool/pool.go (QueryRow, Query) · pgx v5 rows.go (Row.Scan) · Laravel 12 Query Builder · Laravel 12 Database · Laravel 12 API: Query\Builder · Laravel 12 API: Connection · Laravel 12 API: ExplainsQueries

صفحه‌های راهنمای MySQL 8.0 برای تاریخچهٔ نسخه‌هایی که در صفحه‌های 8.4 نیامده‌اند: Hash Join (8.0) · EXPLAIN (8.0) · Nested-Loop Joins (8.0) · Semijoin (8.0; the 8.4 URL redirects here)

ساخته‌شده توسط Morteza Negahi