SELECT Basics
In the previous lesson, you learned how to use SELECT * to retrieve everything from a table. However, in the real world, tables can have dozens or even hundreds of columns, and millions of rows!
Using SELECT * in a production environment is generally considered a bad practice because it forces the database to do unnecessary work fetching data you might not even need. This wastes bandwidth, memory, and processing power.
Selecting Specific Columns
Instead of grabbing everything, you should explicitly specify the columns you want. You do this by replacing the * with a comma-separated list of column names.
Let’s look at the products table in our E-Commerce database. It has the following columns: id, name, category, price, and stock_quantity.
If we only care about the name of the product and its category, we would write:
SELECT name, category FROM products;
Notice that the columns are returned in the exact order you specify them in your SELECT statement. If you wrote SELECT category, name FROM products;, the category column would appear first in your results.
Why this matters
Imagine a users table that has a profile_picture column storing large image files directly in the database. If you run a query to simply count how many users you have or get their email addresses, but use SELECT *, the database has to drag those massive image files across the network for absolutely no reason.
[!IMPORTANT] Always ask yourself: “Do I actually need all the columns?” Specifying exactly what you need makes your queries faster and your intent clearer to other developers reading your code.
Interactive Exercise
For your next task, the inventory manager has requested a list of our products, but they only care about the product’s name and its price. Try writing a query that returns just those two columns from the products table.