Views, UPSERT, RETURNING & Security – SQL
Reusable views, insert-or-update, return values, and protection against SQL injection.
A view stores a query under a name – useful for reusing complex joins or hiding columns. It stores no data (PostgreSQL offers MATERIALIZED VIEW with a stored result and REFRESH MATERIALIZED VIEW).
CREATE VIEW v_bestellwert AS
SELECT b.id AS bestellung_id, b.kunde_id, b.datum, b.status,
SUM(bp.menge * p.preis) AS wert
FROM bestellungen b
JOIN bestellpositionen bp ON bp.bestellung_id = b.id
JOIN produkte p ON p.id = bp.produkt_id
GROUP BY b.id, b.kunde_id, b.datum, b.status;
SELECT * FROM v_bestellwert WHERE wert > 100;UPSERT = "insert if not present, otherwise update" – atomic and without a race condition. PostgreSQL and SQLite use ON CONFLICT, MySQL ON DUPLICATE KEY UPDATE. RETURNING (PostgreSQL, SQLite from 3.35, MariaDB) returns the affected rows directly, e.g. the generated id.
-- PostgreSQL / SQLite
INSERT INTO produkte (id, name, kategorie, preis)
VALUES (4, 'Kaffee', 'Lebensmittel', 9.20)
ON CONFLICT (id) DO UPDATE SET preis = excluded.preis
RETURNING id, preis;
-- MySQL
INSERT INTO produkte (id, name, kategorie, preis) VALUES (4, 'Kaffee', 'Lebensmittel', 9.20)
ON DUPLICATE KEY UPDATE preis = VALUES(preis);SQL injection occurs when user input is pasted into the SQL text. The solution is prepared statements / parameterized queries: the driver sends the statement and the values separately, and the values are never interpreted as SQL.
-- Wrong (Python pseudocode): "SELECT * FROM kunden WHERE name = '" + eingabe + "'"
-- Input: x' OR '1'='1 -> returns all customers!
-- Correct: placeholders (depending on the driver ?, %s, :name or $1)
-- cursor.execute("SELECT * FROM kunden WHERE name = ?", (eingabe,))
PREPARE suche(text) AS SELECT * FROM kunden WHERE name = $1; -- PostgreSQL
EXECUTE suche('Ada');ORDER BY directions. You have to check such identifiers against a fixed whitelist.GRANT SELECT, INSERT ON ... TO app), not the superuser. This limits the damage if something goes wrong after all.