1. Home
  2. Explore
  3. Computer Science
  4. SQL Fundamentals

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

SQL Fundamentals

Transcript

Learn all the basics of structured query language in this comprehensive SQL course. You will build out real database tables and practice querying them in flexible ways as a back-end web developer would in the production setting. Lane Wagner created this course. Lane is an experienced software engineer and creator of Boot.dev. So let's get started. As a web developer, you might think that you need to know JavaScript and Python and Go and TypeScript, but I'm actually here to tell you that what you really need to know is SQL or SQL. See, no matter what programming language you end up using day-to-day as a developer, it's very likely that you'll actually be using SQL alongside that programming language in your web projects. Stick around and in just a few more minutes I'll explain why SQL can actually be a game changer for your career. I'm Lane, the founder of Boot.dev and the host of the back-end banter podcast.

I've been writing SQL for about 10 years now. I've spent over a year designing this course and updating the material, and I've actually already taught thousands of students with this stuff. And all of their feedback has actually gone back into the course improving it over time. So what you're about to watch is actually some really battle-tested material. During this course, we'll be learning all the foundational SQL skills that you need, but we'll be focused on the stuff that's most important for web development. The best part is that we'll be hands-on keyboard, filling out a real-world database layer for an actual web application. It's actually a PayPal clone that I'm calling Cashpal. This next part is very important. Do not, please do not binge watch this video. Look, tutorial hell is a real place. It's a place you're going to find yourself if you don't write your own code. So please, code with me.

So, head over to boot.dev right now, grab a free account, and that's where you can actually follow along with every exercise right in your browser. Alternatively, if you don't want to create a boot.dev account, I've also linked all of the raw text files down in the description below. There's a GitHub link. Now, be aware, this SQL course is actually just one part of a full backend developer career path over on boot.dev. If you're interested in going from zero to hireable as a backend developer, definitely go check that out as well. If you get stuck during this course, don't worry about it. We've got three resources that you can check out. The first is the boot.dev discord, the second is the free code camp discord, and the third is the free code camp forum. All of those places are great resources for getting help. They'll be linked down in the description below.

Lastly, if you want to connect with me personally, there's three places. You can find me on Twitter or X at wagslane. You can go sign up on boot.dev and I'll be in your email. Or I'm also the host of the backend banter podcast, which you can find in any major podcast player or just here on YouTube. With that out of the way, let's talk about SQL. As a backend engineer, one day I'm sitting in my office at work and my boss is staring kind of longingly out the window and I walk over and he says, look at that guy. Look at that guy shoveling manure. That's what I do. That's what I do day to day as a developer. And I mean, he was right. As developers, we just kind of take data from one place and shovel it into another place. We're just kind of moving crap around. And the best tool that we have for moving crap around is SQL or SQL. Say you're a developer working at YouTube.

Your job is to shovel data from creator's devices, right? So a video, a title, a description, a thumbnail, shovel that up into the cloud and store it in some database. And then your job is to shovel that data back down to user's devices where they can watch the videos and see the thumbnails, SQL or structured query language, often also called SQL. I like to call it SQL. It's a little easier to say a few syllables. This is the language that we use to communicate with most databases.

The vast majority of databases use SQL as a query language, a protocol that we use to communicate and get data in and out of database servers, things like MySQL, PostgreSQL or SQL Lite. A database is just a piece of software that makes it easy to store large amounts of data in your computer's file system. You could kind of think about it as just a really advanced Microsoft Excel or an advanced Google sheets. When you work with Google sheets or Excel, you're probably moving data around fairly

manually right? You're pointing and clicking, dragging and dropping. When you work with SQL and with a database, you automate all of that, right? So you write code that automates the creates, the reads, the updates and the deletes within the database. That's why SQL is so cool. And that's why as backend developers, SQL is critically important. Let's hop right into the first lesson and we'll start writing some SQL. So here on the right, I have my kind of starter SQL code for the lesson. On the left, I've got my instructions. And then down here at the bottom, I have the ability to run and submit the code. Now it's important to note that all throughout this course, we're going to be writing SQL that's executed against the cash pal database. And cash pal is really just a toy web application. That's sort of a clone of PayPal. PayPal is an application for sending money online and cash pal is basically the same thing in toy form, right?

