# Writing SQL queries and migrations

Almost every app stores data in a **relational database** such as MySQL, MariaDB, PostgreSQL or SQLite. You interact with it using **SQL**. In Laravel, you usually write Eloquent code, but this is converted to SQL behind the scenes. If you understand SQL, you’ll also understand why something is slow or incorrect.

## The basics

```sql
SELECT id, naam, email
FROM klanten
WHERE plaats = 'Groningen'
ORDER BY naam
LIMIT 20;
```

- `SELECT`: which columns
- `FROM`: which table
- `WHERE`: which rows
- `ORDER BY`: sorting
- `LIMIT`: how many

## Combining tables using JOIN

```sql
SELECT k.naam, f.nummer, f.bedrag
FROM facturen f
INNER JOIN klanten k ON k.id = f.klant_id
WHERE f.betaald = 0;
```

| JOIN | Displays |
|---|---|
| `INNER JOIN` | Only rows that match in both tables |
| `LEFT JOIN` | All rows on the left, even if there is no match (the right-hand side becomes `NULL`) |
| `RIGHT JOIN` | The other way round |
| `FULL OUTER JOIN` | Everything from both sides (not in MySQL) |

## Counting and grouping

```sql
SELECT klant_id, COUNT(*) AS aantal, SUM(bedrag) AS totaal
FROM facturen
GROUP BY klant_id
HAVING SUM(bedrag) > 1000;
```

`WHERE` filters rows before grouping, `HAVING` filters the groups afterwards.

## Indexes: why a query is slow

An **index** works like the index at the back of a book. Without an index, the database reads the entire table. Create an index on columns that you frequently search, filter or join by (`klant_id`, `email`, `created_at`).

See how the database executes a query:

```sql
EXPLAIN SELECT * FROM facturen WHERE klant_id = 42;
```

Do you see the word `type``ALL` in MySQL? If so, the entire table is being read and there is probably no index.

## Migrations in Laravel

A **migration** is a file that describes how your database changes. This ensures that everyone (and the live server) has exactly the same structure.

```bash
php artisan make:migration create_facturen_table
```

```php
Schema::create('facturen', function (Blueprint $table) {
    $table->id();
    $table->foreignId('klant_id')->constrained()->cascadeOnDelete();
    $table->string('nummer')->unique();
    $table->decimal('bedrag', 10, 2);
    $table->boolean('betaald')->default(false)->index();
    $table->timestamps();
});
```

```bash
php artisan migrate            # uitvoeren
php artisan migrate:rollback   # laatste stap terugdraaien
```

Rules:

- Never modify a migration that has already run on the live server. Create a new one.
- `migrate:fresh` deletes **all** data. Only use it locally.
- Use `decimal` for monetary amounts, never `float`.

## The N+1 problem

This code looks harmless:

```php
foreach (Factuur::all() as $factuur) {
    echo $factuur->klant->naam;   // elke keer een extra query
}
```

With 500 invoices, that amounts to 501 queries. The solution is **eager loading**:

```php
foreach (Factuur::with('klant')->get() as $factuur) {
    echo $factuur->klant->naam;   // 2 queries in totaal
}
```

Tip: Add `AppServiceProvider` `Model::preventLazyLoading(! app()->isProduction());` to your `AppServiceProvider`. This will trigger a local error message as soon as this happens.

## Security: SQL injection

Never hard-code user input into an SQL string. Use Eloquent or placeholders:

```php
DB::select('SELECT * FROM klanten WHERE email = ?', [$email]);   // goed
DB::select("SELECT * FROM klanten WHERE email = '$email'");      // FOUT
```

## Need help?

Has your app become slow, or are you unsure whether your queries are secure? I’ll take a look at it as part of **AI code review**. Setting up a new database falls under **Bespoke software and web applications**.

## Skills

- [SQL Performance Optimization Assistant] (/nl/skills/sql-optimization)
- [SQL Code Review] (/nl/skills/sql-code-review)
- [SQL Optimization Patterns] (/nl/skills/sql-optimization-patterns)
- [Supabase Postgres Best Practices] (/nl/skills/supabase-postgres-best-practices)
- [Laravel Database Optimization] (/nl/skills/laravel-database-optimization)
- [Database Migration] (/nl/skills/database-migration)
- [PostgreSQL Table Design] (/nl/skills/postgresql-table-design)

## Related services

- [Maatwerk software en webapplicaties] (/nl/services#service-03)
- [Beoordeling van AI-code] (/nl/services#service-05)

