Beyond Queries: Exploring the Lesser-Known MySQL Magic — MySQL Cookbook (Part 2)

Harsh SinghHarsh Singh
6 min read

Continuing our journey through the pages of MySQL wisdom, one mind-blowing tip at a time.

Introduction: The Cookbook that Keeps on Giving

If you thought Part 1 of our journey through MySQL Cookbook was filled with golden nuggets, buckle up. This part dives even deeper — into corners of MySQL you probably didn't even know existed.

What I love about this book is that it’s not just a guide. It feels like a mentor sitting beside you, whispering, “Hey, try this. You’ll thank me later.”

Let’s dive into some more things that made me stop, stare at my screen, and say: “Wait, you can do that in MySQL?”

1. The World of FULLTEXT — Real Search Engines, No Extra Tools

Most devs I know jump straight to Elasticsearch when building a search feature. What most of them don’t realize? MySQL has native FULLTEXT indexing, and it's wildly powerful.

Let me show you:

CREATE TABLE articles (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255),
    body TEXT,
    FULLTEXT(title, body)
);

Now you can search naturally:

SELECT * FROM articles
WHERE MATCH(title, body) AGAINST('MySQL indexing' IN NATURAL LANGUAGE MODE);

It supports:

  • Boolean mode searches (+term1 -term2)
  • Ranking results based on relevance
  • Even stopwords and minimum word lengths

You can build a blog search or eCommerce engine without adding another service.


2. Metadata Magic — Querying Your Queries

Did you know you can query the structure of your database like it’s data?

This blew my mind:

SELECT table_name, column_name, data_type
FROM information_schema.columns
WHERE table_schema = 'cookbook';

It’s like asking your database:
“Hey, what do you look like right now?”

You can use this to:

  • Auto-generate reports
  • Build admin dashboards
  • Validate column naming conventions

And it’s all built-in. No third-party plugin required.


3. Scheduled Events — MySQL’s Internal Cron Job

Raise your hand if you’ve ever written a cron job just to delete old data. 🙋‍♂️

What if I told you MySQL has its own scheduler?

CREATE EVENT cleanup_old_data
ON SCHEDULE EVERY 1 DAY
DO
  DELETE FROM logs WHERE log_date < NOW() - INTERVAL 30 DAY;

Yup, that’s native MySQL automation. No external script. No cron tab edits. And you can monitor them like so:

SHOW EVENTS;

You can also:

  • Disable/enable events dynamically
  • Write recurring weekly/monthly tasks
  • Schedule heavy queries during off-peak hours

4. The mysql_config_editor — A Safe Haven for Passwords

This is something most MySQL users don’t do — but should. Instead of typing your password into every CLI command (or worse, putting it in .my.cnf as plain text), you can securely store it using:

mysql_config_editor set --login-path=local --user=root --password

And then connect like this:

mysql --login-path=local

What’s magical? The password is encrypted. Not even you can view it in plain text. This is the safest way to store credentials locally without exposing them.


5. Server Logging — Know Thy Queries

Every once in a while, your queries slow down, and you're not sure why. That’s where MySQL server logging becomes your best friend.

Here's the gem:

slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2

Once enabled, MySQL logs every query that takes more than 2 seconds to run.

What’s cool?

  • You can analyze this log with mysqldumpslow
  • You can catch bad JOINs and missing indexes
  • You can clean up bloated query logic

The book doesn’t just tell you how — it walks you through real examples.


6. The Joy of Temporary Tables

Here’s one that might sound boring — but once you get it, it's a game-changer.

Temporary tables are like whiteboards: scratch space that disappears after use.

CREATE TEMPORARY TABLE temp_sales AS
SELECT * FROM sales WHERE year = 2024;

-- Use it freely
SELECT * FROM temp_sales;

-- It's gone when your session ends.

They’re perfect for:

  • Multi-step transformations
  • ETL staging operations
  • Protecting real data during testing

And since they auto-destroy, you never have to clean up after them. Chef’s kiss. 👨‍🍳


7. Data Validation Like a Pro

Before the book, I used to validate everything in the application layer. Now? I’m obsessed with CHECK constraints.

CREATE TABLE employees (
    id INT PRIMARY KEY,
    name VARCHAR(100),
    salary DECIMAL(10,2),
    CHECK (salary > 0)
);

Add some constraints, and your database becomes a guardian of sanity. You’re not just storing data — you’re shaping the rules of your domain.


8. Using ENUMs for Controlled Values

Sometimes, a simple enum saves you from writing a join. Case in point:

CREATE TABLE tickets (
    id INT AUTO_INCREMENT PRIMARY KEY,
    priority ENUM('low', 'medium', 'high') NOT NULL
);

Querying becomes easier:

SELECT * FROM tickets WHERE priority = 'high';

The book even discusses how MySQL stores ENUMs internally as integers, making them efficient and readable.


9. Handling Duplicates — Clean, Prevent, and Survive

Duplicate rows? We’ve all been there.

The book gives several strategies — this one is my favorite:

DELETE t1 FROM my_table t1
INNER JOIN my_table t2
WHERE
  t1.id > t2.id AND
  t1.email = t2.email;

It deletes the older duplicate but keeps one row intact.

Prevention tip from the book:

CREATE UNIQUE INDEX idx_unique_email ON users(email);

10. Fun with Sequences and AUTO_INCREMENT

Want to reset the counter?

ALTER TABLE orders AUTO_INCREMENT = 1000;

Want custom sequence simulation?

CREATE TABLE seq (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);

INSERT INTO seq VALUES (NULL);
SELECT LAST_INSERT_ID();

I once used this trick to assign sequential invoice numbers manually.


11. Triggers — Magic That Executes Itself

Imagine auto-logging every update:

CREATE TRIGGER before_update
BEFORE UPDATE ON users
FOR EACH ROW
INSERT INTO audit_log(user_id, old_email, new_email, changed_at)
VALUES (OLD.id, OLD.email, NEW.email, NOW());

Triggers are a powerful — and dangerous — tool. Use them wisely.


12. Subqueries That Solve Problems in One Line

SELECT name FROM customers
WHERE id IN (
  SELECT customer_id FROM orders WHERE total > 1000
);

No join. No temp table. Pure subquery magic.

You can even use EXISTS, NOT EXISTS, and correlated subqueries for advanced filtering.


13. Randomization — Perfect for Testing

SELECT * FROM products
ORDER BY RAND()
LIMIT 5;

This is how I often test layouts and email variations.


Closing Thoughts

The further you read MySQL Cookbook, the more you realize it’s more than just a technical manual. It’s a life hack compendium for anyone working with data.

From FULLTEXT to replication, from scheduled events to logging — this book isn’t teaching you SQL. It’s teaching you how to think in SQL.

Until next time — stay curious, keep experimenting, and may your queries be fast and your joins be indexed. 🚀

0
Subscribe to my newsletter

Read articles from Harsh Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Harsh Singh
Harsh Singh