iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL SELECT

SELECT is the most common SQL statement. It reads rows from one or more tables, optionally filtered, joined, sorted, and aggregated.

SELECT in practice

EXAMPLE
-- Pick specific columns (preferred over SELECT *)
SELECT id, name, email
FROM users;

-- All columns (use sparingly in production code)
SELECT *
FROM users;

-- Filter with WHERE
SELECT id, name
FROM users
WHERE country = 'AU' AND active = TRUE;

-- Aliases for clarity
SELECT
  u.id        AS user_id,
  u.email     AS contact,
  o.total     AS amount
FROM users u
JOIN orders o ON o.user_id = u.id;

-- Sort + limit
SELECT id, name, signup_date
FROM users
ORDER BY signup_date DESC
LIMIT 10;

-- Group + aggregate
SELECT country, COUNT(*) AS users
FROM users
GROUP BY country
ORDER BY users DESC;

-- Subquery in WHERE
SELECT id, email
FROM users
WHERE id IN (
  SELECT DISTINCT user_id
  FROM orders
  WHERE created_at > NOW() - INTERVAL '30 days'
);

-- CTE (common table expression) - cleaner than nested subqueries
WITH recent_buyers AS (
  SELECT user_id
  FROM orders
  WHERE created_at > NOW() - INTERVAL '30 days'
  GROUP BY user_id
)
SELECT u.id, u.email
FROM users u
JOIN recent_buyers rb ON rb.user_id = u.id;

-- Window function - rank without collapsing rows
SELECT
  id, total,
  RANK() OVER (PARTITION BY user_id ORDER BY total DESC) AS rk
FROM orders;

Why it matters

List columns instead of SELECT * once you are past prototyping. Pair every SELECT with an EXPLAIN ANALYZE when performance matters. CTEs and window functions are the modern toolbox - learn them before adding application-level joins.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
SELECT id, name, email
FROM customers
WHERE active = 1
ORDER BY name ASC;
Try it Yourself »

Exercise

Read every column from the customers table.

SELECT FROM customers;

Test yourself

Q1. To return every column, you write…
Q2. Why avoid SELECT * in production?
Q3. You can use SELECT with no FROM to…

Discussion

Loading…