So you can imagine that the data that's stored in cash pal's database is things like users, right? Who are the people that use cash pal and then transactions, right? Every time one user sends money to another user, we need to store that information in our database. So let's jump right into the assignment. It says, I have provided a simple SQL statement for you that retrieves some records from a table. However, there isn't a people table. The table in our database is called users fix the bug by changing people to users within the select statement. So here we've got select star from people. Um, and it looks like there was just, you know, a mistake made. So we're going to swap that out for select star from users. In fact, let me really quickly run it in its old state and just see what happens. SQL logic error, no such table people. Okay cool. And then let's change it to users. Run that code perfect.

And I just want to call attention to the fact that the output of our little SQL statement here isn't console output, like you might get in a programming language like Python or go. Instead, we actually get a result set that's kind of formulated as a table of rows and columns. So now let's kind of break down the anatomy of the select statement that we modified in the first exercise. It's important to note that select statements are probably the most common type of statement that you'll write in SQL because select statements are the equivalent of a read operation, right? It's how we get data out of the database. Let's take a look at this first example, right? Select ID from users. In this case, we're selecting the ID column from the users table and all SQL statements and in a semi-colon. So we're saying, give me all of the IDs from the users table. It's also worth pointing out that keywords in SQL are case insensitive. Generally speaking, SQL is case insensitive.

So this select statement is all caps, which is typically the convention. The convention would normally also be for this from keyword to be all caps. But I just wanted to demonstrate that it doesn't actually matter. It will work either way. So we've talked about how to select a single field or a single column, right? Select ID from users. Selecting multiple fields is also pretty easy. You just separate field names with a comma, right? So if we want all of the IDs and the names from the users table, then we would select ID, comma, name from users. Now in the last assignment, we actually just selected all fields. We didn't name explicitly which fields from the table we wanted to get back. We said, just give me all of the columns that exist on the table, right? And when you want to do that, you just use the star operator or the wildcard operator instead of explicitly naming every single field and separating with commas.

So moving on to the assignment, it says the state of our cache pal users table is as follows, gives us this nice little table. So keep in mind, this is the data that's actually in the database, right? And when we write a select statement, we're generally trying to select some subset of that data. We generally don't want all of the data in the database to come back from our query. We're just trying to get at something specific, right? So the assignment goes on, it says, it's very common to write queries that only return specific portions of data from a table. Our HR team has requested a report asking for all of the names and balances of all of our users. Write a query that retrieves all of the names and balances from the users table. So let's go ahead and do that. Start with a select keyword. And we're not going to do star because we just want name and balance. We just want the name and the balance columns, right?

And I will capitalize to kind of adhere to conventions from the users table. Go ahead and run that. So you can see all we got back was names and balances. If we wanted, for example, the age as well, then we could add age here, right? We'd get an additional column back in our result set, but we don't need age, right? The assignment didn't ask for that. So we'll go ahead and submit that. So many databases use SQL. SQL is just a query language, right?

And lots of different database technologies out there use SQL or allow us to write SQL in order to interface with the database, right? So Postgres is a really popular one. It's one that I use in production all the time. SQLite is really popular. It's the one that we are using in this course, actually. SQLite is what boot dev is running on the back end to power this whole interactive experience. But really, that's all you need to know is that SQL is a common language. So when you learn SQL, you'll be able to use basically any database that supports SQL. Though it is worth mentioning that while SQL is a common language, sometimes databases support different dialects of SQL. So you will see minor differences, right? Maybe SQLite only supports certain data types, whereas Postgres supports other data types. So there are little nuances, but generally speaking, when you pick up SQL as a skill,

it will make it so that you're able to use all of these databases, even if you do have to look up little things that are different from time to time. So let's jump into this assignment. It says one way in which SQLite is a bit different is that it stores Boolean values as integers, right? The integers zero and one. So it's very kind of raw binary in that way. Select all the IDs, names, and is admin flags from the users table. Okay. Pretty straightforward. So select ID, name, is admin from users, go ahead and run that. Looks good to me. You may have heard that SQL isn't web scale. Why didn't you use MongoDB? MongoDB is a web scale database. Just by not using structured query language, you can make your database scale to billions and billions of users, anyways, that's not how it works. Let's talk about the real differences between SQL and no SQL. Let's look at a few of the more popular examples in both categories.

