{
    "url": "https://delaparra-services.nl/manuals/sql-queries-en-migraties",
    "locale": "en",
    "title": "Writing SQL queries and migrations · DeLaParra Services",
    "description": "The basics of SQL (SELECT, WHERE, JOIN, GROUP BY), indexes, Laravel migrations and the N+1 problem with Eloquent.",
    "alternates": {
        "en": "https://delaparra-services.nl/manuals/sql-queries-en-migraties",
        "nl": "https://delaparra-services.nl/nl/handleidingen/sql-queries-en-migraties"
    },
    "formats": {
        "csv": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.csv",
        "md": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.md",
        "json": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.json",
        "zip": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.zip",
        "pdf": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.pdf"
    },
    "downloads": [
        {
            "url": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.csv",
            "encodingFormat": "text/csv",
            "name": "sql-queries-en-migraties.csv"
        },
        {
            "url": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.json",
            "encodingFormat": "application/json",
            "name": "sql-queries-en-migraties.json"
        },
        {
            "url": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.md",
            "encodingFormat": "text/markdown",
            "name": "sql-queries-en-migraties.md"
        },
        {
            "url": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.pdf",
            "encodingFormat": "application/pdf",
            "name": "sql-queries-en-migraties.pdf"
        },
        {
            "url": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.zip",
            "encodingFormat": "application/zip",
            "name": "sql-queries-en-migraties.zip"
        }
    ],
    "markdown": "# Writing SQL queries and migrations\n\nAlmost 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.\n\n## The basics\n\n```sql\nSELECT id, naam, email\nFROM klanten\nWHERE plaats = 'Groningen'\nORDER BY naam\nLIMIT 20;\n```\n\n- `SELECT`: which columns\n- `FROM`: which table\n- `WHERE`: which rows\n- `ORDER BY`: sorting\n- `LIMIT`: how many\n\n## Combining tables using JOIN\n\n```sql\nSELECT k.naam, f.nummer, f.bedrag\nFROM facturen f\nINNER JOIN klanten k ON k.id = f.klant_id\nWHERE f.betaald = 0;\n```\n\n| JOIN | Displays |\n|---|---|\n| `INNER JOIN` | Only rows that match in both tables |\n| `LEFT JOIN` | All rows on the left, even if there is no match (the right-hand side becomes `NULL`) |\n| `RIGHT JOIN` | The other way round |\n| `FULL OUTER JOIN` | Everything from both sides (not in MySQL) |\n\n## Counting and grouping\n\n```sql\nSELECT klant_id, COUNT(*) AS aantal, SUM(bedrag) AS totaal\nFROM facturen\nGROUP BY klant_id\nHAVING SUM(bedrag) > 1000;\n```\n\n`WHERE` filters rows before grouping, `HAVING` filters the groups afterwards.\n\n## Indexes: why a query is slow\n\nAn **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`).\n\nSee how the database executes a query:\n\n```sql\nEXPLAIN SELECT * FROM facturen WHERE klant_id = 42;\n```\n\nDo you see the word `type``ALL` in MySQL? If so, the entire table is being read and there is probably no index.\n\n## Migrations in Laravel\n\nA **migration** is a file that describes how your database changes. This ensures that everyone (and the live server) has exactly the same structure.\n\n```bash\nphp artisan make:migration create_facturen_table\n```\n\n```php\nSchema::create('facturen', function (Blueprint $table) {\n    $table->id();\n    $table->foreignId('klant_id')->constrained()->cascadeOnDelete();\n    $table->string('nummer')->unique();\n    $table->decimal('bedrag', 10, 2);\n    $table->boolean('betaald')->default(false)->index();\n    $table->timestamps();\n});\n```\n\n```bash\nphp artisan migrate            # uitvoeren\nphp artisan migrate:rollback   # laatste stap terugdraaien\n```\n\nRules:\n\n- Never modify a migration that has already run on the live server. Create a new one.\n- `migrate:fresh` deletes **all** data. Only use it locally.\n- Use `decimal` for monetary amounts, never `float`.\n\n## The N+1 problem\n\nThis code looks harmless:\n\n```php\nforeach (Factuur::all() as $factuur) {\n    echo $factuur->klant->naam;   // elke keer een extra query\n}\n```\n\nWith 500 invoices, that amounts to 501 queries. The solution is **eager loading**:\n\n```php\nforeach (Factuur::with('klant')->get() as $factuur) {\n    echo $factuur->klant->naam;   // 2 queries in totaal\n}\n```\n\nTip: Add `AppServiceProvider` `Model::preventLazyLoading(! app()->isProduction());` to your `AppServiceProvider`. This will trigger a local error message as soon as this happens.\n\n## Security: SQL injection\n\nNever hard-code user input into an SQL string. Use Eloquent or placeholders:\n\n```php\nDB::select('SELECT * FROM klanten WHERE email = ?', [$email]);   // goed\nDB::select(\"SELECT * FROM klanten WHERE email = '$email'\");      // FOUT\n```\n\n## Need help?\n\nHas 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**.\n\n## Skills\n\n- [SQL Performance Optimization Assistant] (/nl/skills/sql-optimization)\n- [SQL Code Review] (/nl/skills/sql-code-review)\n- [SQL Optimization Patterns] (/nl/skills/sql-optimization-patterns)\n- [Supabase Postgres Best Practices] (/nl/skills/supabase-postgres-best-practices)\n- [Laravel Database Optimization] (/nl/skills/laravel-database-optimization)\n- [Database Migration] (/nl/skills/database-migration)\n- [PostgreSQL Table Design] (/nl/skills/postgresql-table-design)\n\n## Related services\n\n- [Maatwerk software en webapplicaties] (/nl/services#service-03)\n- [Beoordeling van AI-code] (/nl/services#service-05)\n\n",
    "structured_data": {
        "@context": "https://schema.org",
        "@graph": [
            {
                "@type": "TechArticle",
                "@id": "https://delaparra-services.nl/manuals/sql-queries-en-migraties#article",
                "url": "https://delaparra-services.nl/manuals/sql-queries-en-migraties",
                "headline": "Writing SQL queries and migrations",
                "description": "The basics of SQL (SELECT, WHERE, JOIN, GROUP BY), indexes, Laravel migrations and the N+1 problem with Eloquent.",
                "inLanguage": "en",
                "subjectOf": {
                    "@id": "https://delaparra-services.nl/manuals/sql-queries-en-migraties#dataset"
                }
            },
            {
                "@type": "Dataset",
                "@id": "https://delaparra-services.nl/manuals/sql-queries-en-migraties#dataset",
                "name": "Writing SQL queries and migrations",
                "description": "The basics of SQL (SELECT, WHERE, JOIN, GROUP BY), indexes, Laravel migrations and the N+1 problem with Eloquent.",
                "url": "https://delaparra-services.nl/manuals/sql-queries-en-migraties",
                "identifier": "https://delaparra-services.nl/manuals/sql-queries-en-migraties#dataset",
                "about": {
                    "@id": "https://delaparra-services.nl/manuals/sql-queries-en-migraties#article"
                },
                "publisher": {
                    "@type": "Organization",
                    "name": "DeLaParra Services",
                    "url": "https://delaparra-services.nl/"
                },
                "isAccessibleForFree": true,
                "inLanguage": "en",
                "isPartOf": {
                    "@type": "Dataset",
                    "@id": "https://delaparra-services.nl/manuals#dataset",
                    "name": "Manuals for working on your own app",
                    "url": "https://delaparra-services.nl/manuals"
                },
                "includedInDataCatalog": {
                    "@type": "DataCatalog",
                    "@id": "https://delaparra-services.nl/knowledge-hub#catalog",
                    "name": "Knowledge hub data catalog",
                    "url": "https://delaparra-services.nl/knowledge-hub"
                },
                "distribution": [
                    {
                        "@type": "DataDownload",
                        "name": "sql-queries-en-migraties.csv",
                        "encodingFormat": "text/csv",
                        "contentUrl": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.csv",
                        "inLanguage": "en"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "sql-queries-en-migraties.json",
                        "encodingFormat": "application/json",
                        "contentUrl": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.json",
                        "inLanguage": "en"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "sql-queries-en-migraties.md",
                        "encodingFormat": "text/markdown",
                        "contentUrl": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.md",
                        "inLanguage": "en"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "sql-queries-en-migraties.pdf",
                        "encodingFormat": "application/pdf",
                        "contentUrl": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.pdf",
                        "inLanguage": "en"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "sql-queries-en-migraties.zip",
                        "encodingFormat": "application/zip",
                        "contentUrl": "https://delaparra-services.nl/manuals/sql-queries-en-migraties.zip",
                        "inLanguage": "en"
                    }
                ]
            }
        ]
    }
}