# Database Steps

{% hint style="info" %}
**Who is this for?** SDETs and testers who need to verify backend data directly by running SQL queries during test execution.
{% endhint %}

Database steps let you execute SQL queries against a configured database environment and verify the results — all within a test case. Use them to confirm that a UI action actually wrote the correct data, to set up preconditions by checking existing records, or to validate data transformations that are not visible in the UI.

## Prerequisites

* You have created or opened a test case.
* A **database environment** is configured in **Settings -> Environments** with `type: Database` and valid connection credentials.
* You are familiar with the [Test Steps Editor](https://learning.contextqa.com/web-testing/test-steps-editor) basics.

***

## Adding a database step

1. Open a test case and click **Add Step**.
2. In the step builder sidebar, select **Database**.
3. Configure the fields described below.
4. Click **Create Step** to add the step to your test case.

***

## Fields

| Field                    | Required | Description                                                                                                                                   |
| ------------------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| **Database Environment** | Yes      | Select the database environment to connect to. Only environments configured with `type: Database` appear in this dropdown.                    |
| **Normal Environment**   | No       | Select a standard environment for variable resolution. Use this when your queries reference environment variables like `${ENV.TABLE_PREFIX}`. |
| **Queries**              | Yes      | One or more SQL queries to execute. Each query has its own variable name and optional assertions.                                             |

### Query configuration

Each query row contains:

| Field             | Description                                                                                                       |
| ----------------- | ----------------------------------------------------------------------------------------------------------------- |
| **Query**         | The SQL statement to execute. Supports variable substitution: `SELECT * FROM users WHERE email = '${userEmail}'`. |
| **Variable Name** | The variable that stores the query result. Reference it in later steps with `${variableName}`.                    |
| **Assertions**    | Optional verification rules applied to the query result (see below).                                              |

### Assertions

Each query can have one or more assertions to verify the returned data:

| Field                 | Description                                                                                       |
| --------------------- | ------------------------------------------------------------------------------------------------- |
| **JSON Path**         | Path to the value in the result set to verify (e.g., `$.rows[0].status`).                         |
| **Verification Type** | The comparison operator. Default: `equals`.                                                       |
| **Expected Type**     | The data type of the expected value: `string`, `number`, `boolean`, `null`, `object`, or `array`. |
| **Expected Value**    | The value to compare against.                                                                     |

***

## Running a query preview

Before saving the step, you can test your query directly in the step builder:

1. Enter your SQL query and select the **Database Environment**.
2. Click the **Run Query** button.
3. The query executes against the selected database, and the results display below the query field.

Use this to verify your query syntax and confirm the data you expect is present before adding assertions.

***

## Example: Verify a user was created

```
Step 1 (AI Agent): Navigate to the registration page
Step 2 (AI Agent): Fill in the registration form with test data
Step 3 (AI Agent): Click the Submit button
Step 4 (AI Verification): Verify the success message is displayed

Step 5 (Database):
  Database Environment: QA Database
  Query: SELECT email, status FROM users WHERE email = '${testEmail}'
  Variable: newUser
  Assertion: $.rows[0].status equals string "active"
```

After execution, reference the stored result in later steps:

* `${newUser.rows[0].email}` — the email value from the first row
* `${newUser.rows[0].status}` — the status value from the first row

***

## Example: Validate data after an API call

```
Step 1 (REST API): POST ${ENV.BASE_URL}/api/orders
  Body: { "product": "Widget A", "quantity": 3 }
  Store response in: orderResponse

Step 2 (Database):
  Database Environment: QA Database
  Query: SELECT quantity, total_price FROM orders WHERE id = '${orderResponse.body.orderId}'
  Variable: orderRecord
  Assertion 1: $.rows[0].quantity equals number 3
  Assertion 2: $.rows[0].total_price equals number 29.97
```

***

## Advanced settings

| Setting              | Description                                                             |
| -------------------- | ----------------------------------------------------------------------- |
| **Skip Step**        | Skip this step during execution without removing it from the test case. |
| **Mark as Optional** | If enabled, a failure on this step does not fail the overall test case. |

***

## Tips & best practices

* **Use environment variables in queries** to keep test cases portable across environments. Reference `${ENV.DB_SCHEMA}` or `${ENV.TABLE_PREFIX}` instead of hardcoding schema names.
* **Add a wait step before database verification** if the data is written asynchronously. The UI action may return before the database commit completes.
* **Use the Run Query preview** to validate your SQL syntax before saving the step. This prevents execution failures caused by typos in column or table names.
* **Keep queries read-only.** While the step executes arbitrary SQL, avoid INSERT, UPDATE, or DELETE statements in verification steps. Use REST API steps for data setup and teardown.
* **Combine with assertions** to make database steps true verification steps. A query without assertions only stores data — it never fails on its own.

## Troubleshooting

**The Database Environment dropdown is empty** No environments with `type: Database` are configured. Go to **Settings -> Environments**, create a new environment, and set its type to **Database** with valid connection credentials (host, port, database name, username, password).

**Query fails with a connection error** Verify the database credentials in the environment configuration. Ensure the database server is accessible from the ContextQA execution network. If running behind a firewall, confirm that the execution agent has network access to the database host and port.

**Assertions pass but the data looks wrong** Check the JSON path syntax. Query results are returned as a JSON object — use `$.rows[0].columnName` to access the first row. Use the **Run Query** preview to inspect the exact result structure before writing assertions.

## Related pages

* [Test Steps Editor](https://learning.contextqa.com/web-testing/test-steps-editor)
* [Environments](https://learning.contextqa.com/execution/environments)
* [Test Data Management](https://learning.contextqa.com/web-testing/test-data-management)
* [Creating Test Cases](https://learning.contextqa.com/web-testing/creating-test-cases)

{% hint style="info" %}
**70% less manual test maintenance with AI self-healing.** [**Book a Demo →**](https://contextqa.com/book-a-demo/) — See ContextQA create and maintain tests for your web application.
{% endhint %}