So on the SQL side, we've got Postgres, QL, one of my personal favorites, for sure. You've probably heard of MySQL, SQLite. We've got SQL Server, SQL Server, that's Microsoft's. You've probably heard of Oracle, and also thrown a mention of Cockroach, CockroachDB. Okay. So these are just a few examples. There's literally hundreds of SQL databases out there, but these are ones that you may have heard of. No SQL databases, got Mongo, MongoDB. You probably heard of Redis.

You may have heard of Elastic, Elasticsearch. Firebase, Firebase is pretty popular. And we'll also mention Dynamo, DynamoDB, that's Amazons. So these are just some examples of databases that fall into the SQL and the NoSQL categories. Now the first thing you need to understand about the difference between SQL and NoSQL databases is that the SQL databases tends to be much more similar. I mean, they're in a group because they're all SQL databases.

So right out of the gate, they have something in common. Whereas the NoSQL databases, all they have in common is the fact that they don't use SQL right? They don't all use the same query language, right? All SQL databases use structured query language. They have a common language that we use to interface with the databases. No SQL databases do not all use the same query language. They just don't use SQL. Now SQL databases also tend to be, they tend to be kind of general, general purpose.

Now that's not always true, right? At the end of the day, a SQL database is just any database that supports SQL, right? So you could have a specialized database, but it just so happens that the most popular SQL databases tend to sort of be general purpose, which means they're often a great starting point for most web applications or websites. And right out of the gate, I'm going to go ahead and call out an exception here in that Cockroach DB is kind of an outlier among these databases in that it's a very distributed database kind of built for scale, right? So you add some complexity to the database, you get some scaling benefits. Same with SQLite. SQLite is kind of purpose built for very small applications where you embed your database like directly within your application. So those two, I'm going to kind of just flag as a little different, not quite as general purpose.

Now, no SQL databases on the other hand, tend to be specialized, specialized, right? So usually no SQL databases are built for a very specific purpose, right? And again, I'd flag an exception MongoDB tends to be a little bit more of a general purpose database. For example, Redis is often just used for caching or kind of in memory, key value stores, right? So it's very specifically built for one use case. A lot of times, web apps will use Redis and a SQL database.

Elasticsearch, as you could probably tell, is very often used for search and used for aggregations. So if you have, for example, a giant search component on your site, right, like the eBay search bar, for example, you might use Elasticsearch to make those searches efficient. Firebase is Google's product. It's kind of specifically good at real time, real time, and mobile, like mobile apps, right? And then DynamoDB is probably actually similar to Mongo.

It's a little bit more general purpose, but it's AWS's kind of specific product for data at scale. Now I've done a lot of hand waving here, but the thing that I really want you to take away from this is that at the end of the day, an SQL database is just any database that can be interacted with using the programming language, structured query language, SQL, right? And any no SQL database is a database that just doesn't have that, right? It probably has its own kind of proprietary or specific query language that you'll use to interact with it. Just like any technology decision, when you're deciding which database to use for your project, you really need to kind of weigh the pros and cons of the database against your specific use case. That said, for most simple web applications or websites, something like Postgres is going to do really well, right?

It's a general purpose database that can handle scale at a decent level as your application scales up and you understand more your specific needs, right? Maybe you need caching, maybe you need search. You can look at introducing other database technologies to your stack. So as we spoke about earlier, the big difference between SQL and no SQL databases is just whether or not the databases support the use of SQL, right? And that's what this assignment is talking about. And it really, I want to reiterate the fact that no SQL databases don't have all that much in common, right? For example, there's a bunch of no SQL document databases and those tends to have more in common with each other, right? MongoDB and DynamoDB, for example, are both kind of document stores and they're more similar than just like the whole group of all no SQL databases, right? Key value stores like Redis and Memcached are quite similar, but they're not similar

