SQL Basics

SQL SELECT

Master the SELECT statement to retrieve exactly the data you need from your database.

The SQL SELECT Statement

The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.

SELECT Syntax

SELECT column1, column2, ... FROM table_name;

To select all columns, use SELECT *

SELECT DISTINCT

The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; sometimes you only want to list the different values.

Column Aliases

Use AS to give a column or table a temporary name (alias). Useful for making columns more readable.

Expressions in SELECT

You can perform calculations directly in the SELECT clause.

Example

sql
-- Select all columns
SELECT * FROM products;

-- Select specific columns
SELECT product_name, price, category
FROM products;

-- Select distinct values
SELECT DISTINCT category
FROM products;

-- Column aliases
SELECT
  product_name AS name,
  unit_price AS price,
  units_in_stock * unit_price AS total_value
FROM products;

-- String concatenation
SELECT
  first_name || ' ' || last_name AS full_name,
  email,
  DATE_PART('year', created_at) AS year_joined
FROM users;

-- Conditional expression
SELECT
  name,
  price,
  CASE
    WHEN price < 10 THEN 'Budget'
    WHEN price < 50 THEN 'Mid-range'
    ELSE 'Premium'
  END AS price_tier
FROM products;

Want to run this code interactively?

Try in Compiler