Skip to main content

Read data from SQL databases

Learn how to construct queries to retrieve data from SQL databases and similar data stores.

You can create queries that use SQL statements to retrieve (read) data from connected database resources, such as a PostgreSQL or a MySQL database.

1. Add a query

  1. Navigate to the Code tab in the IDE.
  2. Click + to add a new query.
  3. Select the resource.

There are two modes from which to select when writing an SQL query. The mode you choose depends on whether you need to read or write data:

  • SQL: Read data using an SQL statement.
  • GUI: Write data using a graphical query editor.

Select SQL mode.

2. Write an SQL statement to retrieve data

Create AI-generated SQL queries

You can also use the Ask AI option to generate SQL queries.

Write an SQL statement to retrieve data from the database. The following example retrieves the id, name, subscription, and expiration values for all records in the sample_users table of a database.

getUsers
SELECT 
id,
name,
subscription,
expiration
FROM
sample_users

You use {{ }} embedded expressions to reference other values within the SQL statement, such as components and queries.

The following example adds a WHERE clause to retrieve only records with an expiration date prior to a Date Input component value.

getUsers
SELECT 
id,
name,
subscription,
expiration
FROM
sample_users
WHERE
expiration < {{ date1.value }}
Prepared statements

To prevent SQL injection, Retool converts SQL queries into prepared statements that separate the query from values. This prevents you from writing queries that dynamically reference column or table names.

3. Run the query

Click Save & Run to save the query and then execute it. The query results then appear in the Output tab.

You can reference the query output elsewhere in the app using the query's data property. This contains an object with key names that correspond to the column names. Each key contains an array of values.