MySQL Tutorial menu

MySQL Indexes, Views and Transactions

Indexes make queries fast, views save useful queries, and transactions keep related changes together. Real applications use all three.

Indexes

Without an index, MySQL must read every row to find a match, like looking for a name in a book that has no index page. With an index, it jumps straight to the right rows.

Example

sql
CREATE INDEX idx_products_category
ON products (category);
Output
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

Now queries such as WHERE category = 'Grocery' can use the index.

Which Columns Need an Index?

  • Columns you often search in WHERE, such as email or category
  • Columns used to join tables (MySQL indexes foreign keys automatically)
  • Columns you often sort by in ORDER BY

Primary keys and UNIQUE columns already have an index.

Do not index every column. Each index takes disk space and makes INSERT, UPDATE and DELETE a little slower, because the index must be updated too.

An Index on Two Columns

Example

sql
CREATE INDEX idx_orders_customer_date
ON orders (customer, order_date);

This helps queries that filter by customer, or by customer and order_date together.

Check with EXPLAIN

Put EXPLAIN before a SELECT to see how MySQL plans to run it:

Example

sql
EXPLAIN SELECT name FROM products WHERE category = 'Grocery';

In the result, look at the key column. If it shows idx_products_category, the index is used. If type is ALL, MySQL is reading the whole table.

To see or remove indexes:

Example

sql
SHOW INDEX FROM products;
DROP INDEX idx_products_category ON products;

Views

A view is a saved SELECT query that you can use like a table. This one gives a simple order report:

Example

sql
CREATE VIEW order_report AS
SELECT o.id,
       o.customer,
       p.name AS product,
       o.quantity,
       o.quantity * p.price AS total
FROM orders AS o
JOIN products AS p ON p.id = o.product_id;

Now anyone can read it without writing the join:

Example

sql
SELECT * FROM order_report WHERE customer = 'Ayesha';
Output
+----+----------+------------------+----------+---------+
| id | customer | product          | quantity | total   |
+----+----------+------------------+----------+---------+
|  1 | Ayesha   | Basmati Rice 5kg |        2 | 4900.00 |
|  4 | Ayesha   | Cooking Oil 1L   |        5 | 3100.00 |
+----+----------+------------------+----------+---------+
2 rows in set (0.00 sec)

A view stores no data itself. Each time you read it, MySQL runs the query on the current tables, so it is always up to date.

CommandUse
CREATE VIEW name AS SELECT ...;Make a view
CREATE OR REPLACE VIEW name AS ...;Change a view
DROP VIEW name;Remove a view

Transactions

A transaction groups several statements so that they all succeed together or all fail together.

Think of a sale: the shop must add an order and reduce the stock. If the power goes off after the first step, the data would be wrong. A transaction prevents that:

Example

sql
START TRANSACTION;

INSERT INTO orders (product_id, quantity, customer, order_date)
VALUES (3, 2, 'Fatima', '2026-10-15');

UPDATE products
SET stock = stock - 2
WHERE id = 3;

COMMIT;

COMMIT saves both changes permanently.

ROLLBACK

If something goes wrong before COMMIT, ROLLBACK cancels every change since START TRANSACTION:

Example

sql
START TRANSACTION;

DELETE FROM orders;   -- oops, no WHERE!

ROLLBACK;

SELECT COUNT(*) FROM orders;
Output
+----------+
| COUNT(*) |
+----------+
|        5 |
+----------+
1 row in set (0.00 sec)

All five orders are still there.

Transactions only work with the InnoDB engine, which is the default. Statements such as CREATE TABLE and DROP TABLE commit automatically and cannot be rolled back.

ACID

Transactions give four promises, known as ACID:

LetterPromise
AtomicityAll steps happen, or none do
ConsistencyRules such as foreign keys are always kept
IsolationOther users do not see half-finished changes
DurabilityOnce committed, the data survives a crash

Exercise

Exercise

You started a transaction and deleted the wrong rows. You have not committed yet. Which command brings the rows back?

Learn MySQL with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp