DEV Community

Cover image for Query optimization in MySQL is crucial for improving database performance, especially when dealing with large datasets
Ahmedraza Fyntune
Ahmedraza Fyntune

Posted on

Query optimization in MySQL is crucial for improving database performance, especially when dealing with large datasets

1. Use Proper Indexing

  • Indexes speed up data retrieval by reducing the amount of data scanned
SELECT * FROM employees WHERE last_name = 'Smith';
Enter fullscreen mode Exit fullscreen mode
  • if you are query a single column of a table multiple times then make index for that column

  • if you are or your app require data from multiple columns based on conditions then make composite index

2. Avoid SELECT *

  • Select only those columns which are require if u select all the columns that are not required the this will just consume more ram of server and lead to slow the server in high load or frequency time

E.g Your table contains columns like created_at and updated_At and timesptamps then avoid selecting * as they don't needed in normal senarios

Inefficient Query

SELECT * FROM orders WHERE order_date > '2023-01-01';

Enter fullscreen mode Exit fullscreen mode

Optimized Query

SELECT order_id, customer_id FROM orders WHERE order_date > '2023-01-01';

Enter fullscreen mode Exit fullscreen mode
  1. Optimize Joins
  • Ensure indexes exist on columns used in JOIN conditions.

if you are joining tables with primary key then there is no need to create as Primary key is already an index

SELECT orders.order_id, customers.name FROM orders
JOIN customers ON orders.customer_id = customers.id
WHERE customers.country = 'USA';
Enter fullscreen mode Exit fullscreen mode

in the above query the orders.customer_id is need to be indexed and its a relation from another table

customers.id is an primary key of customers table so no need to create index

customers.country need to be indexed as it's a condition

5. Avoid Subqueries; Use Joins Instead

6. Use Query Caching

  • If your query results don’t change frequently, use MySQL’s query cache.

like listing of users and orders and other stuff that does not change frequently

7. Partition Large Tables

CREATE TABLE orders (
    order_id INT NOT NULL,
    order_date DATE NOT NULL,
    ...
    PRIMARY KEY (order_id, order_date)
)
PARTITION BY RANGE (YEAR(order_date)) (
    PARTITION p0 VALUES LESS THAN (2000),
    PARTITION p1 VALUES LESS THAN (2010),
    PARTITION p2 VALUES LESS THAN (2020),
    PARTITION p3 VALUES LESS THAN MAXVALUE
);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)