Blogs · SQL · Database System

SQL: Index and Optimization

A short guide on optimizing query performances

2020.08.31 · 1 min read · by Zhenlin Wang · updated 2022-08-19

Overview

To be honest, I’m not a pro-SQL programmer. I’m still on my journey to learn more about database and query optimization. In this blog I will just give whatever I’ve learnt about indexing and optimization and its mostly based on MySQL. Hope it helps!

Guidelines

  1. Single Sheet query is much better than Multiple Sheet
  2. If multiple sheet is needed, Use JOIN well:
    • Small Sheet drive Large Sheet (for e.g. left join in this case)
    • Establish proper indexing
    • Don’t JOIN too many sheets as well
  3. Try best NOT to use subquery or Cartesian Product
  4. Window Funtions can be very helpful

Indexes

1. Index operations

-- show indices
SHOW INDEX FROM your_db_name.customer;

-- Add index
ALTER TABLE payment
ADD INDEX idx_pay (payment_id);  -- [index] can be appended by [unique] to ensure each index is unique

CREATE FULLTEXT INDEX idx_staff ON customer (email); -- [fulltext] only applicable to string data

-- Drop Index
DROP INDEX idx_pay ON payment

For the full list of operations, you may refer to the official documentation of MySQL1

2. Clustered Indexes

TODO