Introduction

In some cases, we want to retrieve data based on some dynamic input. This allows for more flexibility in the data we retrieve and how we display it.

This can be done with the help of parameters, which are passed to the SQL query when it is executed.

Parameters

The parameters are values that are passed to the SQL query when it is executed, either through View components, API requests, or using the CLI. To know more information about how parameters are used in each case, please refer to their own documentation.

In the query, the parameters can be used with the param() function. This function retrieves the value specified by the user and inserts it safely into the query.

SELECT *
FROM companies
WHERE id = {param('company_id')}

Fallback

If the required parameter is not found in the request, the query will fail. To avoid this, you can set a fallback value in the param() function.

SELECT *
FROM companies
WHERE id = {param('company_id', 'Latitude')}
/* If no company_id is found, it will use 'Latitude' as the value */

Check if a parameter is present

Requesting for a parameter that is not present will result in an error. To avoid this, you can check if the parameter is present using a conditional statement and false as the fallback value.

SELECT * 
FROM users
{#if param('user_id', false)}
  /* The parameter is present in the request */
  WHERE id = {param('user_id')}
{/if}