SQL GREATEST

Returns the largest value out of a list of arguments — a row-by-row comparison, not an aggregate across rows.

What & Why

GREATEST(value1, value2, ...) compares several values side by side, within the same row, and returns whichever one is largest. This is easy to confuse with MAX from the Aggregate Functions series — but MAX compares one column's values across many rows, while GREATEST compares several different values within one row. They solve genuinely different problems.

See How It Works

BUSINESS QUESTION

Marketing wants clicks capped at opens and unopened recipients prevented from going below zero.

idcampaign_idsent_atrecipientsopensclicksunsubscribesbounces
20112024-01-20 15:00:00+001200540180924
20222024-02-15 16:30:00+0080042096512
20332024-03-18 13:00:00+0015006102251431
20442024-04-08 14:00:00+0000000
EXAMPLE QUERY
SELECT
  id AS send_id,
  LEAST(clicks, opens) AS valid_clicks,
  GREATEST(recipients - opens, 0) AS unopened_recipients
FROM marketing.email_sends
ORDER BY send_id
LIMIT 20;
RESULT — exact output from the displayed Queryflo rows
send_idvalid_clicksunopened_recipients
201180660
20296380
203225890
20400

LEAST caps clicks and GREATEST prevents negative unopened recipients.

Now You Try

Practice this concept

Marketing wants clicks capped at opens and unopened recipients prevented from becoming negative.

Available schema
marketing

Prefix tables with marketing.table_name.

send_idvalid_clicksunopened_recipients
marketing.email_sends
ColumnType
idinteger
campaign_idinteger
sent_attimestamp with time zone
recipientsinteger
opensinteger
clicksinteger
unsubscribesinteger
bouncesinteger
legacy_send_grouptext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario