# Query

**Queries** allow you write SQL queries to retrieve data from your data sources or modify your databases in queries.&#x20;

**Queries** must be created from **Tables** and are only available in the current app. However, you can have multiple queries for the same tables.&#x20;

All elements across pages can interact with **Queries** through interactions, including trigger **Run Query** or **Set SQL Parameters**.

<div align="left"><figure><img src="https://3574406564-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MB_fx7PCUqvFEdrucJC%2Fuploads%2FkRQAtKzkZF64kO2MoUmm%2Fimage.png?alt=media&#x26;token=e2ddda0a-c187-4b3d-b11a-423439149bd4" alt="" width="375"><figcaption></figcaption></figure></div>

## Set up a query

**Queries** must be created from **Tables** and are only available in the current app. There are two methods to instantiate a query:

* **From Tables**
  1. Navigate to the desired table.
  2. Click on the More option <img src="https://3574406564-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MB_fx7PCUqvFEdrucJC%2Fuploads%2FT8pYS2JcwaTZHq4FZWkK%2Fimage.png?alt=media&#x26;token=41b8d171-1982-4643-ab77-399607d50eb5" alt="" data-size="line">
  3. Select **Create Query** .\
     ![](https://3574406564-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MB_fx7PCUqvFEdrucJC%2Fuploads%2FsSzRAgyyocZb9F0jkElP%2Fimage.png?alt=media\&token=846217d0-368d-4e1b-b1f8-a88c646e432b)
* **Adding from Query Tab**
  1. Go to the Query tab.&#x20;
  2. Click on <img src="https://3574406564-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MB_fx7PCUqvFEdrucJC%2Fuploads%2FonwEffXiKNU2P601Od4D%2Fimage.png?alt=media&#x26;token=9d550d6a-fdd9-4875-8f01-a8d111d7b7fc" alt="" data-size="line">**Add Query**.&#x20;
  3. Choose the table from which you wish to create the query.\
     ![](https://3574406564-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MB_fx7PCUqvFEdrucJC%2Fuploads%2FpvtgYWUe2KVKh8oZQAdO%2Fimage.png?alt=media\&token=10a57b3d-b119-4885-bb13-47151e48ca05)

### Edit Queries

After creating the queries, double click on it to edit.

<figure><img src="https://3574406564-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MB_fx7PCUqvFEdrucJC%2Fuploads%2FmFIzzCHO3lRHXPU5uA2Y%2FScreen%20Shot%202023-05-25%20at%207.47.01%20PM.png?alt=media&#x26;token=760ba0d7-4aa6-4e0a-a517-4669f2c0f8e9" alt=""><figcaption><p>Editing query</p></figcaption></figure>

1. **Queries Name:** In app name of your query
2. **Database Name:** Represents the database you are currently querying against.
3. **Data Directory:** Displays all the available tables across different databases within the same database type, including Acho-hosted and self-hosted databases. For example, in the PostgreSQL query, you can find all the available PostgreSQL databases, but it doesn't include other types of databases (such as MySQL). Also, you cannot query against tables across different PostgreSQL databases simultaneously.
4. **Query Pane:** The pane allows you to write queries. It supports writing a single query at a time. Currently, it doesn't support writing functions or procedures. Macro is supported to help you do complex operation [#macros](#macros "mention")
5. **Generate by AI:** Click on this button to access the AI panel, which leverages generative AI  to assist you in writing SQL queries. You can streamline the query creation process using natural language prompts.&#x20;
6. **Run:** Run the query in the Query Pane and display the query results in the above Table Preview. Note that it's only to run the query but won't save it and its results.
7. **Save:** Run the query and save all the changes (including the query, query results, and parameters).
8. **Parameter Pane:** This pane allows you to create parameters and their initial values. These parameters are dynamic and can be used in the Query Pane. See [here](https://app.gitbook.com/o/-MB_gcnULb42rxiDPWhi/s/-MB_fx7PCUqvFEdrucJC/~/revisions/4JlQ5nOGoRpO9W7fJVeb/build-your-apps/data-sources/data-nodes#set-up-parameters) to learn more about how to set up parameters.
9. **Table Preview:** When you run a query, the results will be presented in the Table Preview. Use the pagination below to switch page.

## How do queries work?

Each queries functions like a script, storing an SQL query. When triggered by other elements, the query node fetch information including database address from table node, then run the query, either retrieving data or modifying the database. If the query returns data, the data is stored in Acho's in-memory database, serving as a cache layer for your app. However if your statement is DML (UPDATE, INSERT, DELETE) or DDL(CREATE, DROP), no data will be stored in the query.

## Queries Syntax

The syntax of a queries is determined by the data source they connected

1. **Acho resource and Data Prep Projects**:  Acho resource and Data Prep Projects are replicated and stored in an Acho-hosted data warehouse. For query nodes connected to resources and the Data Prep Project, use BigQuery syntax. See which [statements](https://docs.acho.io/acho-studio/data-prep-projects/applying-actions/tools/sql-editor/supported-sql-queries) and [functions](https://docs.acho.io/acho-studio/data-prep-projects/applying-actions/tools/sql-editor/supported-math-functions-in-formula) you can use.<br>

   At present, it's recommended to use only SELECT queries in such queries. Any data modifications made using DML (UPDATE, INSERT, DELETE) or DDL (CREATE, DROP) may be overwritten when the data source is synced, resulting in the loss of those changes.<br>
2. **Direct Connector**: Query against your database directly. It allows you to query all data stored in your database and supports DQL (SELECT), DML (UPDATE, INSERT, DELETE) or DDL(CREATE, DROP). Different databases have their own SQL dialects and syntax. Currently, we support the following databases for direct access:\
   \- PostgreSQL\
   \- MySQL\
   \- Snowflake\
   \- MongoDB&#x20;

## Set SQL Parameters

Parameters are used for creating dynamic queries. They are like variables that can store any value and be inserted into queries. Their values can be changed via event actions **Set SQL Parameters.** See detailed example in [create-a-filter](https://docs.acho.io/app-builder/popular-use-cases/create-a-filter "mention").

#### **1. Add new parameter**

Click the plus icon at the **Parameter Panel to** add new parameter. You need to specify name and datatype and Default value(optional but recommended).

![](https://3574406564-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MB_fx7PCUqvFEdrucJC%2Fuploads%2FNirPBUREIePlCjDWvjru%2FScreen%20Shot%202023-05-26%20at%2011.32.30%20PM.png?alt=media\&token=ccd977b5-29d7-4f7f-8cb2-f4775b16fe8b)

#### **2. Insert parameters in SQL query**

All parameters can be inserted anywhere in the query. The parameter replaces `{{parameter_name}}` with the value specified in the parameter.

Here are some examples:

Pass a string: (need quotes to represent it as string) &#x20;

```
SELECT *
FROM customers
WHERE customer_id = '{{customer_id}}'
```

Pass an integer or a number: (doesn't require quotes)

```
SELECT *
FROM customers
WHERE age = {{customer_id}}
```

Pass a column name: (doesn't require quotes)

```
SELECT {{category}}, COUNT(DISTINCT customer_id) AS n_customers
FROM customers
GROUP BY {{category}}
```

#### **3. Deal with arrays or objects**

If your parameter is an array, you have to use "macro" to turn the array or object into a format that the database can ingest.

Use an array to specify values in the IN statement

Suppose you have a parameter called `categories`. It's an array and contains three values.

```sql
{
categories: ["New", "Repeat", "Royal"]
}
```

Now, we want to create a query to filter the `customer` table and get all the customers in these three categories via the `IN` statement as shown below.

```sql
SELECT *
FROM customers
WHERE category IN ("New", "Repeat", "Royal")
```

However, the array cannot be passed to the query directly since the query doesn't need the square brackets. In this situation, we need to use "[macro](#macros)" to do some transformation to the array parameter. [Macro](#macros) is a templating language that can help you generate queries. It supports various functionalities, such as for loop, or conditional statement (if and else). In this example, we want to use the for loop to pass all the values in the array one by one and use `joiner()` the function in macro to concatenate all the values with a comma.

```sql
{% set comma = joiner() %}
SELECT *
FROM customers
WHERE category IN ( {% for category in categories} {{comma}} '{{category}}' {% endfor %})
```

You can also use an array to select multiple columns. Suppose you have a parameter called `columns`, which you can dynamically set by [**Set SQL parameters**](#set-sql-parameters).  By default, `columns` is an array that contains four column names.

```sql
{
categories: [
    "first_name",
    "last_name",
    "type",
    "last_login"
    ]
}
```

```sql
SELECT {{ columns|join(',') }}
FROM customers
```

## Macros

Macro is a templating language that enhances queries to make them dynamic. It supports various functionalities, including for loops and conditional statements (if and else).

See available macros template at <https://mozilla.github.io/nunjucks/templating.html>

## Accessor

To access a query elsewhere in the app, use `${#query_name}`. See details in  [accessors](https://docs.acho.io/app-builder/app-construction/accessors "mention")

{% hint style="info" %}
You may need to rename your query to valid variable name to use it in accessor
{% endhint %}

<div align="left"><figure><img src="https://3574406564-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MB_fx7PCUqvFEdrucJC%2Fuploads%2F9BRggBWAod400h5dCBac%2Fimage%20(43).png?alt=media&#x26;token=b8efeaf7-96cd-4150-b609-2b90f51a8d19" alt=""><figcaption><p>A text accessing the query  'car_datebase'</p></figcaption></figure></div>

## Supported Events

![](https://3574406564-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MB_fx7PCUqvFEdrucJC%2Fuploads%2FwkkVAWjgNF6KXQtdsosw%2Fimage.png?alt=media\&token=38f94328-6c39-47ba-8df1-20bd173f2d2f)

**Data Update:** Triggered when the query runs.

**Data Update Error:** Triggered when errors occur as the query runs.