to again, other no SQL databases like Mongo. They're kind of in a class of their own, if that makes sense. So the question for this assignment is each no SQL database tends to use blank query languages. And the answers are the same or different. And I'm going to say different because they're kind of all over the place. The next question on SQL versus no SQL is blank compatible databases tends to be more similar in their functionality than blank databases. So no SQL and SQL or SQL no skill.

Well, let's see what makes sense here. SQL compatible databases tend to be more similar in their functionality than no SQL databases. So it's going to be that second one. Next question is which type of database always uses table structures, right? So SQL organizes data into tables, right? When we were writing our SQL queries earlier, we were doing select star from users, right? The user's table stores data, SQL assumes the existence of tables that we can select data from, right?

No SQL databases don't always use that terminology. Don't even always use that way of grouping data, right? So it's just SQL that always uses table structures. I really quickly want to just compare a few of the popular SQL databases that are out there. You may have heard of Postgres, MySQL, Microsoft SQL Server, SQLite, and there are a ton of others. In fact, if you want to follow this link here, you can go look at really all of the, at least relatively well-known SQL databases that exist, and there's more than a hundred. So let's quickly just compare SQLite and Postgres. So we're using SQLite in this course, but I do use Postgres in later web development courses on boot dev. I think they're both great databases. SQLite is sort of built for the embedded use case. So it's really great when like resources are constrained, maybe you need a database on like a mobile device, or if you're deploying say to the edge, right?

Maybe if you're running a database, um, say hundreds of copies of your database on different edge servers distributed geographically around the world, SQL, SQLite can be really good for that. It's really good at being embedded within your application. So there are great use cases in production, even for SQLite, Postgres on the other hand is more of a monolith, uh, Postgres acts as a server itself and will typically be used for more traditional web applications that need to serve more users or at least operate at a larger scale. Right? So if you're storing massive amounts of data in your database, Postgres will be a better option most likely than SQLite. Postgres also just has many more features than SQLite, right? So if you're storing lots of data in a database and you need to do lots of complex things, Postgres is going to serve your needs a little bit better.

And one of those features is kind of exhaustive type checking. So SQLite is pretty loosey goosey with types, right? You can specify types on your columns, but at the end of the day, SQLite will kind of just let you put whatever you want anywhere, whereas Postgres will enforce kind of more strict static type checking. To show you what I mean, let's jump down into the assignment. So it says, let's look at how SQLite does not enforce type checking. This within the create table statement, name is defined as a text field, right? Okay. So we've got this first statement, create table users. It's got an ID field that's an integer, a name field that is text, and an age field that is an integer. Next it's inserting two records into that table. ID name age values one John Doe and 21, right? So ID one name John Doe age 21. And then also inserting a second record into the table where ID is two, name is Montgomery Burns and age is 33.

And then finally there is a select star from users table that runs. So let's go ahead and just run that code so you can see, see the output, right? Got this users table, got some data in there. So it says run the code and take a look at the results. We did that on line three, change the text string Montgomery Burns to the integer one and run the code. So this is what's kind of interesting, right? We're no longer putting text in the name field. We're putting an integer there, but it still works, right? SQLite just like doesn't care. Whereas Postgres would have actually thrown an error at us in this instance. This is notice how even though we define name as text, SQLite allowed us to use an integer like Python and JavaScript, SQLite has a loose type system. You can store anything anywhere. So to pass the assignment, submit the code in the altered state where the record with ID two has a name of one. Okay cool.

We'll just submit like this. So by now we're familiar with the idea of a table in a database, right? The table has columns and every new entry in the table is a row in the table, right? Each row, of course, having multiple cells, each with a value for the associated column, right? A table, a user's table might have ID, name, date of birth as columns, and then every new user would get their own row in the table. Well, now let's look at the SQL statement that we can use to create new tables.

Okay, so we've got the create table statement. So create table and then the name of the table. So in this example, we're creating an employees table, and then we're specifying a few different columns that we want to create, right? An ID column that's of type integer, a name column of type text, an age column of type integer, and finally is manager, which is a Boolean and salary, which is an integer. This is kind of annoying to specify the create table statement horizontally like this. So there's a little more well organized syntax that we can use like this, where we kind of split it up onto new lines with some nice indentation to make it a little bit easier to read, right? But the takeaway here is that name of the table comes right after the create table statement. Then we've got an open and a closed parentheses, and inside we specify all the fields and their types. So let's jump down into the assignment and write some SQL.

