> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nativeline.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# SQL Editor

> Write and execute SQL queries directly against your database

import { Card, CardGroup, Steps, Tip, Warning, Note } from "mintlify/components";

**Pro plan required.**

The SQL Editor lets you write raw SQL queries when you need precise control over your database. It's the power tool for situations where the visual browser isn't enough.

## When to Use the SQL Editor

Most of the time, you can manage your database through the AI chat or the Data Browser. The SQL Editor is for when you need something more specific:

| Use Case             | Example                                                            |
| -------------------- | ------------------------------------------------------------------ |
| **Complex queries**  | Joins, subqueries, aggregations the AI can't generate through chat |
| **Bulk operations**  | INSERT, UPDATE, or DELETE across many rows at once                 |
| **Custom analytics** | Ad-hoc reports and data exploration                                |
| **Debugging**        | Investigate data issues with targeted queries                      |
| **Testing queries**  | Try out SQL before incorporating it into your app logic            |

## How to Use

<Steps>
  <Step title="Open the Database tab">
    Click the **Database** tab in your workspace.
  </Step>

  <Step title="Navigate to the SQL Editor">
    Switch to the **SQL Editor** view within the Database tab.
  </Step>

  <Step title="Write your SQL query">
    Type your query in the editor. You get syntax highlighting and standard
    editing features to help you write correct SQL.
  </Step>

  <Step title="Execute and view results">
    Run your query and see the results displayed below the editor. SELECT queries
    return a results table. Other statements show affected row counts or error
    messages.
  </Step>
</Steps>

## Example Queries

Here are some practical queries to get you started.

### Count users by signup month

```sql theme={null}
SELECT
  date_trunc('month', created_at) AS month,
  COUNT(*)
FROM users
GROUP BY month
ORDER BY month;
```

### Find posts without comments

```sql theme={null}
SELECT p.*
FROM posts p
LEFT JOIN comments c ON p.id = c.post_id
WHERE c.id IS NULL;
```

### Get the most active users

```sql theme={null}
SELECT
  u.name,
  COUNT(p.id) AS post_count
FROM users u
JOIN posts p ON u.id = p.author_id
GROUP BY u.id, u.name
ORDER BY post_count DESC
LIMIT 10;
```

### Check for duplicate emails

```sql theme={null}
SELECT email, COUNT(*)
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
```

### View RLS policies on a table

```sql theme={null}
SELECT *
FROM pg_policies
WHERE tablename = 'posts';
```

### Insert sample data

```sql theme={null}
INSERT INTO posts (title, body, author_id)
VALUES
  ('First Post', 'Hello world!', '550e8400-e29b-41d4-a716-446655440000'),
  ('Second Post', 'Another entry.', '550e8400-e29b-41d4-a716-446655440000');
```

<Warning>
  SQL operations execute directly against your live database. Be careful with
  UPDATE and DELETE queries — there's no undo.
</Warning>

## Tips for Safe SQL

Writing queries against a live database requires some caution. Here are practices that will save you from mistakes:

<Tip>
  Use SELECT queries first to verify your WHERE clause before running UPDATE or
  DELETE.
</Tip>

For example, before running this:

```sql theme={null}
-- DON'T run this first
DELETE FROM posts WHERE status = 'draft';
```

Run this to see what would be deleted:

```sql theme={null}
-- Run this first to verify
SELECT * FROM posts WHERE status = 'draft';
```

Once you've confirmed the results look right, run the DELETE.

### Other Safety Practices

* **Start with SELECT** — Always preview what your query will affect
* **Use LIMIT** — Add `LIMIT 10` to exploratory queries so you don't pull back thousands of rows
* **Be specific with WHERE** — Broad WHERE clauses (or missing ones) can affect more rows than you expect
* **Use transactions** — Wrap multi-step operations in `BEGIN` and `COMMIT` so you can `ROLLBACK` if something goes wrong

### Using Transactions for Multi-Step Operations

When you need to make several related changes at once, wrap them in a transaction:

```sql theme={null}
BEGIN;

-- Add a new column
ALTER TABLE posts ADD COLUMN slug text;

-- Populate it from existing data
UPDATE posts SET slug = lower(replace(title, ' ', '-'));

-- Add a unique constraint
ALTER TABLE posts ADD CONSTRAINT unique_slug UNIQUE (slug);

COMMIT;
```

If any step fails, you can run `ROLLBACK` instead of `COMMIT` and none of the changes will be applied. This keeps your database consistent.

<Note>
  The SQL Editor is a great companion to the AI chat. If the AI generates a query
  you want to tweak, copy it into the SQL Editor to modify and test it yourself.
</Note>

## SQL Editor vs. AI Chat

Both can execute SQL, but they serve different purposes:

| SQL Editor                         | AI Chat                                    |
| ---------------------------------- | ------------------------------------------ |
| You write the SQL yourself         | AI generates SQL from your description     |
| Full control over every detail     | Faster for common operations               |
| Best for debugging and exploration | Best for creating tables, migrations, CRUD |
| Results displayed in a table       | Results described in conversation          |

Use the AI chat when you know *what* you want but don't want to write the SQL. Use the SQL Editor when you need precise control over *how* the query works.

## Related

<CardGroup cols={2}>
  <Card title="Database Overview" icon="database" href="/features/database-overview">
    Learn about all the database management tools available in Nativeline.
  </Card>

  <Card title="Migrations" icon="code-branch" href="/features/database-migrations">
    Track versioned schema changes to your database.
  </Card>
</CardGroup>
