SQL Functions and Aggregation

Reference for string, date, numeric, conditional, null-handling, and aggregate SQL functions.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## String Functions
Concatenate strings
SELECT first_name || ' ' || last_name AS full_name
FROM users;

# Join multiple strings into one value.

Change case
SELECT UPPER(email) AS email_upper, LOWER(email) AS email_lower
FROM users;

# Convert strings to uppercase or lowercase.

Trim whitespace
SELECT TRIM(name) AS cleaned_name
FROM customers;

# Remove spaces from the left, right, or both sides.

Extract substring
SELECT SUBSTRING(phone FROM 1 FOR 3) AS area_code
FROM contacts;

# Return part of a string.

Replace text
SELECT REPLACE(phone, '-', '') AS digits_only
FROM contacts;

# Substitute one substring for another.

## Date and Time Functions
Get current date and timestamp
SELECT CURRENT_DATE AS today, CURRENT_TIMESTAMP AS now_ts;

# Return the current date and current timestamp.

Extract date parts
SELECT
  EXTRACT(YEAR FROM created_at) AS year_num,
  EXTRACT(MONTH FROM created_at) AS month_num
FROM orders;

# Return year, month, day, and other pieces from a date or timestamp.

Add an interval
SELECT created_at, created_at + INTERVAL '7 days' AS plus_seven_days
FROM orders;

# Shift a date or timestamp forward or backward.

Cast timestamp to date
SELECT CAST(created_at AS DATE) AS created_date
FROM orders;

# Remove the time portion from a timestamp.

## Conditional, NULL, and Conversion Functions
Use CASE expression
SELECT order_id,
       CASE
         WHEN amount >= 1000 THEN 'large'
         WHEN amount >= 100 THEN 'medium'
         ELSE 'small'
       END AS bucket
FROM orders;

# Return different values based on conditions.

Replace NULL with fallback value
SELECT COALESCE(phone, mobile_phone, 'N/A') AS preferred_phone
FROM contacts;

# Return the first non-NULL value in a list.

Convert a value to NULL conditionally
SELECT revenue / NULLIF(order_count, 0) AS revenue_per_order
FROM daily_metrics;

# Return NULL when two expressions are equal.

Convert data types
SELECT CAST(total AS DECIMAL(12,2)) AS total_decimal
FROM invoices;

# Cast an expression to a different type.

## Advanced Aggregation
Count distinct values
SELECT COUNT(DISTINCT customer_id) AS unique_customers
FROM orders;

# Count unique entries in a column.

Conditional aggregation with CASE
SELECT
  COUNT(*) AS total_orders,
  SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_orders,
  SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS refunded_orders
FROM orders;

# Compute multiple categorized totals in one query.

Aggregate by date
SELECT CAST(created_at AS DATE) AS day, COUNT(*) AS total
FROM events
GROUP BY CAST(created_at AS DATE)
ORDER BY day;

# Roll up metrics by calendar day.

Recommended next

No recommendations yet.