Skip to content

Commit b781671

Browse files
Using indexes for sorting
1 parent 558791f commit b781671

File tree

1 file changed

+50
-0
lines changed
  • 13_indexing_for_high_performance/08_using_indexes_for_sorting

1 file changed

+50
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
## Using Indexes For Sorting:
2+
lets check the indexes and then sort by ASC
3+
```sql
4+
SHOW INDEXES IN customers;
5+
EXPLAIN
6+
SELECT customer_id
7+
FROM customers
8+
ORDER BY state;
9+
SHOW STATUS LIKE 'last_query_cost';
10+
```
11+
Lets check the cost of previous query!
12+
13+
Now lets check first_name which is not in indexes
14+
```sql
15+
EXPLAIN
16+
SELECT customer_id
17+
FROM customers
18+
ORDER BY first_name;
19+
SHOW STATUS LIKE 'last_query_cost';
20+
```
21+
Why cost is so high? because first_name is not indexes, when we put a column in indexes, mysql will automatically sort it in ASC and store it parmanent.
22+
Now first_name is not in indexes so why mysql find? mysql uses filesort algorithm which is very expensive.
23+
**Here's how it works:**
24+
* Query Execution: When a query is executed, MySQL first retrieves the rows that match the WHERE clause.
25+
* Sorting: If the query has an ORDER BY clause and there's no suitable index to perform the sorting efficiently, MySQL resorts to the filesort algorithm. It sorts the result set based on the specified columns.
26+
* Temporary File: As MySQL sorts the result set, it may need to write intermediate results to a temporary file on disk if the result set is too large to fit into memory. This temporary file is used to store portions of the result set that can't be held in memory at once.
27+
* Merging: Once all the rows are sorted and stored in the temporary file, MySQL performs a merge operation to combine the sorted portions into a single sorted result set.
28+
* Final Result: After merging, MySQL returns the sorted result set to the client.
29+
```sql
30+
EXPLAIN
31+
SELECT customer_id
32+
FROM customers
33+
ORDER BY state , points DESC;
34+
SHOW STATUS LIKE 'last_query_cost';
35+
```
36+
Why cost decreases again? because both were in indexes.
37+
```sql
38+
EXPLAIN
39+
SELECT customer_id
40+
FROM customers
41+
ORDER BY state ,first_name, points;
42+
SHOW STATUS LIKE 'last_query_cost';
43+
44+
-- --------------------------------------------------------
45+
EXPLAIN
46+
SELECT customer_id
47+
FROM customers
48+
ORDER BY state DESC , points DESC;
49+
SHOW STATUS LIKE 'last_query_cost';
50+
```

0 commit comments

Comments
 (0)