So the assignment says, let's begin building a table for the cache pal database, create the people table with the following fields. All right, so create table, going to be called people, open parentheses, the names of all the fields, we've got ID, which is an integer, then a comma to separate between the columns. You'll notice that I'm using the term column and field kind of interchangeably. In SQL world, column is definitely the more correct term. The reason you'll hear developers kind of, I don't know, slip up or use the terms field and column interchangeably is because once you convert a row in a database into a struct or an object, then within the programming language, you'd call that a field on an object. So for example, a person object might have an ID field. All right, moving on, we've got handle, which is text, name, which is text, age, which is an integer, balance, also an integer, integer, and finally is admin, is a Boolean.

Then we end all of our SQL statements with a semicolon. Great. I'm going to go ahead and run that. And just so you're aware, this next SQL statement that's running after the create table statement just kind of dumps the information about the people table. So that's why we were able to get kind of this nice little description of the table that we just created, all the different columns we created and their types. That looks correct to me. I'm going to go ahead and submit it. Now it's extremely rare to work on a web application that only has one table. Most web applications are going to have many tables. They certainly have a table per entity. So for example, in a social media application, you might have a table for your users, a table for their posts, maybe a separate table for all of the comments on those posts, and then maybe even a separate table keeping track of all the likes on the posts, right?

Well in our case, we're building a cash pal, which is a PayPal like clone. So we'll probably need another table called transactions. This is where we'll keep track of all of the payments between users. So create the transactions table with the following fields. So create table transactions, fields ID, integer, recipient ID, integer, sender ID, integer, note, text, and finally amount, integer, perfect, right? This makes sense.

Every transaction is going to get a unique ID to identify that transaction. We'll also need to keep track of the recipient and the sender in every transaction, an optional note and how much money is being sent. Cool. Let's go ahead and run that. And that's looking correct to me. Now rather than creating a new table, let's talk about changing an existing tables. This would typically be kind of dangerous, right? If you have code that depends on a specific name of a database table, then it can be tricky to kind of swap the name out live. But if you're working with a toy database or maybe you haven't pushed to production yet, this is usually a pretty simple thing to get done. We have an alter table statement that allows us to do it. So for example, if we would just want to rename a table, then we can alter table employees, rename it to the contractors table, right?

We can also rename columns by doing alter table name of the table and then rename column salary to invoice, for example, right? So the same alter table keywords are used for both altering the name of the table and the name of individual columns. And then if we're not actually renaming, but instead we're adding or deleting columns, we actually still use that same alter table keyword at the start of the SQL query. So alter table contractors, in this case, add column, and then the name of the column and its type, or just alter table contractors drop column and then the name of the column. So this alter table statement really gets a lot done for us. It's the latter half of the statement that really kind of describes what's going on. So dropping down into the assignment here, it says, we need to make some changes to the people table.

At the moment, we have these five columns shown as rows so we can display data types. Okay, so these are our columns, ID, handle, name, age, balance, is admin. Rename the table to users, rename the handle column to username and add the password, text column. Okay, so we're actually gonna be writing a few different SQL commands here. And just to start, I'm gonna go ahead and run the code in its current state and it looks like the users table doesn't exist, which if we take a look at the setup code, we can see that this is kind of what's being run before our code runs. So this makes sense, right? The people table is being created and when we kind of dump the information on the users table, it's not there. Okay, so first thing we need to do is rename the table to users. So we'll do alter, able people and then I'm gonna double check our syntax up here.

Rename to, rename to users and just so that you're aware, users is a very conventional name for the users of an application. You typically would not name all of the people that are using your tool in your database. You typically would not name that table people. In fact, I explicitly named the table people so that we could in this exercise change it to users because that's the much more kind of standard thing to do. So alter table people, rename to users, I'm gonna go ahead and run that.

Cool, now we're getting closer to the right answer, right? We're at least getting this output that describes the users table. But there's a couple more instructions. Rename the handle column to username. Okay, so after this, we'll do alter table, now called users, right? Alter table users, rename handle to usernames. It's going to be rename column handle to username, okay? This one I've seen both ways. I wouldn't say there's necessarily a right or a wrong answer around handle or username, right?

