// SQL snippet

Profile a column: min, max, distinct

Get the shape of a table in one pass: how many rows, the range of each numeric or date column, and how many distinct values a categorical column has.

Main statement
All engines

The task

You just inherited a database and want a feel for the orders table before writing any report: typical totals, the date range covered, and whether status is really a small set of values.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT
  COUNT(*) AS row_count,
  MIN(order_date) AS earliest_order,
  MAX(order_date) AS latest_order,
  MIN(total) AS min_total,
  MAX(total) AS max_total,
  AVG(total) AS avg_total,
  COUNT(DISTINCT status) AS distinct_statuses
FROM orders;

Cómo funciona

Everything aggregates over the whole table, so the result is one row. MIN and MAX give the range for dates and numbers, AVG the center, and COUNT(DISTINCT status) says how many categories exist. If that comes back as 3, status is enum-like and worth grouping by; if it is thousands, it is free text wearing a label.

Variations

Profile every column as rows (SQL Server, PostgreSQL, SQLite, Oracle; MySQL needs CAST AS CHAR)

SQL Server PostgreSQL MySQL SQLite Oracle
SELECT 'order_date' AS column_name,
       CAST(MIN(order_date) AS VARCHAR(30)) AS min_value,
       CAST(MAX(order_date) AS VARCHAR(30)) AS max_value
FROM orders
UNION ALL
SELECT 'total', CAST(MIN(total) AS VARCHAR(30)), CAST(MAX(total) AS VARCHAR(30))
FROM orders
UNION ALL
SELECT 'status', MIN(status), MAX(status)
FROM orders;

Last 30 days only (PostgreSQL, Oracle date arithmetic)

PostgreSQL Oracle
SELECT MIN(total) AS min_total, MAX(total) AS max_total, AVG(total) AS avg_total
FROM orders
WHERE order_date >= CURRENT_DATE - 30;

Questions that come up

Does COUNT(DISTINCT status) include NULLs?

No. DISTINCT aggregates ignore NULLs, so a column that is 90 percent NULL but has two real values reports 2. That is usually what you want for a cardinality check; pair this query with the NULL-count recipe when the missing-data share matters too.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.