SQL

Lesson 02

Explicit SELECT columns

Select the columns the caller needs instead of depending on table shape.

Good Code

submitted-reviews.sql
SELECT
  reviews.id,
  reviews.title,
  reviews.status,
  users.name AS author_name,
  reviews.submitted_at
FROM code_reviews AS reviews
JOIN users ON users.id = reviews.author_id
WHERE reviews.status = 'submitted'
ORDER BY reviews.submitted_at DESC
LIMIT 20;

Bad Code

submitted-reviews.sql
SELECT *
FROM code_reviews
JOIN users ON users.id = code_reviews.author_id
WHERE status = 'submitted'
ORDER BY submitted_at DESC
LIMIT 20;

Review Notes

What to review

Good Code

The good version names the result columns and aliases the author field so the consumer gets a stable shape.

Bad Code

The bad version leaks every column from both tables, risks duplicate column names, and can break callers when schema changes add sensitive or unexpected fields.

Takeaways

  • A query result is an API contract, so keep its shape intentional.