Twitter calls them handles. Most applications probably call them usernames, but it's not too important. And I would argue the more social your app is, the more likely you're probably going to call them handles. Okay, cool, let's run that. Now we can see that we've swapped that handle out for the username fields. That's looking good. And then add the password column and it should be of type text. So again, alter table users, add column, password type text. And let's run that.

Cool, this is looking good to me. I'm going to go ahead and submit it. Good database migrations are kind of like unit tests in the sense that a lot of people don't actually do them very well, but like to walk around talking about how great they are. I am an aggressive unit tester. So if you're wondering what the hell I'm talking about, this video is for you. Let's talk about database migrations. Let's jump right into an example. Let's say that we have a users table in our database and you, the users table has a few fields might have an ID. Say users have a username, maybe a password anyways, let's say that we've deployed this application to production. So we actually have users, this table is being used in production by our web application. But what happens is now we want to add a new feature and the new feature requires a new field in the database. Turns out now we need to add a new field, call it birthday.

The act of adding that field of adding a new column to the table. That is a database migration. Now this type of migration where we've added, add a new column or add a new table, it tends to be fairly safe, tends to be fairly safe. And the reason for that is the application that's been connected to this database and running queries, it didn't care about this birthday field before. It was never say, you know, querying, give me all of the users whose birthdays are before the state.

It wasn't making those queries by adding a new field. It's very unlikely that we'll break anything by adding a new table to a database that's being used. Very unlikely you'll break anything because the current code simply doesn't care about that database table because it just didn't exist in the last version. On the other hand, let's say we do a migration where we remove passwords from the users table. Maybe we're no longer storing user passwords because we only support signed one with Google, something like that. These types of migrations, right, removals of data, remove, I'll just do RM, they're very dangerous. They tend to be very dangerous. So let's talk through some rules of thumb about how you'd approach migrations depending on if your migration is adding a resource like a column or a table, deleting a column or a table, or updating because this is going to change a lot, right? So let's assume that we're adding, we're adding a new column or a new table.

This tends to be safe and so what you can do first to keep things simple is first you run the migration on the database. So you update the database, step number one, right? And by updating the database, you haven't broken what's currently running because you're just adding new stuff, right, again, generally speaking. Okay, number two, you'll update your code, right? Now you can deploy the new version of the application that actually uses those new fields or tables. Now let's assume that you're deleting a column or a table. The first thing you're actually going to do in this case is update the code, right? So presumably you're deleting a column or a table from a database because you no longer need it in your application logic, right? For whatever reason, you don't care about users' birthdays anymore so we're just going to go ahead and delete it. Well, first you need to update the code. Stop querying that resource, right?

Stop querying that column or that table. Once the code has been updated, now you can safely update the database without breaking anything. Now let's talk about the thing that is by far the hardest. This is updating. Now generally speaking, you should try just to not update. And what I mean is changing the name of a table is generally speaking just a really bad idea, changing the name of a column really bad. Try to get those things right the first time.

But if you do have to change it, just know that it's going to be more work and you need to be extra careful. Because keep in mind, when we're adding stuff, we can safely update the database beforehand. When we're deleting stuff, we can safely update the database after the fact. When we're updating stuff, there's really no safe way. I mean, think about it for just a second. You've got an old version of code that expects an old database name and a new version of code that expects a new database name. Really your only option is to make sure that you update both the database table name and the code at exactly the same moment in time. And it's really hard to make sure that happens. You're going to have probably milliseconds or seconds of downtime. So because this is a harder problem, there's not just a simple one to solution. I'm going to just give a few ideas of how you can approach updating the database. Approach number one is scheduled downtime.

Downtime. This means you literally just turn off your application. You're like, look, customers, I'm sorry, you cannot access the application for the next 30 minutes. We're doing a big update to our database. I don't recommend that that kind of sucks, right? People want access to your web application. So this is like what you would do if you really feel like you don't have any other options. It's simple, but it does affect your customers. Number two is kind of what I described at the start, which is just a same, same time deploy right? So we're just going to deploy the update and we're going to deploy the code at the same time. We understand that there will be kind of a bug there for a few seconds. But if you've determined that say you don't have any active users at the moment or a few seconds of issues, aren't really a problem and it's not worth doing anything more complex. I mean, I've seen companies do this.

