S-strings

PRQL

SQL

  1. SELECT
  2. version() AS db_version
  3. FROM
  4. my_table

Embed a column name in an s-string using braces. For example, PRQL’s standard library defines the average function as:

  1. func average column -> s"AVG({column})"

So this compiles using the function:

PRQL

  1. from employees
  2. aggregate [average salary]

SQL

  1. SELECT
  2. AVG(salary)
  3. FROM
  4. employees

Here’s an example of a more involved use of an s-string:

PRQL

SQL

  1. de.*,
  2. s.*
  3. FROM
  4. dept_emp AS de
  5. LEFT JOIN salaries AS s ON s.emp_no = de.emp_no
  6. AND (s.from_date, s.to_date) OVERLAPS (de.from_date, de.to_date)

Note that interpolations can only contain plain variable names and not whole expression like Python.

We can also use s-strings to produce a full table:

PRQL

  1. from s"SELECT DISTINCT ON first_name, id, age FROM employees ORDER BY age ASC"

SQL

  1. WITH table_0 AS (
  2. SELECT
  3. DISTINCT ON first_name,
  4. id,
  5. age
  6. FROM
  7. employees
  8. ORDER BY
  9. age ASC
  10. ),
  11. table_1 AS (
  12. SELECT
  13. *
  14. FROM
  15. salaries
  16. )
  17. SELECT
  18. table_2.*,
  19. table_3.*
  20. table_0 AS table_2
  21. JOIN table_1 AS table_3 ON table_2.id = table_3.id

Note

To output braces from an s-string, use double braces:

  1. from employees
  2. derive [
  3. ]

The PRQL compiler simply places a literal copy of each variable into the resulting string, which means we may get surprising behavior when the variable is has multiple terms and the s-string isn’t parenthesized.

In this toy example, the salary + benefits / 365 gets precedence wrong:

  1. from employees
  2. derive [
  3. gross_salary = salary + benefits,
  4. daily_rate = s"{gross_salary} / 365"
  5. ]

  1. SELECT
  2. *,
  3. salary + benefits AS gross_salary,
  4. salary + benefits / 365 AS daily_rate
  5. FROM
  6. employees

  1. from employees
  2. derive [
  3. gross_salary = salary + benefits,
  4. daily_rate = s"({gross_salary}) / 365"
  5. ]

  1. SELECT
  2. *,
  3. salary + benefits AS gross_salary,
  4. (salary + benefits) / 365 AS daily_rate
  5. FROM