Functions have two types of parameters:

  1. Positional parameters, which require an argument.
  2. Named parameters, which optionally take an argument, otherwise using their default value.

  1. SELECT
  2. *,
  3. (temp_f - 32) / 1.8 AS temp_c
  4. FROM
  5. cities

This function is named interp, and has two positional parameters named high and x, and one named parameter named low which takes a default argument of 0. It calculates the proportion of the distance that x is between low and high.

  1. func interp low:0 high x -> (x - low) / (high - low)
  2. derive [
  3. sat_proportion_1 = (interp 1600 sat_score),
  4. sat_proportion_2 = (interp low:0 1600 sat_score),
  5. ]

  1. SELECT
  2. (sat_score - 0) / 1600 AS sat_proportion_1,
  3. (sat_score - 0) / 1600 AS sat_proportion_2
  4. FROM
  5. students

PRQL

SQL

  1. SELECT
  2. *,
  3. (sat_score - 0) / 1600 AS sat_proportion_1,
  4. (sat_score - 0) / 1600 AS sat_proportion_2
  5. FROM
  6. students

and

PRQL

  1. func fahrenheit_to_celsius temp -> (temp - 32) / 1.8
  2. from cities
  3. derive temp_c = (temp_f | fahrenheit_to_celsius)

SQL

  1. SELECT
  2. *,
  3. (temp_f - 32) / 1.8 AS temp_c
  4. FROM

PRQL

SQL

  1. SELECT
  2. *,
  3. ((temp_c - 32) / 1.8 - 0) / 100 AS boiling_proportion
  4. kettles

Scope

Functions can binding to any variables in scope when the function is executed. For example, here cost_total refers to the column that’s introduced in the from.

  1. func cost_share cost -> cost / cost_total
  2. from costs
  3. select [materials, labor, overhead, cost_total]
  4. derive [
  5. materials_share = (cost_share materials),
  6. labor_share = (cost_share labor),
  7. overhead_share = (cost_share overhead),
  8. ]

  1. SELECT
  2. materials,
  3. labor,
  4. overhead,
  5. cost_total,
  6. materials / cost_total AS materials_share,
  7. labor / cost_total AS labor_share,
  8. overhead / cost_total AS overhead_share
  9. FROM
  10. costs