Select Query
Example 1: Select Data
In this example, we'll use the MySQL Execute function with the Type set to Select
to get data from MySQL.
Add MySQL Execute Function
Start by adding the MySQL Execute function. Give it a Result Name and set the Type to Select
.
Write the SQL Query
In the function configuration, write the SQL query you want to use to fetch data.
Assume we have a users
table and want to retrieve x
number of records. The users
table schema looks like this:
Now write the following query:
Fill the Arguments
Now provide the required arguments for the query. Since we're using LIMIT ?
, we need to supply how many records to fetch. For example, if you want to retrieve 5 users:
Define a Model for Returned Values
Next, we define a model (struct) that maps the returned SQL data to a usable object in the function.
We recommend defining models in reusable custom functions. This allows you to update a model in one place and automatically reflect changes across all references.
For simplicity, we’ll define the model inline in this example.
In the Model input:
- Click Define to create a new struct.
- Set a name, e.g.,
User
. - Add your fields. These can include more than what's returned from the query, but must at least match the selected columns.
Map Struct Fields to SQL Query
After defining your model, you need to map the fields to the selected SQL columns using the Field Mapper input.
The order here must match the order of columns in your SQL query:
Finally, set the Expected Result Set to 5
to allocate a list with enough space to store the results efficiently.
Use the Returned Result
The result is returned as either Res<SqlRes>
or directly SqlRes
if unwrapped.
It contains a Data
field, which is a list of rows returned from the database.
To access a specific field, like the ID of the first user, use dot syntax:
To easily select nested fields, use the UI helper:
- Click the Select button next to the
selectRes1
variable. - Click the
Data
field, then manually enter an index (e.g.0
) in the input box. - Click the field name (e.g.
Id
) from the list that appears.
You can insert !
symbol at end to force unwrap the result and access the value directly, without handling the Result
wrapper.
Example 2: Select one field
In this example, sometimes we only return one column from a SELECT
statement, so we can use a primitive type directly without creating a custom struct type.
Write the SQL Query
Assume we want only the id
of all users in the users
table. Write the following query:
Map Struct Fields to SQL Query
Because we only selected one field from the database, we don't need to map fields. Just provide an empty List[string]
value.