In SQL, an ordered-set aggregate closes its parentheses and then takes WITHIN GROUP (ORDER BY ...). DQL cannot parse anything after a function’s closing parenthesis, so in DQL the clause moves inside the call:
SQL
DQL
percentile_cont(0.5) WITHIN GROUP (ORDER BY e.value)
PERCENTILE_CONT(0.5 WITHIN GROUP ORDER BY e.value)
percentile_disc(0.9) WITHIN GROUP (ORDER BY e.value DESC)
PERCENTILE_DISC(0.9 WITHIN GROUP ORDER BY e.value DESC)
mode() WITHIN GROUP (ORDER BY e.status)
MODE(WITHIN GROUP ORDER BY e.status)
No comma between the fraction and WITHIN GROUP, and no parentheses around ORDER BY .... MODE takes no fraction, so its call starts straight with WITHIN GROUP.
ORDER BY takes exactly one item, optionally with ASC / DESC. PostgreSQL rejects more than one, and DQL does not accept a literal there.
The fraction is a literal, a parameter, or an expression over columns listed in GROUP BY. PostgreSQL rejects a fraction that reads an ungrouped column.
-- WIDTH_BUCKET: bucket number (1-based) for a value in a histogram with N equal-width bucketsSELECTWIDTH_BUCKET(e.score,0,100,10)asbucket,COUNT(e.id)ascountFROMEntityeGROUPBYbucketORDERBYbucket-- POWER used for square root and Pythagorean distanceSELECTPOWER(e.value,0.5)assquare_rootFROMEntityeWHEREe.value>0SELECTPOWER(POWER(e.x2-e.x1,2)+POWER(e.y2-e.y1,2),0.5)asdistanceFROMEntitye-- Random reservoir sampling: WHERE filters ~10% of rows, ORDER BY shuffles themSELECTeFROMEntityeWHERERANDOM()<0.1ORDERBYRANDOM()-- DQL has no LIMIT: cap the rows with $query->setMaxResults(100)-- GREATEST/LEAST with aggregates — clamp aggregate results to a floor or ceilingSELECTe.category,GREATEST(MAX(e.value),0)asmax_non_negative,LEAST(MIN(e.value),100)asmin_cappedFROMEntityeGROUPBYe.category-- Ordered-set aggregates: WITHIN GROUP ORDER BY goes inside the parentheses (see above)SELECTe.category,PERCENTILE_CONT(0.5WITHINGROUPORDERBYe.value)asmedian,PERCENTILE_DISC(0.9WITHINGROUPORDERBYe.valueDESC)astop_decile,MODE(WITHINGROUPORDERBYe.status)asmost_common_statusFROMEntityeGROUPBYe.category
📝 Function Categories:
Mathematical Functions
Basic Math: CEIL, FLOOR, ROUND, TRUNC for rounding operations
Power Functions: POWER, CBRT, EXP for exponential calculations
Logarithmic: LN, LOG for logarithmic operations
Trigonometric: DEGREES, RADIANS for angle conversions
Comparison: GREATEST, LEAST for finding extremes
Utility: SIGN, RANDOM, PI for various mathematical needs
💡 Tips for Usage:
Mathematical functions work with numeric types and return appropriate precision
WIDTH_BUCKET is excellent for creating histograms and analytics
RANDOM() generates values between 0 and 1
GREATEST/LEAST can take multiple arguments and handle NULL values