From abd05c2f60d068a997c02662f08c195ceff33eb8 Mon Sep 17 00:00:00 2001 From: Hau Nguyen Date: Sun, 17 Nov 2024 11:32:38 +0700 Subject: [PATCH] sql: compositex index --- docs/2022-07-31-sql.html | 23 +++++++++++++++++++++++ posts/2022-07-31-sql.md | 23 +++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/docs/2022-07-31-sql.html b/docs/2022-07-31-sql.html index 37d799a..7e00638 100644 --- a/docs/2022-07-31-sql.html +++ b/docs/2022-07-31-sql.html @@ -196,6 +196,29 @@ PRIMARY KEY (id), INDEX idx_user_id (user_id) ); + +

+ If use composite index, order is important, either both + DESC or both ASC, do not mix: +

+
+
CREATE INDEX idx_user_id_created_at
+    ON user_upload (user_id, created_at);
+
+-- Do not
+SELECT *
+FROM user_upload
+ORDER BY user_id, created_at DESC;
+
+-- Do
+SELECT *
+FROM user_upload
+ORDER BY user_id DESC, created_at DESC;
+
+-- Or do
+SELECT *
+FROM user_upload
+ORDER BY user_id, created_at;

Use EXPLAIN to check if index is used or not: