In this episode, we dig into the all-too-common habit of fetching every single column from your database when you don't actually need all that data in your app. We'll use a posts table as an example and point out that doing something like SELECT *
pulls in everything—including large bodies of text you're not even displaying, which really adds up!
You'll see us experiment with pagination and memory usage, ramping up the number of posts per page to really highlight the impact. Then, we'll refactor our code to only select the columns we're actually showing (like id
, title
, slug
, and teaser
). We'll also look at how to do this for relationships, such as only grabbing a user's name
instead of all their data.
We hit a common pitfall when restricting selected columns: forgetting to include foreign keys! You'll see an error occur when the user_id
isn't selected, since that breaks our relationship. Once we fix that, you'll immediately notice our page's memory usage drops dramatically and requests get faster.
So, the take-home? Only pull in what you really need from the database, and your app will thank you with improved performance and efficiency!