You don't need NoSQL (use MySQL)
MySQL has first party support for JSON documents and it can be a really nice escape hatch from the rigid structure of a relational database.
Everything I said
I don't think enough people know, and that's probably because I don't talk about it enough, but I don't think enough people know that MySQL has full on, first party, robust support for unstructured JSON documents inside of MySQL. So you don't have to reach for a secondary NoSQL database, and you definitely don't have to use a NoSQL database as your primary data store.
Can you imagine? But you can get the best of both worlds. You can have your full on, rigid, relational, integrity driven data all in MySQL, and then have your messy, schemaless, document based, unstructured data right alongside it. So you really don't have to sacrifice anything.
So we're gonna go over, um, indexing JSON, both single keys and arrays. You can index JSON arrays, which is very cool. We're gonna go over in place updating, so you don't actually have to pull the whole object out. You can just patch the object in place. We'll look at different ways to extract data out of that JSON document or that JSON column.
But before we do that, we need to talk a little bit about philosophy, because I know that somebody is already commenting that JSON in MySQL is a mistake. JSON in a relational database is a mistake. Let me see if I can provide a little bit of nuance of when you would want to use JSON versus when you maybe wouldn't. I know that nuance on the internet is not supposed to happen, but I feel like it's my job to teach you, not give you a hot take.
So brace yourself, here comes some nuance. I think the first thing I would say is if your schema is well-defined and rigid and well-known, I wouldn't put that in a JSON blob necessarily. If your schema is well-known, MySQL is going to work better when the columns are well-defined, when the columns are discrete, when you put dates in a date column and strings in a string column.
MySQL is going to be able to work better all the way from the storage on disk through the querying up to the indexing. Everything is going to work better with compact, discrete columns. So if you know that your structure is well-defined, make top level columns out of that. There are times when your structure is not super well-defined. So there are times when maybe the structure of this blob or this set of data that you're thinking, "Should it be JSON?
Should it be a column?" That structure changes row by row or maybe per tenant. So you have a tenant that has a certain structure and another tenant or another SaaS user that has a separate structure. That might be a good time to put that in a JSON blob if the schema changes. Another thing that might be useful for a JSON blob is when you're storing a chunk or a set of data and you don't know if you need the entire thing right now, but you may need it from time to time.
So a good example of that would be the entirety of a log or a trace or an API response or even an API request. If you want to keep the parameters that you sent, you want to keep those around for debugging, maybe for 30 days or something, that might be a good, a use case for a JSON blob. Something else that might work there is, um, customer defined attributes or product defined attributes.
So if you have a T-shirt, maybe it has a size, and you, you shove all of those attributes into a JSON blob. Another thing would be, um, configuration or maybe like feature flags. So if you've got a whole bunch of feature flags per user, instead of having, you know, 30 or 40 Boolean columns that say, "Is dark mode enabled?" That sort of thing, you can wrap all those up into a JSON blob and just put those in a single column.
So there are lots of really good use cases when you really do have unstructured data that you want to store alongside of your regular traditional MySQL data. So there are a lot of good use cases. I will say that if you store a huge amount of data in there, you can start to run into some problems if you're always selecting a giant blob of data and bringing it back.
I think at PlanetScale, our JSON columns support up to, I think, 67 megs of data. I wouldn't, I wouldn't do-- don't do that. Don't put that much data in there. If you do end up with these massive blobs, there are some strategies to make sure that you're not selecting them and not bringing them back when you don't need to bring those over the wire or even get them off of the disk, and we'll look at that.
But before we do, let's, let's stop talking and let's actually play with some JSON. All right, we got a lot to cover. Let's start by creating a table here. We're just gonna put an ID so we can tell them apart, and then we'll have a column called JSON that is JSON. And let's do the same with text because there's something I want to show you here about the JSON column versus just a text column.
So if we run that, we can insert into example, and I'm just gonna start by just inserting into the JSON column. And I'm gonna insert, uh, what do you want to insert? Let's insert an object that is foo, key of foo, value of bar. We run that, and let's insert that into the text field as well. So now if we select star from example, we see that, all right, well, we've got two columns here.
We've got two columns, two rows. They both have foo bar in there. So what's the point of the JSON column versus the text column? Because we'll talk about selecting out of, um, we'll talk about selecting key parts out, but I do want to show you that if you select JSON arrow, arrow, and then we do this little dollar sign thing, which we'll talk about.
If we run that, you see that we're pulling the foo key out of the JSON blob, and that also works on the text column. So no matter if you're using JSON or text, you can actually use these JSON functions on the values stored there. So what's the benefit? What's the benefit of a JSON column versus a text column?
There are a few benefits. So if we, for example, let's say that we do something wrong. So we, we don't quote the bar. So instead of inserting, inserting a string there, it's some kind of constant that should be or variable that should be defined somewhere, and we run that. It's gonna work just fine on the text column.
So now if we read that back, it says, "Ooh, ah." It's not really JSON. It's not really JSON anymore. So let's say SELECT * FROM example. You can see it went ahead and it inserted it because this is just a text column. It went ahead and it inserted it, but now you're in this really bad spot where you have not JSON in your JSON column.
So one of the differences is if you try to do that in an actual JSON column, you get stopped at the insertion point rather than reading it back. So this will... This bad JSON is not going to make it into your database. Instead, it's gonna say, "Hey, you told me this was a JSON column. This is invalid JSON." So there's some, there's some level of data validation that goes in upfront when it's a JSON column.
Another benefit, it's kind of hard for me to demonstrate, but I can explain it to you. If you store JSON in a text column, it just sits there on disk as text, and anytime you wanna do anything, the text has to be reparse into a real JSON representation and then operated on. With a JSON column, it's actually stored in a binary format, and it has a little bit of overhead.
Um, MySQL will keep a little bit of information around as it relates to the structure of the object. But what that means is it doesn't have to be reparse from text every time you wanna deal with the JSON object. It is already a JSON object. So while you can store JSON in a JSON column or a text column, absolutely please use the JSON data type.
All right, let's keep going. I think most of the time, the JSON's gonna be coming from your application, but there are some ways you can create JSON in MySQL. And so what we did is we just, we just typed it in. We just typed it in foo, bar, and that worked. Eh, that worked just fine. There's another way that you can do that. You can say JSON object, and what this does is this accepts key one, value one, key two, value two, so on and so forth.
So what we could do here is we could put a column name. So if you're trying to create a JSON object out of some existing data, you could put column one as the name and column two as, like, the value. But we'll just keep our foo bar going, and we'll just say that the first key is foo and the first value is bar, and that will create that JSON object for us.
And so if we do baz and buzz, you'll see that it just keeps going, and it just keeps creating that object for us. This can be a nice way to create a JSON object without doing a bunch of weird string concatenation. Um, it also works with... We can just leave those and say JSON array. So if we do a JSON array, then it turns each successive, uh, argument into a part of the array.
So these are nice ways, uh, these are nice ways to create objects here. We can actually, if we do one, one, two, three, we can say that the JSON object should be, um, we'll just put a string of key, and then we can just pass in this array here. And we'll pretty that up just a little bit, and now you can see we're using these two in conjunction to create a more rich object.
There's another thing that you can do that's kind of cool. If you have a table that looks like this, SELECT * FROM eav. If you have a table that looks like this, this is the entity attribute value pattern, um, that I said early on in this video that you could just use as a JSON blob instead of doing it like this. But there are times where this exists in your database.
This exists in your database, and you want to get a JSON object out of this. So instead of doing some sort of complicated creating of this yourself, you can actually just use a function for this. So what we have here is we have an entity, some other entity. Let's call it a product or, or a piece of clothing or whatever, an item. The entity of one has an attribute of size, large, that's this first one, and color, red, that's the second one.
And the entity of two, so the second product, is a medium blue. And so what we wanna do is we wanna turn this into a JSON object, and we can do that by saying, "Give me the entity ID." And then I'm gonna do JSON object aggregate, I think. And what we're gonna say is we're gonna say that the attribute should be the key and the value should be the value, and we're gonna group by entity ID.
And what that does is that's going to group by the entity ID, and then every time it sees an attribute-value pair that matches, it's gonna put that into a JSON object. So we've turned that long table that's the EAV pattern, we've turned it into a pretty compact result set that we can send back to our application and have a nice JSON blob constructed out of this database, out of this table for us.
We're gonna move on to a more robust table that holds a bunch of products, and the attributes are stored in a JSON column. I'll put the link to where I got this table structure and data in the video description, so if you wanna follow along, you can. But let's take a look at this table. So we've got a products table here, and if you look, you'll see that this is what I was talking about. The attributes are stored as a JSON document off to the side here.
Instead of using that EAV pattern, we just threw it in a JSON blob. So we've got a bunch of good stuff in here, good, rich JSON data. Let's start talking about how we get some of this data out. And like I was telling you with a text versus a JSON column, this doesn't have to be reparse. MySQL already has this in a binary representation, so pulling this kind of stuff out is going to be quick.
So the first thing that we can do is we can look at this JSON extract. Function. And this JSON extract function takes a column, and then it takes a, a path, and the path can actually be really powerful, and we'll look at many examples of it. But the first thing that we're gonna do is we're gonna say start with the dollar sign. This is a representation of the root object or the root of the document.
Why we need to put that there, I don't know, stylistic decision that I don't super love. But after that, we can chain off of it with the dot. So if we say dollar.screen and we look at that, you'll see that it extracts the screen item out of that JSON document. Let's select the attributes column so we can see it side by side. So you'll see all of these here have a screen key at the top level that we have just extracted out.
These down here don't have it, and so it just simply returns null. So one thing that we know already is that this is really nice and safe. We don't have to check to see if the key exists or it doesn't exist. It just returns null. It doesn't blow up in our face. That's super nice. Okay, moving on. You'll see that these are all in quotes, right? So this is quote, fifty int. I mean, technically, yeah, that's exactly an exact representation.
That's not what I want. Come on. Now you know that that's not what I want. So there's another function called JSON unquote. And if you do that, it will unwrap, it will unwrap that value. And it's nice to see that if we have ports.usb here, so unquoting that three doesn't really do anything because it's already unquoted.
And so that's another safe access function. So you'll see this three here is not actually a string. It's just a number, but we can still call the unquote on it, and it just is like, "Meh, that's fine. I know, I know what you mean." So using the JSON unquote is a very nice way to get the actual value that you're looking for. Now, this is a little bit wordy, isn't it?
JSON unquote, JSON extract attributes. Yeah. That's a little wordy. There is a shorthand way to do this. So you can start with the column name and then do this arrow syntax and put your key path here. So if you do that, this is a shorthand for the JSON extraction operator, and you'll see that it pulls it out quoted again. So we don't have to wrap this in the unquote because there's an even further shorthand of double arrow.
So if you use this double arrow guy, this is a combination JSON unquoting extraction operator. I think that's exactly what it is called in the docs, the unquoting extraction shorthand operator. And if you run that, you get the exact same thing in a much less wordy kind of way. So here are some ways that you can start to pull stuff out.
When we start getting to arrays, it gets to be even more fun, as if you're not having fun yet. You're having fun. I know you're having fun. I'm having fun. Let's look at arrays because it gets even more fun. So let's see if we can find an array in this data. I think there's one for networks. I think networks is an array. So if we look down here, I'm just gonna pretend that I found it.
I didn't actually see it. And we say, I think it's dollar.networks. Is that actually a thing? No, that is not a thing. What is it actually called? A few moments later. I think it's actually called network.
Ah, I was so close. We'll see if Steve, the editor, can make that mistake disappear. It's called network. So now we have this array, right? We have this array of attributes, and now we can start doing, now we can start doing some really interesting things that you might not expect SQL can do. So let's just get rid of this guy, and we'll just select that guy. Now, what you can do here, we'll keep that one alive, and we'll drop down here.
We're gonna, we're gonna open some square brackets, and you can have just direct access like you might expect. Because we are doing that unquoting operator, we still get the benefit of the unquoting. Even though we're reaching into this array and pulling an item out, we still get it unquoted. That's kinda nice. Now, this is what you would expect, right? This is not what you would expect.
You would-- You just simply... I wouldn't expect this to work. So you can have ranges. You can pass through ranges and say zero to one or zero to two, and this is going to give you the items in there. If you say zero to ten, it'll give you up until the last item. We don't have ten items in any of these. And so this is really nice and surprising to me.
What's more surprising to me is you can just put last. You can just simply say, "Give me the last, uh, item." So there's no like, there's no breaking out of this and concatenating the JSON. I think it's length of the network minus one. You just say, "I just want the last one." Now, what if you want the second to last one?
Well, that's gonna be a lot harder. You have to put a minus one. That's it. That's all you have to do. And so you can actually say, "Give me the last," let's say, "minus two to last." What in the world? Who knew that my SQL was able to do this? Not me until, you know, I started researching for this video, but now I know and now you know as well. So playing with these array access functions can be really, really interesting, especially when you're needing to work from the end of the array back or take a range out of the array.
These can be really, really powerful. Those are good examples for pulling known entities or known quantities out of a JSON blob. Let's talk a little bit more about searching or querying on JSON instead of just, like, plucking the items that we want out. If we go back to this products table and we just pull the attributes out again, now we're gonna start looking for JSON documents that contain a single path.
There is a function called JSON contains path, where you pass in the JSON column, and then you have to specify, do you just want one match, or do you w- need every single thing to match? I'll show you that in a second. We'll start with one. And I wanna pull documents or match documents that have a ports key on the root document or the root node.
So if we do that, you see over here, you're left with a nice one, one, one, zero, zero, zero. Which means you can move that guy down here and say where that. And now you get just your five. What is that? Five. You get your five items back. So the one versus many thing. What we can do is we can just keep going. We can just keep passing through new keys over here, and this will continue to match the same number.
But you'll see that I modified this one to say SCRN instead of screen. So now if I say, "Actually, I need all of the keys to be present," and you run that one, now it goes away because it only had ports and it doesn't have screen. So this JSON contains path is a nice way to see if there is, um, if there is a key in a JSON document.
We've tested to see if an object contains a key path, but now let's check to see if an array contains a particular item. So if we look here and we try to remember what the array is, let's see if we can do it first time this time, dollar dot network. All right. Cool. There is our array. And what we wanna do is we wanna check to see if, uh, let's say HSPA is in that array.
So I'm gonna say HSPA, and then I'm gonna use member of this array. And now this will show you where HSPA is a member of that array, which of course means we can drop this down just like we did and use this as a where. So now we have all of the rows or the records where HP- HSPA is in that array.
All right. Hopefully, this is showing you that there are a lot of JSON functions, and we've only barely scratched the surface of how many JSON functions there are. But I do wanna move on to indexing JSON documents. There are two types of indexes that you can put on a JSON document. One is just a traditional key, right? So we can index a particular key in the document, and that's just kinda like a normal index.
We can do that either through a generated column or a functional index. And I have a full video, uh, that goes really into detail on that, but I'll show you a few examples here. The second type of index that you can put on a JSON document is very, very interesting because it's not one that MySQL had prior to eight dot zero dot seventeen, and that's a multi-value index, which is, I think, exclusively for creating indexes on JSON arrays.
So traditionally, when you create an index in MySQL, you're putting an index on a column that contains a single value: first name, last name, email, whatever. With one of these multi-value indexes that are very new, you can create an index over an array of items and then when we do our member of query, it will use that multi-value index. Let me show you how these work. Let's start by explaining this query just to prove we don't have any indexes.
It's just doing a full table scan, and this is actually what we're trying to remedy here. So this is our array. Let's just drop that out, and we'll say alter table products, and we're just gonna add an index called... What do you wanna call it? Let's call it networks. And I'm gonna open a double set of parentheses. A single set of parentheses is what you would do if you were just putting an index on a column name or multiple columns.
But when you are creating a functional index, which means the index on the result of a function, you do a double set of parentheses, and then you put your function definition in here. So here is our, you know, function definition, which is pulling this array out. We have to do one more thing. When we, when we pull this out, we need to tell MySQL what the data type is.
So we're gonna cast this as a two hundred and fifty-five character. It-- there is no cast as a variable or varying length character, so we just say character two fifty-five, and we call it an array. And that should create the index on our table. Now, if we go back and we say select star from products where, uh, what was it?
H- HSPA member of our array, and we run that, we still get the same thing back, but now we are using an index. So this is really interesting to me because this is like the first time that we've ever been able to index this m- multiple values in a single index entry instead of just first name, last name, email.
We're now indexing six items, and our comparison is, is this HSPA in, in this array of six items? And so this is a really, really powerful way to index these multiple values in, in a way that we've never been able to do before. So here we created a functional index. We created a functional index on a part of a JSON document.
Let me show you how we can create a generated column and kinda get the same thing. Let's just look at this entire table again and see what we want our generated column to be. Um, let's just pull the screen key out to the top level. So the way that we can get that again is we will say attributes, and then we'll use that JSON unquoting operator dollar sign dot screen.
Double-check. Okay, we are getting that screen pulled out to the top level. And now what we can do is we can say alter table products, add column screen, um, as a... Uh, that's probably long enough. And then we'll say generated always as, and we'll put our, uh, we'll put our expression in there.
And if we run that and say select star from products, now we have a generated column, a top-level column that we can address by name. So if we get rid of that, pretty that up, and then just say ID and screen, you can see now it is a top-level column. Now, this is a generated column. We could put an index on top of that just as you would any other column that has ever existed since the dawn of time.
We could have created a functional index to do this. Under the hood, functional indexes use generated columns. They just hide it from you. So if you wanna create the generated column to have it on the top level to see it on your table, that is fine. If you wanna skip that and create a functional index only and you don't wanna see this on your, on your table, that is also fine.
There is no difference. At this point, at this point This generated column is a virtual column. This is a virtual column, meaning that this is calculated at runtime. So it's basically as if it's a shorthand for writing this for us. It, it's not actually stored on the disk, because it's a generated column that is virtual.
There is a type of generated column that is stored on the disk, and that is a stored generated column. What's the difference? Why, when it comes to JSON, would you want to have a virtual column versus a stored generated column? I don't know that there's a lot of reason, generally, to s- to choose a stored generated column.
The difference is, when it comes to JSON, I can definitely think of a reason to choose a stored generated column. Let's look at this again. So if we do, um, let's just back up out of here. And so this is how we created, this is how we created our generated column, right? We called it screen, generated always as, and then you just throw stored.
You just throw the word stored on there at the end. We'll call this screen2, create that, and now if we do select star... Let's do select ID and screen2 from products. Same thing. Same exact thing, but here's the difference. Here's the difference. Screen2 has actually been written to the disk.
What that means is that means MySQL does not need to go over to that JSON blob, which could potentially be stored in a different location on disk. That is the trick. If the JSON blob gets big enough, what MySQL's going to do is it's going to say, "Hey, that's a really big column." It'll do this with blobs, texts, um, JSON, medium texts, long texts, any of those big blobby columns, what MySQL's gonna do is gonna say, "I'm not gonna store that in the actual row anymore.
It's too big. What I'm gonna do is I'm gonna leave a pointer in the row on the disk. I'm gonna leave a pointer to a secondary location where that big blob is stored." There's a big blob parking lot, and that's where it puts all of your text columns, your blobs, your JSONs. All those big guys, stores them somewhere else.
Now, if you write this generated column to disk, it no longer has to go over there and inspect that JSON blob to calculate that value. So if you are not selecting the JSON blob at all, it never has to touch it, and so this is a good, this is a very, very good use case for writing the generated column to the disk and leaving that expensive, heavy blob alone.
We can take this a step further, 'cause what we're trying to avoid is we're trying to avoid bringing this blob along for a ride that it doesn't need to be a part of, right? So if you're using explicit column listing like this, that's fine, 'cause we haven't selected attributes, so we're not bringing the blob along for a ride. However, if somebody does select star, which, you know, eh, I don't really recommend. I don't recommend select star.
Sometimes it happens, and a lot of times an ORM will do it. If you're, if you're using select star, you're bringing this blob along for the ride when you may not need it. Now, what you can do is you can say alter table products, alter column attributes set invisible. And if we run that and then, watch this, select star from products, it's not there.
It is now invisible. So now you have, you have ensured that even when someone runs select star, they're not gonna get that attributes column back. Is that a good idea? I don't know. You'd have to discuss it with your team. But you have ensured that that big blob isn't coming along for the ride unless you explicitly add it in.
And so in this situation, this might be a good use case for creating some stored generated columns for keys that you access often. Those keys will be written to the actual table, and so it's as if you have these top level columns that are driven by the JSON data, and the JSON data stays invisible, never to be brought along for a ride that it shouldn't be a part of, and you still get this nice, um, rich access to the JSON data that is written to disk.
So you incur a little bit of overhead, um, in the actual storage, but it's not that bad, because now you're leaving this heavy thing off to the side. You can tell that I love JSON in MySQL, right? I think it's so powerful, so flexible. There's one more thing I wanna show you, and that's updating these documents in place. You don't have to pull the entire object out, muck around with it, and put it back in.
You can update it in place, and that's a lot faster. So let me show you how you can do this. We're gonna update the USB ports on this first item from three to four. And what you could do is you could say update products set attributes equal to, and then just construct an entirely new object, where you, you've pulled the old object, you've changed some stuff, and now you're just gonna throw the entirely new object back in, where ID equals one.
I don't want to do it that way, 'cause I just wanna target that one key and change the value there. So what we can do is we can say JSON set attributes, and then we, we do the whole key path dance again, right? So we say dollar.ports.usb, and we wanna set that value to four. Now, what this is gonna do is this is going to update it in place without having to change the entire object, and this is an optimizer enhancement that started,
uh, maybe in 8.0.7 or something like that. Um, so if we run this guy, and then let's just get rid of it and select star from products, we'll see... Ah, we made it invisible, didn't we? Select star and attributes from products. We'll see that the ports have been updated to four. There are three functions that operate in place, JSON set, JSON insert, and JSON replace.
That's listed in the docs, but I did wanna tell you here. The other ones do not operate in place, and that's not the end of the world. Um, but if you can get away with using the JSON set function, that is gonna operate in place and that is gonna be a little bit faster. JSON, amazing, powerful, we love it. Use it when it's useful. Don't use it when it's not useful. I read every single comment, but I don't wanna read any comments about JSON never being useful.
If y'all wanna battle in the comments, that's totally fine. I might recuse myself from that battle. I would love to hear where you have used JSON in your schemas, where it has been valuable and powerful for you, and other things that you think I may have missed as it relates to JSON. Please leave a comment. If you liked this, you can visit us at planetscale.com/youtube.
I teach an eight-hour course on just MySQL. It's totally free. I would love to see you over there. Until the next time, see ya.