Sikau

Databases and SQL · Day 16 · about 25 min

Safe queries from apps

SQL injection and parameterised queries.

Bobby Tables

If your app builds SQL by pasting user input into a string, someone can type SQL instead of a name — and run it. SQL injection has leaked millions of records. The fix is simple and non-negotiable: parameters.

Never concatenate — parameterise

SELECT name FROM customers WHERE name = 'x'' OR ''1''=''1';

SELECT name FROM customers WHERE name = 'x' OR '1'='1';
  • Use your driver's placeholders ($1 in PostgreSQL, ? in MySQL) or an ORM/query builder.
  • Give the app's database user only the permissions it needs (no DROP for the web app!).
  • Identifiers (table/column names) can't be parameters — pick them from an allow-list.

The rest of this lesson

  • How an injection worksexplain
  • Defence in depthexplain
  • Safe?predict
  • Safe or unsafe?match
  • Parameterise itfill
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 17 lessons of Databases and SQL