### Install via Winget Source: https://prql-lang.org/book/project/integrations/prqlc-cli.html Installation command for Windows users using Winget. ```bash winget install prqlc ``` -------------------------------- ### Install via Homebrew Source: https://prql-lang.org/book/project/integrations/prqlc-cli.html Installation command for macOS users using Homebrew. ```bash brew install prqlc ``` -------------------------------- ### Install cargo-insta Source: https://prql-lang.org/book/project/contributing/development.html Installs the cargo-insta testing framework used for snapshot testing. ```bash cargo install cargo-insta ``` -------------------------------- ### Compile documentation examples to test SQL Source: https://prql-lang.org/book/project/contributing/development.html Compiles all examples from documentation (Website, README, PRQL Book) to verify they produce expected SQL and catch regressions. ```shell cargo insta test --accept ``` -------------------------------- ### Install pyprql Source: https://prql-lang.org/book/project/integrations/jupyter.html Install the pyprql package to enable PRQL support in Jupyter. ```bash pip install pyprql ``` -------------------------------- ### Install prqlc via npm Source: https://prql-lang.org/book/project/bindings/javascript.html Install the prqlc package using npm. ```bash npm install prqlc ``` -------------------------------- ### Install and load PRQL extension in DuckDB Source: https://prql-lang.org/book/project/integrations/duckdb.html Use these commands to install and load the PRQL community extension, then execute a PRQL query against a CSV file. ```sql INSTALL prql FROM community; LOAD prql; -- Once the extension is loaded, you can write PRQL queries from (read_csv 'https://raw.githubusercontent.com/PRQL/prql/0.8.0/prql-compiler/tests/integration/data/chinook/invoices.csv') filter invoice_date >= @2009-02-01 take 5; ``` -------------------------------- ### Install via Cargo Source: https://prql-lang.org/book/project/integrations/prqlc-cli.html Installation commands for installing from crates.io or a local repository. ```bash # From crates.io cargo install prqlc ``` ```bash # From a local PRQL repository cargo install --path prqlc/prqlc ``` -------------------------------- ### Run setup-dev task Source: https://prql-lang.org/book/project/contributing/development.html Runs the project's setup-dev task to install dependencies via Taskfile.yaml. ```bash task setup-dev ``` -------------------------------- ### Install prqlc via pip Source: https://prql-lang.org/book/project/bindings/python.html Install the prqlc Python package from PyPI using pip. ```bash pip install prqlc ``` -------------------------------- ### SQL: Translation of comprehensive parentheses example Source: https://prql-lang.org/book/reference/syntax/operators.html Equivalent SQL generated from the PRQL example above, showing how each PRQL expression translates to SQL operations like BETWEEN, SUM OVER, MIN OVER, and ORDER BY. ```SQL __ SELECT *, distance BETWEEN 0 AND 20 AS is_proximate, SUM(distance) OVER () AS total_distance, MIN(COALESCE(distance, 5)) OVER () AS min_capped_distance, distance / 40 AS travel_time, ROUND(distance, 1 + 1) AS distance_rounded_2_dp, distance >= 100 AS is_far, distance BETWEEN -100 AND 0, distance BETWEEN -100 AND 0 AS is_negative, AVG(distance) OVER () AS average_distance FROM employees ORDER BY distance DESC ``` -------------------------------- ### PRQL loop example Source: https://prql-lang.org/book/reference/stdlib/transforms/loop.html An example of using the loop transform to increment a value until a condition is met. ```prql from [{n = 1}] loop ( filter n<4 select n = n+1 ) # returns [1, 2, 3, 4] ``` -------------------------------- ### Install prql-compiler via Homebrew Source: https://prql-lang.org/book/project/changelog.html Use the Homebrew package manager to install the PRQL compiler on macOS or Linux. ```bash brew install prql-compiler ``` -------------------------------- ### SQL translation for SQLite division example Source: https://prql-lang.org/book/reference/stdlib SQL translation of the SQLite division example, showing how PRQL compiles / and // for SQLite. ```SQL __ WITH table_0 AS ( SELECT 13 AS x, 5 AS y ) SELECT (x * 1.0 / y) AS quotient, CAST(ABS(x * 1.0 / y) AS INTEGER) * SIGN(x) * SIGN(y) AS int_quotient FROM table_0 ``` -------------------------------- ### Global sort and take Source: https://prql-lang.org/book/reference/stdlib/transforms/group.html Example of finding the first employee to join across the entire table. ```prql from employees sort join_date take 1 ``` ```sql SELECT * FROM employees ORDER BY join_date LIMIT 1 ``` -------------------------------- ### Install prqlr package Source: https://prql-lang.org/book/project/bindings/r.html Use this command to install the prqlr package from CRAN. ```R install.packages("prqlr") ``` -------------------------------- ### Take transform with ranges in SQL Source: https://prql-lang.org/book/reference/syntax/ranges.html The equivalent SQL output for the PRQL take range example. ```sql __ SELECT * FROM orders ORDER BY value DESC, created_at LIMIT 10 OFFSET 100 ``` -------------------------------- ### Root module example with nested modules Source: https://prql-lang.org/book/reference/spec/modules.html Shows a root module containing a std module with function definitions and a default_db module for inferred tables and CTEs, plus a main query selecting from tracks. ```prql module project { module std { let sum = a -> ... let mean = a -> ... } module default_db { # all inferred tables and defined CTEs } let main = ( from t = tracks select [track_id, title] ) } ``` -------------------------------- ### Basic usage of prqlc.compile Source: https://prql-lang.org/book/project/bindings/python.html Shows how to import prqlc, define a PRQL query, create CompileOptions, and compile to SQL with and without options. The example uses a join and group/aggregate. ```python import prqlc prql_query = """ from employees join salaries (==emp_id) group {employees.dept_id, employees.gender} ( aggregate { avg_salary = average salaries.salary } ) """ options = prqlc.CompileOptions( format=True, signature_comment=True, target="sql.postgres" ) sql = prqlc.compile(prql_query) sql_postgres = prqlc.compile(prql_query, options) ``` -------------------------------- ### SQL output for PRQL comment example Source: https://prql-lang.org/book/reference/syntax/comments.html The SQL generated from the PRQL comment example, showing the equivalent SELECT query with AVG(salary) from employees. ```sql SELECT AVG(salary) FROM employees ``` -------------------------------- ### Start interactive mode Source: https://prql-lang.org/book/project/integrations/prqlc-cli.html Running prqlc compile without arguments starts an interactive session where you can input PRQL and compile it to SQL by pressing Ctrl-d or Ctrl-z. ```bash prqlc compile ``` -------------------------------- ### PRQL and SQL Salary Calculation Example Source: https://prql-lang.org/book/reference/stdlib/index.html Demonstrates calculating gross salary and rounding it, alongside retrieving the current timestamp in both PRQL and the resulting SQL. ```prql __ from employees derive { gross_salary = (salary + payroll_tax | as int), gross_salary_rounded = (gross_salary | math.round 0), time = date.now, # current timestamp; or use s"NOW()" for a dialect-specific s-string } ``` ```sql __ SELECT *, CAST(salary + payroll_tax AS int) AS gross_salary, ROUND(CAST(salary + payroll_tax AS int), 0) AS gross_salary_rounded, CURRENT_TIMESTAMP AS time FROM employees ``` -------------------------------- ### PRQL round and cast syntax example Source: https://prql-lang.org/book/project/changelog.html Demonstrates the updated parameter order for round and cast functions, allowing for consistent piping. ```prql derive [ gross_salary = (salary + payroll_tax | as int), gross_salary_rounded = (gross_salary | round 0), ] ``` -------------------------------- ### Development commands with uv and task Source: https://prql-lang.org/book/project/bindings/python.html Commands for installing development dependencies, running tests, type checking, and using the task runner. ```bash # Install development dependencies and run tests uv run pytest # Run type checking uv run ty check # Or use the task runner task test ``` -------------------------------- ### SQL parameter syntax Source: https://prql-lang.org/book/reference/syntax/parameters.html Example of the compiled SQL output using a positional parameter. ```sql __ SELECT * FROM employees WHERE id = $1 ``` -------------------------------- ### Left Join Example Source: https://prql-lang.org/book/reference/stdlib/transforms/join.html A basic left join between employees and positions tables. ```prql from employees join side:left positions (employees.id==positions.employee_id) ``` ```sql SELECT employees.*, positions.* FROM employees LEFT OUTER JOIN positions ON employees.id = positions.employee_id ``` -------------------------------- ### Compile PRQL to SQL using Compiler class Source: https://prql-lang.org/book/project/bindings/php.html PHP example using Prql\Compiler\Compiler to compile a PRQL query and output the result. ```php compile("from employees"); echo $result->output; ``` -------------------------------- ### SQL translation of PRQL derive example Source: https://prql-lang.org/book/reference/stdlib SQL translation of the PRQL derive example, showing the generated SELECT statement with CAST, ROUND, and CURRENT_TIMESTAMP. ```SQL __ SELECT *, CAST(salary + payroll_tax AS int) AS gross_salary, ROUND(CAST(salary + payroll_tax AS int), 0) AS gross_salary_rounded, CURRENT_TIMESTAMP AS time FROM employees ``` -------------------------------- ### Basic PRQL Query and SQL Compilation Source: https://prql-lang.org/book/index.html A simple example demonstrating how PRQL filters data and aggregates columns compared to the equivalent SQL query. ```prql __ from tracks filter artist == "Bob Marley" # Each line transforms the previous result aggregate { # `aggregate` reduces each column to a value plays = sum plays, longest = max length, shortest = min length, # Trailing commas are allowed } ``` ```sql __ SELECT COALESCE(SUM(plays), 0) AS plays, MAX(length) AS longest, MIN(length) AS shortest FROM tracks WHERE artist = 'Bob Marley' ``` -------------------------------- ### Identifier examples Source: https://prql-lang.org/book/reference/syntax/keywords.html Examples of valid PRQL identifiers including alphanumeric characters, underscores, and the dot lookup operator. ```prql __ hello _h3llo hello.world ``` -------------------------------- ### Grouped sort and take Source: https://prql-lang.org/book/reference/stdlib/transforms/group.html Example of finding the first employee to join within each department using the group transform. ```prql from employees group role ( sort join_date # taken from above take 1 ) ``` ```sql WITH table_0 AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY role ORDER BY join_date ) AS _expr_0 FROM employees ) SELECT * FROM table_0 WHERE _expr_0 <= 1 ``` -------------------------------- ### PRQL example: division and integer division for MySQL Source: https://prql-lang.org/book/reference/stdlib PRQL query targeting sql.mysql that computes quotient and int_quotient using / and // operators on a literal table. ```PRQL __ prql target:sql.mysql from [{x = 13, y = 5}] select { quotient = x / y, int_quotient = x // y, } ``` -------------------------------- ### SQL: Equivalent output for PRQL r-string example Source: https://prql-lang.org/book/reference/syntax/r-strings.html The SQL generated by the PRQL compiler for the r-string example. It shows the literal backslash and tab characters in the normal_string value and the escaped backslashes in the raw_string value. ```sql SELECT *, '\ ' AS normal_string, '\\\t' AS raw_string FROM artists ``` -------------------------------- ### Compile PRQL in Rust Source: https://prql-lang.org/book/project/integrations/prqlc-cli.html Example of using the prqlc library in Rust to compile a PRQL string to a specific SQL dialect. ```rust #![allow(unused)] fn main() { // In a file src/main.rs use prqlc::{compile, Options, DisplayOptions, Target, sql::Dialect}; let prql = "from employees | select {name, age}"; let opts = &Options { format: false, target: Target::Sql(Some(Dialect::SQLite)), signature_comment: false, display: DisplayOptions::Plain, ..Default::default() }; let sql = compile(&prql, opts).unwrap(); assert_eq!("SELECT name, age FROM employees", sql); } ``` -------------------------------- ### Filter with ranges in SQL Source: https://prql-lang.org/book/reference/syntax/ranges.html The equivalent SQL output for the PRQL range filter example. ```sql __ SELECT *, latitude >= 0 AS is_northern FROM events WHERE created_at BETWEEN DATE '1776-07-04' AND DATE '1787-09-17' AND magnitude BETWEEN 50 AND 100 ``` -------------------------------- ### SQL translation of PRQL expression example Source: https://prql-lang.org/book/reference/syntax/operators.html The SQL translation of the PRQL expression example, using a CTE and POW for exponentiation. The filter becomes a WHERE clause with AND and <>. ```SQL WITH table_0 AS ( SELECT diameter * 3.14159 AS circumference, POW(diameter / 2, 2) AS area, color FROM foo ) SELECT circumference, area, color FROM table_0 WHERE circumference > 10 AND color <> 'red' ``` -------------------------------- ### Define a module structure with nested namespaces Source: https://prql-lang.org/book/reference/spec/modules.html This example illustrates the conceptual module structure using the 'module' keyword and curly braces to define nested namespaces and declarations. ```prql __ module my_playlists { let bangers = ... # a declaration module soundtracks { let movie_albums = ... # another declaration } } ``` -------------------------------- ### PRQL Number Literals Source: https://prql-lang.org/book/reference/syntax/literals.html Example demonstrating various number literal formats in PRQL, including underscores for readability, scientific notation, and base prefixes. ```prql __ from numbers select { small = 1.000_000_1, big = 5_000_000, huge = 5e9, binary = 0b0011, hex = 0x80, octal = 0o777, } ``` -------------------------------- ### PRQL example: division and integer division for SQLite Source: https://prql-lang.org/book/reference/stdlib PRQL query targeting sql.sqlite that computes quotient and int_quotient using / and // operators on a literal table. ```PRQL __ prql target:sql.sqlite from [{x = 13, y = 5}] select { quotient = x / y, int_quotient = x // y, } ``` -------------------------------- ### Run database integration tests Source: https://prql-lang.org/book/project/contributing/development.html Runs example queries against databases with actual data to ensure correct SQL across supported dialects. Requires a clang compiler for DuckDB; on Windows these tests are excluded. ```shell task prqlc:test-all # or cargo insta test --accept --features=default,test-dbs ``` -------------------------------- ### SQL equivalent of PRQL text functions Source: https://prql-lang.org/book/reference/stdlib/text.html Shows the SQL translation for the PRQL text module operations demonstrated in the previous example. ```sql __ SELECT LOWER(last_name) LIKE CONCAT('a', '%'), REPLACE(title, 'manager', 'chief') FROM employees ``` -------------------------------- ### Advanced PRQL Pipeline and SQL Compilation Source: https://prql-lang.org/book/index.html A complex example showing data transformation, grouping, aggregation, and the use of F-strings and S-strings in PRQL, alongside the resulting SQL. ```prql __ from employees filter start_date > @2021-01-01 # Clear date syntax derive { # `derive` adds columns / variables gross_salary = salary + (tax ?? 0), # Terse coalesce gross_cost = gross_salary + benefits, # Variables can use other variables } filter gross_cost > 0 group {title, country} ( # `group` runs a pipeline over each group aggregate { # `aggregate` reduces each group to a value average gross_salary, sum_gross_cost = sum gross_cost, # `=` sets a column name } ) filter sum_gross_cost > 100_000 # `filter` replaces both of SQL's `WHERE` & `HAVING` derive id = f"{title}_{country}" # F-strings like Python derive country_code = s"LEFT(country, 2)" # S-strings permit SQL as an escape hatch sort {sum_gross_cost, -country} # `-country` means descending order take 1..20 # Range expressions (also valid as `take 20`) ``` ```sql __ WITH table_0 AS ( SELECT title, country, AVG(salary + COALESCE(tax, 0)) AS _expr_0, COALESCE(SUM(salary + COALESCE(tax, 0) + benefits), 0) AS sum_gross_cost FROM employees WHERE start_date > DATE '2021-01-01' AND salary + COALESCE(tax, 0) + benefits > 0 GROUP BY title, country ) SELECT title, country, _expr_0, sum_gross_cost, CONCAT(title, '_', country) AS id, LEFT(country, 2) AS country_code FROM table_0 WHERE sum_gross_cost > 100000 ORDER BY sum_gross_cost, country DESC LIMIT 20 ``` -------------------------------- ### PRQL: Comprehensive parentheses examples Source: https://prql-lang.org/book/reference/syntax/operators.html Shows when parentheses are required in PRQL: for pipes, function calls, negative numbers, and function calls in larger expressions. Includes a tuple with multiple derives and sorting by negative distance. ```PRQL __ from employees # Requires parentheses, because it contains a pipe derive is_proximate = (distance | in 0..20) # Requires parentheses, because it's a function call derive total_distance = (sum distance) # `??` doesn't require parentheses, as it's not a function call derive min_capped_distance = (min distance ?? 5) # No parentheses needed, because no function call derive travel_time = distance / 40 # No inner parentheses needed around `1+1` because no function call derive distance_rounded_2_dp = (math.round 1+1 distance) derive { # Requires parentheses, because it contains a pipe is_far = (distance | in 100..), # The left value of the range requires parentheses, # because of the minus sign is_negative = (distance | in (-100..0)), # ...this is equivalent is_negative = (distance | in (-100)..0), # _Technically_, this doesn't require parentheses, because it's # the RHS of an assignment in a tuple # (this is especially confusing) average_distance = average distance, } # Requires parentheses because of the minus sign sort (-distance) # A tuple is fine too sort {-distance} ``` -------------------------------- ### Join with Multiple Conditions Source: https://prql-lang.org/book/reference/stdlib/transforms/join.html A join example demonstrating the use of multiple conditions including a filter. ```prql from tracks join side:left artists ( # This adds a `country` condition, as an alternative to filtering artists.id==tracks.artist_id && artists.country=='UK' ) ``` ```sql SELECT tracks.*, artists.* FROM tracks LEFT OUTER JOIN artists ON artists.id = tracks.artist_id AND artists.country = 'UK' ``` -------------------------------- ### SQL Number Literals Compilation Source: https://prql-lang.org/book/reference/syntax/literals.html The corresponding SQL output for the PRQL number literal example. ```sql __ SELECT 1.0000001 AS small, 5000000 AS big, 5000000000.0 AS huge, 3 AS "binary", 128 AS hex, 511 AS octal FROM numbers ``` -------------------------------- ### Use s-strings for from transform Source: https://prql-lang.org/book/project/changelog.html Example of using an s-string to define a from transform in PRQL. ```prql from s"SELECT * FROM employees WHERE foo > 5" ``` -------------------------------- ### Define PRQL annotation for binding strength Source: https://prql-lang.org/book/project/changelog.html Example of using the @ syntax for annotations to specify binding strength in PRQL. ```prql __ @{binding_strength=11} let mod = l r -> s"{l} % {r}" ``` -------------------------------- ### Use the case function Source: https://prql-lang.org/book/project/changelog.html The experimental case function sets a variable based on multiple expressions. This example shows the PRQL source and its compiled SQL output. ```prql derive var = case [ score <= 10 -> "low", score <= 30 -> "medium", score <= 70 -> "high", true -> "very high", ] ``` ```sql SELECT *, CASE WHEN score <= 10 THEN 'low' WHEN score <= 30 THEN 'medium' WHEN score <= 70 THEN 'high' ELSE 'very high' END AS var FROM bar ``` -------------------------------- ### SQL recursive CTE equivalent Source: https://prql-lang.org/book/reference/stdlib/transforms/loop.html The SQL output generated by the PRQL loop example using a recursive CTE. ```sql WITH RECURSIVE table_0 AS ( SELECT 1 AS n ), table_1 AS ( SELECT n FROM table_0 UNION ALL SELECT n + 1 FROM table_1 WHERE n < 4 ) SELECT n FROM table_1 AS table_2 ``` -------------------------------- ### derive multiple columns Source: https://prql-lang.org/book/reference/stdlib/transforms/derive.html Example of adding multiple calculated columns, where subsequent columns can reference previously derived ones. ```prql from employees derive { gross_salary = salary + payroll_tax, gross_cost = gross_salary + benefits_cost } ``` ```sql SELECT *, salary + payroll_tax AS gross_salary, salary + payroll_tax + benefits_cost AS gross_cost FROM employees ``` -------------------------------- ### PRQL division operators / and // Source: https://prql-lang.org/book/reference/syntax/operators.html Demonstrates the difference between float division (/) and integer division (//) in PRQL. The target is set to sql.sqlite, and the example uses a literal table with positive and negative values. ```PRQL prql target:sql.sqlite from [ {a = 5, b = 2}, {a = 5, b = -2}, ] select { div_out = a / b, int_div_out = a // b, } ``` -------------------------------- ### PRQL query example Source: https://prql-lang.org/book/project/bindings/python.html A simple PRQL query that filters tracks by artist and aggregates plays, longest, and shortest lengths. Demonstrates the pipelined syntax with comments and trailing commas. ```prql from tracks filter artist == "Bob Marley" # Each line transforms the previous result aggregate { # `aggregate` reduces each column to a value plays = sum plays, longest = max length, shortest = min length, # Trailing commas are allowed } ``` -------------------------------- ### Build prqlc JavaScript bindings Source: https://prql-lang.org/book/project/bindings/javascript.html Build the Node, bundler, and web packages. ```bash npm run build ``` -------------------------------- ### SQL equivalent for window function Source: https://prql-lang.org/book/reference/stdlib/transforms/aggregate.html The SQL translation of the derive example, using AVG(salary) OVER () to add a column without reducing rows. ```SQL SELECT *, AVG(salary) OVER () AS avg_sal FROM employees ``` -------------------------------- ### SQL equivalent for aggregate with group Source: https://prql-lang.org/book/reference/stdlib/transforms/aggregate.html The SQL translation of the grouped aggregate example, using GROUP BY on title and country. ```SQL SELECT title, country, AVG(salary), COUNT(*) AS ct FROM employees GROUP BY title, country ``` -------------------------------- ### Cyclic references between modules are allowed Source: https://prql-lang.org/book/reference/spec/modules.html Shows that modules can reference each other cyclically. The example defines mod_a and mod_b, where mod_a references mod_b.decl_b and mod_b references mod_a.decl_a. ```prql module mod_a { let decl_a_1 = ... let decl_a_2 = (from mod_b.decl_b | take 10) } module mod_b { let decl_b = (from mod_a.decl_a | take 10) } ``` -------------------------------- ### Run website components locally Source: https://prql-lang.org/book/project/contributing/development.html Use these task commands to run the main website, the PRQL online book, or the PRQL playground locally. ```bash # Run the main website task web:run-website # Run the PRQL online book task web:run-book # Run the PRQL playground task web:run-playground ``` -------------------------------- ### Compile PRQL queries with PRQL.compile Source: https://prql-lang.org/book/project/bindings/elixir.html Use the PRQL.compile function to convert PRQL strings into SQL. The first example compiles to default SQL, while the second specifies a target dialect. ```elixir iex> PRQL.compile("from customers", signature_comment: false) {:ok, "SELECT\n *\nFROM\n customers\n"} iex> PRQL.compile("from customers\ntake 10", target: :mssql, signature_comment: false) {:ok, "SELECT\n *\nFROM\n customers\nORDER BY\n (\n SELECT\n NULL\n ) OFFSET 0 ROWS\nFETCH FIRST\n 10 ROWS ONLY\n"} ``` -------------------------------- ### Define and use multiple utility functions Source: https://prql-lang.org/book/reference/declarations/functions.html Demonstrates defining several functions and using them in a pipeline. ```PRQL __ let is_adult = col -> col >= 18 let writes_code = col -> (col | in ["PRQL", "Rust"]) let square = col -> (col | math.pow 2) let starts_with_a = col -> (col | text.lower | text.starts_with("a")) from employees select { first_name, last_name, hobby, adult = is_adult age, age_squared = square age, } filter ((starts_with_a last_name) && (writes_code hobby)) ``` ```SQL __ WITH table_0 AS ( SELECT first_name, last_name, hobby, age >= 18 AS adult, POW(age, 2) AS age_squared FROM employees ) SELECT first_name, last_name, hobby, adult, age_squared FROM table_0 WHERE LOWER(last_name) LIKE CONCAT('a', '%') AND hobby IN ('PRQL', 'Rust') ``` -------------------------------- ### PRQL comment example Source: https://prql-lang.org/book/reference/syntax/comments.html Shows the use of '#' for comments in PRQL. The first comment follows the 'from employees' line, and the second comment is on its own line before the aggregate clause. ```prql from employees # Comment 1 # Comment 2 aggregate {average salary} ``` -------------------------------- ### SQL translation of reading multiple file formats with DuckDB functions Source: https://prql-lang.org/book/reference/data/read-files.html SQL generated by PRQL for the read_parquet, read_csv, and read_json example. Shows the WITH table_x AS SELECT * FROM ... boilerplate that may be reduced in future versions. ```SQL WITH table_0 AS ( SELECT * FROM read_parquet( 'artists.parquet', binary_as_string = false, file_row_number = false, hive_partitioning = NULL, union_by_name = false ) ), table_1 AS ( SELECT * FROM read_csv_auto('albums.csv') ), table_2 AS ( SELECT * FROM read_json_auto('metadata.json') ) SELECT table_0.*, table_1.*, table_2.* FROM table_0 INNER JOIN table_1 ON table_0.artist_id = table_1.artist_id INNER JOIN table_2 ON table_0.artist_id = table_2.artist_id ``` -------------------------------- ### Enable nix experimental features Source: https://prql-lang.org/book/project/bindings/php.html Commands to enable nix flakes by creating a nix.conf file with the experimental-features setting. ```bash mkdir -p ~/.config/nix echo "experimental-features = nix-command flakes" >> ~/.config/nix/nix.conf ``` -------------------------------- ### Wrapping a logical line with backslashes Source: https://prql-lang.org/book/reference/syntax/operators.html Demonstrates wrapping a select statement across multiple lines using the backslash operator at the start of each continuation line. ```prql __ from artists select is_europe = \ country == "DE" \ || country == "FR" \ || country == "ES" ``` ```sql __ SELECT country = 'DE' OR country = 'FR' OR country = 'ES' AS is_europe FROM artists ``` -------------------------------- ### Execute PRQL directly with the prql function Source: https://prql-lang.org/book/project/integrations/postgresql.html Runs PRQL code directly using the prql function, useful for custom SQL in ORMs. Includes examples with static types and cursor-based fetching. ```sql select prql('from matches | filter player == ''Player1''') as (id int, match_id int, round int, player text, kills int, deaths int) limit 2; id | match_id | round | player | kills | deaths ----+----------+-------+---------+-------+-------- 1 | 1001 | 1 | Player1 | 4 | 1 3 | 1001 | 2 | Player1 | 1 | 7 (2 rows) -- Same as above without the need for the static types, but returns cursor select prql('from matches | filter player == ''Player1''', 'player1_cursor'); fetch 2 from player1_cursor; ``` -------------------------------- ### from_text function with CSV format Source: https://prql-lang.org/book/project/changelog.html Example of using from_text with format:csv and a string argument containing CSV data. The argument is currently limited to string constants. ```prql from_text format:csv """ a,b,c 1,2,3 4,5,6 """ ``` -------------------------------- ### Calculate age squared using math.pow Source: https://prql-lang.org/book/reference/stdlib/math.html Example showing how to calculate the square of the age column using the math.pow function in PRQL and its corresponding SQL output. ```PRQL __ from employees select age_squared = (age | math.pow 2) ``` ```SQL __ SELECT POW(age, 2) AS age_squared FROM employees ``` -------------------------------- ### Read multiple file formats with read_parquet, read_csv, read_json in PRQL Source: https://prql-lang.org/book/reference/data/read-files.html PRQL example that reads three files (parquet, CSV, JSON) and joins them on artist_id. Uses DuckDB-specific functions. Note that these functions do not currently support all DuckDB options. ```PRQL prql target:sql.duckdb from a = (read_parquet "artists.parquet") join b = (read_csv "albums.csv") (a.artist_id == b.artist_id) join c = (read_json "metadata.json") (a.artist_id == c.artist_id) ``` -------------------------------- ### Test prqlc JavaScript bindings Source: https://prql-lang.org/book/project/bindings/javascript.html Run the test suite. ```bash npm test ``` -------------------------------- ### Load default Nix development shell Source: https://prql-lang.org/book/project/contributing/development.html Enters the default Nix development environment. ```bash nix develop ``` -------------------------------- ### from_text function with JSON array format Source: https://prql-lang.org/book/project/changelog.html Example of using from_text with format:json and a string argument containing a JSON array. The argument is currently limited to string constants. ```prql from_text format:json ''' [{"a": 1, "b": "x", "c": false }, {"a": 4, "b": "y", "c": null }] ''' ``` -------------------------------- ### text.starts_with Source: https://prql-lang.org/book/reference/stdlib/text.html Returns true if the column starts with the given substring. ```APIDOC ## text.starts_with ### Description Returns true if `col` starts with `sub`. ### Parameters - `sub` (string) - Required - The substring to check for at the start. - `col` (string) - Required - The column to check. ### Returns Boolean ``` -------------------------------- ### Reference module declarations Source: https://prql-lang.org/book/reference/spec/modules.html Demonstrates how to reference declarations from within a module from the outside. ```prql module my_playlists let great_tracks = my_playlists.bangers let movie_scores = my_playlists.soundtracks.movie_albums ``` -------------------------------- ### derive single column Source: https://prql-lang.org/book/reference/stdlib/transforms/derive.html Example of adding a single calculated column to a table. ```prql from employees derive gross_salary = salary + payroll_tax ``` ```sql SELECT *, salary + payroll_tax AS gross_salary FROM employees ``` -------------------------------- ### prqlc multi-file interface usage Source: https://prql-lang.org/book/reference/spec/modules.html Shows two ways to invoke prqlc compile with the multi-file interface. The first specifies the root module file and pipeline identifier; the second relies on automatic detection of the root module by searching for .prql files starting with _ in the current directory. ```bash $ prqlc compile _project.prql sales.projections.orders_2024 ``` ```bash $ prqlc compile sales.projections.orders_2024 ``` -------------------------------- ### Build with development profile Source: https://prql-lang.org/book/project/bindings/javascript.html Build with PROFILE=dev for faster, less optimized builds. ```bash PROFILE=dev npm run build ``` -------------------------------- ### Project module file (_project.prql) Source: https://prql-lang.org/book/reference/spec/modules.html Declares the top-level modules for a project: employees, sales, and util. ```prql # _project.prql module employees module sales module util ``` -------------------------------- ### PRQL parameter syntax Source: https://prql-lang.org/book/reference/syntax/parameters.html Example of using a positional parameter in a PRQL filter clause. ```prql __ from employees filter id == $1 ``` -------------------------------- ### SQL order non-guarantee Source: https://prql-lang.org/book/reference/stdlib/transforms/sort.html An example of an SQL query that does not guarantee row order after a join. ```sql WITH albums_sorted AS ( SELECT * FROM albums ORDER BY title ) SELECT * FROM albums_sorted JOIN artists USING (artist_id) ``` -------------------------------- ### Compile PRQL to SQL using PrqlCompiler Source: https://prql-lang.org/book/project/bindings/dotnet.html Demonstrates how to use the PrqlCompiler.Compile method with custom PrqlCompilerOptions to convert PRQL code into SQL. ```csharp using Prql.Compiler; var options = new PrqlCompilerOptions { Format = false, SignatureComment = false, }; var sql = PrqlCompiler.Compile("from employees", options); Console.WriteLine(sql); ``` -------------------------------- ### Get current timestamp with date.now Source: https://prql-lang.org/book/reference/stdlib/date.html Retrieves the current date and time as a timestamp for filtering. ```prql __ from test_tables filter test_time < date.now ``` ```sql __ SELECT * FROM test_tables WHERE test_time < CURRENT_TIMESTAMP ``` -------------------------------- ### Build and test PHP bindings Source: https://prql-lang.org/book/project/bindings/php.html Commands to build the PHP bindings and run tests using the task runner. ```bash task build-php task test-php ``` -------------------------------- ### PRQL select with column concatenation Source: https://prql-lang.org/book/reference/stdlib/transforms/select.html Example of selecting and renaming a column using string concatenation. ```prql from employees select name = f"{first_name} {last_name}" ``` ```sql SELECT CONCAT(first_name, ' ', last_name) AS name FROM employees ``` -------------------------------- ### Apply window function with group in PRQL Source: https://prql-lang.org/book/reference/stdlib/transforms/window.html Demonstrates using the group transform to partition window functions by department. ```prql from employees group department ( sort age derive {rnk = rank age} ) ``` -------------------------------- ### PRQL datetime cast example Source: https://prql-lang.org/book/reference/syntax/literals.html Shows a timestamp literal cast to a datetime type using . ```PRQL derive pi_day = @2017-03-14T15:09:26.535898 ``` -------------------------------- ### Function implementation with target and representation annotations Source: https://prql-lang.org/book/reference/spec/type-system.html Illustrates the made-up syntax for implementing a function for a specific target and parameter representations, using #[target(sql.sqlite)] and #[repr(int8)]. ```prql # using a made-up syntax #[target(sql.sqlite)] func std.int8.add #[repr(int8)] x #[repr(int8)] y -> s"{x} + {y}" ``` -------------------------------- ### Run full test suite Source: https://prql-lang.org/book/project/contributing/development.html Executes the full test suite to verify the environment, including Python dependencies. ```bash cargo test ``` -------------------------------- ### Load specific Nix development shell Source: https://prql-lang.org/book/project/contributing/development.html Enters the web-specific Nix development environment. ```bash nix develop .#web ``` -------------------------------- ### Basic from usage Source: https://prql-lang.org/book/reference/data/from.html Specifies the source table for a query. ```PRQL __ from artists ``` ```SQL __ SELECT * FROM artists ``` -------------------------------- ### SQL: Translation of corrected parentheses example Source: https://prql-lang.org/book/reference/syntax/operators.html Equivalent SQL generated from the corrected PRQL snippet, showing the SUM(distance) OVER () expression. ```SQL __ SELECT *, SUM(distance) OVER () AS other_distance FROM employees ``` -------------------------------- ### SQL equivalent for aggregate without group Source: https://prql-lang.org/book/reference/stdlib/transforms/aggregate.html The SQL translation of the PRQL aggregate example, using AVG and COUNT with a GROUP BY clause. ```SQL SELECT AVG(salary), COUNT(*) AS ct FROM employees ``` -------------------------------- ### Create GitHub release via CLI Source: https://prql-lang.org/book/project/contributing/development.html Command to create a GitHub release with the specified version and changelog notes. The notes are provided via a here-document. ```bash __ gh release create $version --title "$version" --notes "$(cat <<'EOF' EOF )" ``` -------------------------------- ### Function declaration syntax Source: https://prql-lang.org/book/project/changelog.html Shows the updated syntax for declaring functions using the let keyword, replacing the previous func keyword. ```PRQL let add = a b -> a + b ``` -------------------------------- ### Spawn nix shell for PHP dev environment Source: https://prql-lang.org/book/project/bindings/php.html Command to enter a nix shell with PHP 8.1 and ext-ffi, as declared in composer.json. ```bash nix shell github:loophp/nix-shell#env-php81 --impure ``` -------------------------------- ### Partially apply functions Source: https://prql-lang.org/book/reference/declarations/functions.html Creating a reusable transform wrapper using partial application. ```PRQL __ let top_n = n -> take n from invoices top_n 10 ``` ```SQL __ SELECT * FROM invoices LIMIT 10 ``` -------------------------------- ### Run and accept prqlc snapshot tests Source: https://prql-lang.org/book/project/contributing/development.html Runs the tests and automatically updates the test snapshots. ```bash cargo insta test --accept --package prqlc --lib ``` -------------------------------- ### Bundler usage Source: https://prql-lang.org/book/project/bindings/javascript.html Use prqlc with a bundler by importing from prqlc/dist/bundler. ```javascript import compile from "prqlc/dist/bundler"; const sql = compile(`from employees | select first_name`); console.log(sql); ``` -------------------------------- ### PRQL query with Jinja template syntax Source: https://prql-lang.org/book/project/changelog.html An example of a PRQL query containing Jinja-style double curly braces, which no longer passes through to the output in version 0.6.0. ```text from {{foo}} ``` -------------------------------- ### PRQL text module usage Source: https://prql-lang.org/book/reference/stdlib/text.html Demonstrates using text.lower, text.starts_with, and text.replace functions within a PRQL select statement. ```prql __ from employees select { (last_name | text.lower | text.starts_with("a")), (title | text.replace "manager" "chief"), } ``` -------------------------------- ### Basic function call syntax Source: https://prql-lang.org/book/reference/syntax/function-calls.html The standard way to call a function in PRQL is by placing the function name followed by its arguments separated by whitespace. ```prql function_name arg1 arg2 arg3 ``` -------------------------------- ### Inferred column names include relation name Source: https://prql-lang.org/book/project/changelog.html Example showing that inferred column names include the relation name, allowing the use of albums.title in the select clause. ```prql from albums select title # name used to be inferred as title only select albums.title # so using albums was not possible here ``` -------------------------------- ### SQL translation of specifying file name directly in FROM clause Source: https://prql-lang.org/book/reference/data/read-files.html SQL generated by PRQL for the direct file name example. The file name is quoted with double quotes. ```SQL SELECT * FROM "artists.parquet" ``` -------------------------------- ### Compile with options (target, format, signature_comment) Source: https://prql-lang.org/book/project/bindings/javascript.html Compile a PRQL query with custom options: target sql.mssql, format false, signature_comment false. ```javascript const opts = new prqlc.CompileOptions(); opts.target = "sql.mssql"; opts.format = false; opts.signature_comment = false; const sql = prqlc.compile(`from employees | take 10`, opts); console.log(sql); ``` -------------------------------- ### PRQL take syntax Source: https://prql-lang.org/book/reference/stdlib/transforms/take.html The basic syntax for the take transform using an integer or a range. ```prql take (n|range) ``` -------------------------------- ### Centered and expanding windows in PRQL Source: https://prql-lang.org/book/reference/stdlib/transforms/window.html Demonstrates a centered weekly average using rows and an expanding running total using a group. ```prql from orders sort day window rows:-3..3 ( derive {centered_weekly_average = average value} ) group {order_month} ( sort day window expanding:true ( derive {monthly_running_total = sum value} ) ) ``` -------------------------------- ### Sales module file (sales/_sales.prql) Source: https://prql-lang.org/book/reference/spec/modules.html Declares submodules orders and projections, and defines revenue_by_source within the sales module. ```prql # sales/_sales.prql module orders module projections let revenue_by_source = (...) ``` -------------------------------- ### Escape braces in s-string with double braces Source: https://prql-lang.org/book/reference/syntax/s-strings.html To output literal braces in an s-string, use double braces. This example uses a regex with escaped braces to check a title pattern. ```PRQL from employees derive { has_valid_title = s"regexp_contains(title, '([a-z0-9]*-){{2,}}')" } ``` ```SQL SELECT *, regexp_contains(title, '([a-z0-9]*-){2,}') AS has_valid_title FROM employees ``` -------------------------------- ### Utility module file (util.prql) Source: https://prql-lang.org/book/reference/spec/modules.html Defines a pretty_print_num function that takes a column. ```prql # util.prql let pretty_print_num = col -> (...) ``` -------------------------------- ### Import a module with the module statement Source: https://prql-lang.org/book/reference/spec/modules.html Use the module statement to import a PRQL file. It loads either ./my_playlists.prql (leaf module) or ./my_playlists/_my_playlists.prql (directory module). If none or both files exist, a compilation error is raised. ```prql __ module my_playlists ``` -------------------------------- ### Rows vs Range window comparison in SQL Source: https://prql-lang.org/book/reference/stdlib/transforms/window.html The SQL equivalent demonstrating the difference between ROWS and RANGE window frames. ```sql WITH table_0 AS ( SELECT 1 AS time_id, 15 AS value UNION ALL SELECT 2 AS time_id, 11 AS value UNION ALL SELECT 3 AS time_id, 16 AS value UNION ALL SELECT 4 AS time_id, 9 AS value UNION ALL SELECT 7 AS time_id, 20 AS value UNION ALL SELECT 8 AS time_id, 22 AS value ) SELECT time_id, value, AVG(value) OVER ( ORDER BY time_id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) AS sma3rows, AVG(value) OVER ( ORDER BY time_id RANGE BETWEEN 2 PRECEDING AND CURRENT ROW ) AS sma3range FROM table_0 ORDER BY time_id ``` -------------------------------- ### Basic PRQL case statement Source: https://prql-lang.org/book/reference/syntax/case.html Demonstrates a basic case statement in PRQL and its equivalent SQL translation. ```prql from employees derive distance = case [ city == "Calgary" => 0, city == "Edmonton" => 300, ] ``` ```sql SELECT *, CASE WHEN city = 'Calgary' THEN 0 WHEN city = 'Edmonton' THEN 300 ELSE NULL END AS distance FROM employees ``` -------------------------------- ### from_text function with JSON object format Source: https://prql-lang.org/book/project/changelog.html Example of using from_text with format:json and a string argument containing a JSON object with columns and data. The argument is currently limited to string constants. ```prql from_text format:json '''{ "columns": ["a", "b", "c"], "data": [ [1, "x", false], [4, "y", null] ] }''' ``` -------------------------------- ### Compose multiple partial applications Source: https://prql-lang.org/book/reference/declarations/functions.html Combining multiple partially applied functions into a pipeline. ```PRQL __ let top_n = n -> take n let add_constant = x -> derive {constant = x} let my_pipeline = (top_n 5 | add_constant 42) from invoices my_pipeline ``` ```SQL __ SELECT *, 42 AS constant FROM invoices LIMIT 5 ``` -------------------------------- ### Apply window function to whole table in PRQL Source: https://prql-lang.org/book/reference/stdlib/transforms/window.html Demonstrates applying a rank function to the entire table without a window transform. ```prql from employees sort age derive {rnk = rank age} ``` -------------------------------- ### Define string literals in PRQL and SQL Source: https://prql-lang.org/book/reference/syntax/strings.html Demonstrates defining single, double, and triple-quoted strings in PRQL and their corresponding SQL output. ```PRQL __ from artists derive { single = 'hello world', double = "hello world", double_triple = """hello world""", } ``` ```SQL __ SELECT *, 'hello world' AS single, 'hello world' AS double, 'hello world' AS double_triple FROM artists ``` -------------------------------- ### Basic filter syntax Source: https://prql-lang.org/book/reference/stdlib/transforms/filter.html The fundamental syntax for the filter transform. ```prql filter boolean_expression ```