sql: compositex index

main
sudo pacman -Syu 2024-11-17 11:32:38 +07:00
parent e704dca7e9
commit abd05c2f60
2 changed files with 46 additions and 0 deletions

View File

@ -196,6 +196,29 @@
<span class="pl-k">PRIMARY KEY</span> (id),
INDEX idx_user_id (user_id)
);</pre>
</div>
<p>
If use composite index, order is important, either both
<code>DESC</code> or both <code>ASC</code>, do not mix:
</p>
<div class="highlight highlight-source-sql">
<pre><span class="pl-k">CREATE</span> <span class="pl-k">INDEX</span> <span class="pl-en">idx_user_id_created_at</span>
<span class="pl-k">ON</span> user_upload (user_id, created_at);
<span class="pl-c"><span class="pl-c">--</span> Do not</span>
<span class="pl-k">SELECT</span> <span class="pl-k">*</span>
<span class="pl-k">FROM</span> user_upload
<span class="pl-k">ORDER BY</span> user_id, created_at <span class="pl-k">DESC</span>;
<span class="pl-c"><span class="pl-c">--</span> Do</span>
<span class="pl-k">SELECT</span> <span class="pl-k">*</span>
<span class="pl-k">FROM</span> user_upload
<span class="pl-k">ORDER BY</span> user_id <span class="pl-k">DESC</span>, created_at <span class="pl-k">DESC</span>;
<span class="pl-c"><span class="pl-c">--</span> Or do</span>
<span class="pl-k">SELECT</span> <span class="pl-k">*</span>
<span class="pl-k">FROM</span> user_upload
<span class="pl-k">ORDER BY</span> user_id, created_at;</pre>
</div>
<p>Use <code>EXPLAIN</code> to check if index is used or not:</p>
<ul>

View File

@ -72,6 +72,29 @@ CREATE TABLE user_upload
);
```
If use composite index, order is important, either both `DESC` or both `ASC`, do
not mix:
```sql
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:
- [For MySQL 5.7](https://dev.mysql.com/doc/refman/5.7/en/explain-output.html)