Mastering SQL Queries in MySQL and MariaDB: A Practical Guide from Scratch for Large Tables

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

Imagine a query that should take less than a second to respond ending up taking 30 seconds instead. It is not just annoying: it bottlenecks the server, runs up your hosting (or cloud) bill, and worst of all… it makes users close the tab and leave.

This guide is aimed at developers who are starting out with SQL (or who already use it but feel they need to polish their skills) and work with MySQL or MariaDB. The goal is for you to walk away with real, immediately applicable tools so that querying large tables stops being a headache, without needing to become a database administrator or mess with advanced server configurations.

Why Slow Queries Hurt (and Hurt Seriously)

An inefficient query is not merely “slow.” It has tangible consequences:

  • A query that takes 10 seconds and runs multiple times a day on a 1-million-row table can easily cost you an extra $50 or more each month in infrastructure.
  • In a logistics management system for a global shipping company that, over several years, has accumulated tables with millions of records on container shipments, maritime routes, and real-time tracking, every additional second translates into reduced agility for the operations team and a worse experience for customers expecting instant updates.

In environments where MySQL or MariaDB are poorly utilized, these issues compound quickly. Query optimization is not a “nice to have”: over time, it becomes an essential core skill if you want your application to scale without collapsing.

Core Concepts to Understand Before Optimizing

These are the foundational concepts. If you apply them consistently, most of your performance bottlenecks will improve without touching anything else.

1. SELECT: Request Only What You Will Use

Every column you retrieve consumes memory, CPU, and network bandwidth. It sounds obvious, but it is one of the most common mistakes.

-- Mala idea: trae TODO
SELECT * FROM envios WHERE fecha > '2025-01-01';

-- Mucho mejor: solo lo que necesitas
SELECT id_contenedor, destino, estado
FROM envios
WHERE fecha > '2025-01-01';

A simple rule of thumb: if you are not going to display it or use it in code, do not select it. Period.

2. WHERE: Filter as Early as Possible

The sooner you reduce the number of rows MySQL/MariaDB has to process, the better.

-- Muy buena práctica cuando hay índice en fecha
WHERE fecha BETWEEN '2025-01-01' AND '2025-12-31';

A classic mistake that kills performance: applying functions to the column you are filtering on.

-- Esto casi siempre impide usar índice → full table scan
WHERE YEAR(fecha) = 2025;

-- Deja que el motor use el índice
WHERE fecha >= '2025-01-01' AND fecha < '2026-01-01';

3. JOIN: Do It Wisely

A poorly written JOIN can turn into an accidental Cartesian product and bring down the server.

-- Peligroso: sin condición → explosión de filas
SELECT e.estado, n.nombre
FROM envios e
JOIN navieras n;

-- Correcto y eficiente
SELECT e.estado, n.nombre
FROM envios e
INNER JOIN navieras n ON e.naviera_id = n.id
WHERE e.fecha >= '2025-01-01';

A life-saving tip: apply your most restrictive filters before the JOIN whenever possible. MySQL/MariaDB will thank you.

Easy Techniques That Deliver Immediate Results

Here are actionable techniques you can implement today to see improvements within minutes.

1. Use LIMIT Almost Everywhere

Especially in listings, admin dashboards, autocompletes, pagination APIs…

SELECT id, destino, fecha
FROM envios
ORDER BY fecha DESC
LIMIT 50 OFFSET 0;

Without a LIMIT, the engine might attempt to sort and prepare millions of rows just for your frontend to display 20.

2. Say Goodbye to SELECT *

It seems harmless… until the table has 40 columns and 2 million rows.

-- Tráfico innecesario (puede ser 80–90% más datos)
SELECT * FROM contenedores;

-- Solo lo esencial
SELECT id, tipo, capacidad, estado_actual
FROM contenedores
WHERE activo = 1;

3. Indexes: Your Best Friends (in Moderation)

Create indexes on the columns you use most frequently in:

  • WHERE
  • JOIN … ON
  • ORDER BY
  • GROUP BY
CREATE INDEX idx_envios_fecha ON envios(fecha);
CREATE INDEX idx_envios_naviera_fecha ON envios(naviera_id, fecha);

Golden rule: start with a few well-thought-out indexes. Too many indexes slow down INSERT, UPDATE, and DELETE operations. First, use EXPLAIN to analyze which ones are actually being utilized.

4. Smart GROUP BY

Make sure to filter before grouping and ensure that the filtered columns are indexed.

SELECT naviera_id, SUM(costo) AS total_costo, COUNT(*) AS cantidad_envios
FROM envios
WHERE fecha >= '2025-01-01' AND fecha < '2026-01-01'
GROUP BY naviera_id
HAVING total_costo > 1000000;

Real Case: Before vs. After (2.5 Million-Row Table)

Before (a typical painful query):

SELECT *
FROM envios
WHERE YEAR(fecha) = 2025;
-- > 18.7 segundos

After (small adjustments):

SELECT id, destino, naviera_id, fecha
FROM envios
WHERE fecha >= '2025-01-01'
  AND fecha < '2026-01-01'
LIMIT 100;
-- > 0.23 segundos

Improvement: ≈ 98% reduction in execution time. Same useful result, happy server.

Free Tools to Help You Out (Without Spending a Dime)

ToolBest ForWhy Use It
phpMyAdminShared hosting, beginnersEasy to install, visual, widely used in cPanel
DBeaverAny environment (MySQL, MariaDB, PostgreSQL…)Cross-platform, excellent autocompletion, free
MySQL WorkbenchPure MySQL / MariaDBOfficial Oracle tool, great for modeling and EXPLAIN
AdminerLightweight serversSingle PHP file, ultra-lightweight

Pick the one that fits your workflow best. DBeaver and Adminer are my daily go-to tools for development.

Your Next Step (Pick Just One)

Do not try to implement everything at once. Choose a single technique covered here that you can apply today to the slowest query in your project.

Often, results appear in a matter of minutes: lower server load, faster response times, happier users, and fewer headaches.

Thanks for reading this far! Keep on coding.