Explain Codes LogoExplain Codes Logo

How to retrieve JSON data from MySQL?

sql
json-handling
mysql-performance
database-normalization
Anton ShumikhinbyAnton Shumikhin·Sep 28, 2024
TLDR

To quickly fetch JSON data from a MySQL table, employ the JSON_EXTRACT() function as follows:

SELECT JSON_EXTRACT(user_profile, '$.interests') AS interests FROM users;

Where '$.interests' specifies the path to the desired JSON element within the user_profile field. Simply replace this path with yours to access different data portions.

Checklist before you start

Normalize your database

Before stuffing all your stuff into a JSON column, think twice! You might want to split your database and use normalized tables. It's like separating eggs for baking: yolks for the cake (structured data in tables) and whites for the meringue (JSON for flexible data).

Stringified JSON handling

Ever seen JSON with double quotes at the start? That's a stringified JSON, more like its undercover identity. Ping it with JSON_UNQUOTE() to unmask its real form and access the content (like unmasking superheroes, but it doesn't fly away!).

Your MySQL version

The version of your MySQL matters, especially if you're into JSON. With MySQL 5.7 onwards, handling JSON data has become easier, kind of like a cheat code. But if your server is older, consider upgrading.

Working with JSON in MySQL

Viewing your data: MySQL views

To effortlessly access your JSON data, consider creating a MySQL view. Think of it as hiring a backstage crew for your theatre play; they manage the props, change scenes, and you just enjoy the show. Here's how:

CREATE VIEW user_interests AS SELECT JSON_EXTRACT(user_profile, '$.interests') AS 'interests' FROM users;

Now user_interests acts like a table, neatly presenting your interests without the JSON fuss. Showtime!

Speed matters: Performance considerations

While JSON_EXTRACT() gives us the JSON gold, it's not a particularly fast runner for large or complex JSON data (more of a tortoise than a hare). In performance-critical situations, split your JSON into standard relational tables or materialized views.