Writing functions
◈ 2 cardsPackage logic into a reusable function.
Reusable logic in the database
You can define your own functions. The simplest are SQL functions — a named, parameterized query:
CREATE FUNCTION book_count(g text) RETURNS bigint AS $$
SELECT count(*) FROM books WHERE genre = g
$$ LANGUAGE sql;
SELECT book_count('fiction'); -- 3
The body lives between the $$ dollar quotes (so inner quotes don't need escaping). Call it anywhere an expression or table is allowed.