I wouldn't say it's a good idea, but it does get the job done. The best approach or the most robust approach is probably to copy, to copy the database or the database table, right? So we create a new copy of the table with all the exact same data. We can update the new copy's name to be the new table, right? And now we can safely deploy the new code that references the new table. There is a possibility of, you know, in the interim of you've done the copy and now you've

deployed the new code that new records will be added to the old table that you would also need to copy, but that can also be handled, right? You can write a fairly robust migration script that copies data to the new table, deploys the code, makes sure it moves over any records that were added in the interim, that sort of thing. So copying tends to be very robust. It takes a little more work, right? You're writing a more, a more complex migration scripts to make sure that everything goes off without a hitch. Now, I know I just said that copying was the best approach and I may have misspoke there. There actually is a better approach that I'm aware of. I'm going to call it aliasing. The thing is sometimes aliasing is not possible. So there are certain databases that support an aliasing feature and some that don't. So it kind of just depends if this is available to you. But the whole idea behind aliasing is that you can give the table a second name.

So your database table effectively has two names it can be referenced by. So what that means is your old code references the old name. You alias the table with a second name, so that can be referenced by two different names. The new code uses the new name, right, and then once you've safely deployed the new code, you can drop the old name from the table. That would actually be the best, the safest and the simplest approach, but it kind of depends on your database technology and what's available to you. These are just four options. These are the four that I've tended to use the most. Hopefully they help. And then I just want to reiterate that you shouldn't be updating names very often, right? Pick good table names, pick good column names, try to do ads and deletes and avoid a bug. Now, the last thing we need to talk about with database migrations are up, up and down migrations. Right?

So we talked about the different types of migrations in the sense that you can add something, delete it, or update it. But realistically, any migration that brings us forward in time, we call an up migration, right? Our first up migration might create a table, right? And then our second migration might delete, I should say our second up migration might delete a column from that table, right? Our third up migration might create a new table, create another table.

Now let's say our fourth up migration renames a column. And then maybe our last migration deletes, deletes a table. Okay, those are all up migrations. And in theory, the latest running or the current running version of our application, we'll just use the latest version of the up migrations. In other words, it will have run every single up migration in order to arrive at kind of the final state of the database, the one that's running in production.

Now a down migration, a down migration is really just used to roll back changes in the case of emergency or in the case that something goes wrong. So you don't plan to use your down migrations. You just kind of have them as a backup. And frankly, this is why at the very beginning of the video, I talked about how people talk about great migrations, but oftentimes they don't employ them. Not every company has great plans for down migrations, just to speak frankly, it's more robust to have a great down migration so that you can roll up your database and roll down your database, bring it forward and backward in time. But it's a lot of work, right? So you won't necessarily always see teams that have fantastic down migrations, but let's just talk about what they'd look like. So a down migration is very simply just the opposite of its kind of related up migration. So when you add a new table, you might also log a down migration that deletes that same table.

So delete table, here we'd have add column, right? We're just doing the inverse of the equivalent up migration. The third down migration would delete a table again, delete table. The fourth would rename the column back to whatever it was, right? It would invert this up migration. And then finally here, we would have an add table command. And that's a five. Why did I write six? There we go. Okay. So the theory is I can go all the way up to the latest version by running these up migrations

in order. And if I need to go back a version, I can just run the equivalent down migration, right? So I get up to the latest and then I say, oh crap, I need to roll back to the last version of my database. I can just run this down migration number five to re-add that table that I just deleted. So as we just talked about, database migrations can be pretty dangerous. They tend to be some of the more dangerous things that you do when working with databases. Like with all web development, the closer you get to the data, the more careful you have to be, right? Bugs that you push to production are generally pretty easy to revert and get the right code pushed out to users and get the bug fixed. When you mess up data, sometimes it can be harder to revert those changes. So you always have to be more careful when you're working with kind of the persisted data that sticks around in your database because sometimes just changing the code back to what

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent