SELECT * FROM employees WHERE last_name = 'Smith';
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
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';
Optimized Query
SELECT order_id, customer_id FROM orders WHERE order_date > '2023-01-01';
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';
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
like listing of users and orders and other stuff that does not change frequently
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 );
The above is the detailed content of Query optimization in MySQL is crucial for improving database performance, especially when dealing with large datasets. For more information, please follow other related articles on the PHP Chinese website!