Link: SQL

General arithmetic operator

+, -, *, /, ^

Work as usual, follow the order of standard arithmetic

Modulus %

  • Modulus or remainder function: returns the remainder of a division
SELECT 23 % 6; -- returns 5
  • Useful to identify odd or even numbers
SELECT * FROM measurements
WHERE measurement_num % 2 = 1 -- find odd numbers

Math functions

ABS() absolute value

ABS()

SELECT ABS(open-close) AS absolute_diff
FROM stock_prices

ROUND(), CEIL() and FLOOR()

  • ROUND(num, 2)
SELECT ROUND(AVG(close), 2) AS rounded_avg
FROM stock_prices
  • CEIL(): round up
  • FLOOR(): round down

POWER() squared values

  • POWER(num, x)~: num
  • POWER(num, 2): same as ^

MOD() and %

MOD(num, x): alternatively we can use %

-- same result
SELECT MOD(close, 5) AS remainder_mod,
       close%5 AS remainder_mod_alt

Division

  • For whole number like 10/4, SQL only keeps the integer part and discards the remainder
QuerySQLExcel
SELECT 10/422.5
SELECT 10/255
SELECT 10/611.666667
SELECT 10.0/42.5000002.5
SELECT 10/3.03.3333333.333333

Solutions

To show decimal output, there are few different ways

Specify decimals/floats using CAST()

QuerySQL
CAST(10 AS DECIMAL)/42.500000
CAST(10 AS FLOAT)/42.5
10/CAST(6 AS DECIMAL)1.666667
10/CAST(6 AS FLOAT)1.666667

Multiply by 1.0

Use 1.0 to convert and format to a decimal data type.

QuerySQL
10/61
10*1.0/61.666667
10/6*1.01.0
10/(6*1.0)1.666667

Use :: to divide

QuerySQL
10::DECIMAL/42.5000000
10::FLOAT/42.5
10/4::DECIMAL1.5000000
10/4::FLOAT2.5
10::FLOAT/61.666667

Show Percentage

  • Use (num / den)* 100 to convert to percentage
  • Futhurmore, use ROUND(num/den * 100, n) to round percentage
  • Limit this form to visuals or reports only
QuerySQL
SELECT (actual_sales/target_sales) * 10050.000000
SELECT ROUND((actual_sales/target_sales) * 100, 2)50.00
SELECT advertiser_id, ROUND(revenue/spend * 100, 2) as roas
FROM ad_campaigns
GROUP BY advertiser_id
ORDER BY advertiser_id