Lesson 16

Indexes and performance tuning

As data volumes grow, SQL database performance becomes critical. Indexes allow optimizing common queries by creating data structures avoiding full table scans. Understanding indexing and performance tuning concepts unlocks speed.

SQL Indexes

Indexes work like an index at the back of a book - it adds a data structure for quicker lookups on specified columns.

For example a customers table index on last_name would rearrange records sorted by last name. Now searches like:

FROM customers
WHERE last_name = 'Smith';

Can lookup the Smith entries directly instead of scanning every row.

Indexes trade write speed for read efficiency. While INSERTS/UPDATES slow down to record new data in indexes, SELECTs accelerate significantly.

SQL natively supports core index types like:

B-Tree - Balanced tree for ordering data

Bitmap - Vectorized bit arrays encoding distinct values

Hash - Hash tables mapping values to table rows

Databases automatically use indexes to speed up queries looking up columns that have useful indexes defined.

Adding an Index in MySQL

To create an index on a column in MySQL, you can use the CREATE INDEX statement.

The basic syntax is:

CREATE INDEX index_name
ON table_name (column_name);

For example, to create an index on the last_name column in the customers table:

CREATE INDEX idx_customers_lastname
ON customers (last_name);

Some key points about adding MySQL indexes:

  • Give indexes descriptive names like idx_table_column
  • Adding an index does not require locking the table or downtime
  • Columns used frequently in WHERE clauses are good index candidates
  • Limit indexes on low-cardinality columns to keep tables lean
  • Use multiple columns together in indexes for efficient queries

For example a multi-column index:

CREATE INDEX idx_orders_cust_date
ON orders (customer_id, order_date);

This optimizes queries filtering on customer ID and date.

Be judicious about adding indexes to balance performance and overheads. The optimal indexes depend on the typical query workload. Analyze slow query logs and tweak indexes iteratively using EXPLAIN plans.

Foreign key

A foreign key in SQL is a column that establishes a link between data in two tables. It enforces referential integrity by ensuring table relationships are valid.

Here is an example of defining a foreign key constraint in MySQL:

  customer_id INT,
  order_date DATE,
  order_total DECIMAL(10,2),
  FOREIGN KEY (customer_id) REFERENCES customers(id)

This orders table has a customer_id column that references the primary key in the customers table.

Some key points about foreign keys in MySQL:

  • The foreign key and referenced column must have matching data types
  • Adding a foreign key requires the REFERENCES privilege on the referenced table
  • ON DELETE and ON UPDATE clauses allow configuring cascade actions
  • Foreign keys prevent invalid data entering linked tables
  • Joins can retrieve data across foreign key relationships

Foreign keys help keep distributed data synchronized. For example if a customer record is deleted from the customers table, the database engine automatically deletes associated orders belonging to that customer.

Performance Tuning Queries

Underused indexes waste space while missing indexes cause slow queries. Some principles for right-sizing indexes:

1. Identify Slow Queries

Check query execution plans to find poorly performing ones for tuning.

2. Analyze Index Usage

See if indexes are being used fully or causing extra work.

3. Profile Data Retrieval

Measure index contribution to query runtime reduction.

4. Add Judicious Indexes

Carefully index commonly filtered columns.

Just like book indexes, database indexes require planning to accelerate common lookups without wasting space or maintenance costs. Measure twice, cut once.

Please note that our test editor doesn't support Insert, Update and Delete queries.👇

No Data

©2024 SQLZap - Learn SQL Interactively