Dynamic SQL and Large Objects
Building and running SQL at run time with EXECUTE, format and USING: looping over tables, optional search filters, generating DDL, and staying safe from injection; then storing large text and binary data with TOAST, bytea and the large object facility, and when files belong outside the database.
kvi5hnuCode Sprout team member11 min readOn this page
Most SQL is static: the statement's text is fixed when the code is written, and only values change. Sometimes the statement itself depends on run-time information: which table to read, which filters a user chose, which columns exist. Dynamic SQL builds the statement's text while the code runs, then executes it.
This article covers dynamic SQL in PL/pgSQL, the rules that keep it safe, and three typical uses. The second half covers a different practical topic that procedural code often deals with: storing large values such as documents and images.
EXECUTE
In PL/pgSQL, EXECUTE runs a statement given as text:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Dynamic SQL: build a statement's text at run time, then EXECUTE it
CREATE FUNCTION row_counts()
RETURNS TABLE (table_name TEXT, row_count BIGINT)
LANGUAGE plpgsql
AS $$
DECLARE
t TEXT;
BEGIN
FOR t IN
SELECT c.table_name FROM information_schema.tables c
WHERE c.table_schema = 'public' AND c.table_type = 'BASE TABLE'
ORDER BY c.table_name
LOOP
table_name := t;
EXECUTE format('SELECT COUNT(*) FROM %I', t) INTO row_count; -- %I quotes the name
RETURN NEXT;
END LOOP;
END
$$;
SELECT * FROM row_counts();
table_name | row_count
-------------+-----------
customers | 6
order_items | 9
orders | 6
products | 7
(4 rows)
row_counts can't be written with static SQL, because a table name can't be a variable in a normal query: SELECT COUNT(*) FROM t would look for a table called t. Instead, the function loops over the table names from information_schema (article 57), builds SELECT COUNT(*) FROM customers and so on as text, and runs each with EXECUTE ... INTO, which stores the result in a variable.
Differences from static SQL inside PL/pgSQL:
- The statement is parsed and planned every time it runs, rather than once and cached. That costs a little, and sometimes helps: a plan made for the actual values can be better than a generic one.
- Errors in the text, such as a misspelt column, appear only at run time.
- PL/pgSQL variables aren't visible inside the text. Values are passed in with
USING. EXECUTE ... INTOstores one row's result,RETURN QUERY EXECUTEreturns all rows from a function, andFOR r IN EXECUTE ... LOOPloops over them.
Other databases have the same idea under other names: Oracle's EXECUTE IMMEDIATE and the DBMS_SQL package, SQL Server's sp_executesql (and the riskier EXEC(@sql)), and MySQL's PREPARE ... FROM @sql with EXECUTE ... USING. psql's \gexec (article 44) runs generated statements from the client side.
Keeping dynamic SQL safe
Dynamic SQL brings back the danger that parameters remove: if any text from outside reaches the statement, it can change what the statement does (article 59). Every piece of a dynamic statement falls into one of three kinds:

- Fixed text written by the developer, such as
SELECT COUNT(*) FROM, can be concatenated freely. - Identifiers that come from data or input, such as table and column names, are quoted with
format('%I', name)orquote_ident(name), which wraps them in double quotes when needed and doubles any quote inside. Better still, when the choices are known, map the input to an allow-list. - Values are passed with
USINGand referenced as$1,$2in the text. They're never part of the text at all, so they can't change it.format('%L', value)quotes a value as a literal, and is safe, butUSINGis cleaner and keeps types intact.
format('%s', ...) inserts text unquoted. Use it only for fixed fragments you control, never for input.
Optional filters
A common need is a search where users may or may not supply each filter. Writing one static query for every combination is impractical, and a single query with (p_category IS NULL OR category = p_category) for every filter is valid but can produce a poor plan. Dynamic SQL adds only the conditions that were asked for:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A search with optional filters: build only the conditions that were asked for,
-- and pass every value as a parameter with USING
CREATE FUNCTION search_products(p_category TEXT DEFAULT NULL,
p_max_price NUMERIC DEFAULT NULL,
p_sort TEXT DEFAULT 'name')
RETURNS TABLE (name VARCHAR, category VARCHAR, price NUMERIC)
LANGUAGE plpgsql
AS $$
DECLARE
v_sql TEXT := 'SELECT name, category, price FROM products WHERE true';
BEGIN
IF p_category IS NOT NULL THEN
v_sql := v_sql || ' AND category = $1';
END IF;
IF p_max_price IS NOT NULL THEN
v_sql := v_sql || ' AND price <= $2';
END IF;
-- identifiers can't be parameters: allow-list the sort column
v_sql := v_sql || ' ORDER BY ' ||
CASE p_sort WHEN 'price' THEN 'price' ELSE 'name' END;
RAISE NOTICE '%', v_sql;
RETURN QUERY EXECUTE v_sql USING p_category, p_max_price;
END
$$;
SELECT * FROM search_products(p_category => 'tents');
SELECT * FROM search_products(p_max_price => 30, p_sort => 'price');
SELECT * FROM search_products(p_sort => 'price; DROP TABLE products');
psql:/workspace/solution.sql:88: NOTICE: SELECT name, category, price FROM products WHERE true AND category = $1 ORDER BY name
name | category | price
---------------+----------+--------
Ridge 2 tent | tents | 249.99
Summit 4 tent | tents | 489.00
(2 rows)
psql:/workspace/solution.sql:89: NOTICE: SELECT name, category, price FROM products WHERE true AND price <= $2 ORDER BY price
name | category | price
------------------+----------+-------
Merino socks | clothing | 16.00
Basecamp lantern | lighting | 27.00
(2 rows)
psql:/workspace/solution.sql:90: NOTICE: SELECT name, category, price FROM products WHERE true ORDER BY name
name | category | price
-------------------+----------+--------
Basecamp lantern | lighting | 27.00
Day 18 backpack | packs | 54.00
Glow head torch | lighting | 34.50
Merino socks | clothing | 16.00
Ridge 2 tent | tents | 249.99
Summit 4 tent | tents | 489.00
Trail 30 backpack | packs | 89.95
(7 rows)
- Each filter adds its condition only when its argument isn't NULL. The conditions refer to
$1and$2, andUSING p_category, p_max_pricesupplies the values: a value can never become SQL. - Parameters are numbered by position in the
USINGlist, so$2always means the price, even when there's no category condition. Unused parameters are allowed. - The sort column is an identifier, so it can't be a parameter. A
CASEmaps the input to a known column, and anything else, including the injection attempt in the third call, falls back toname. RAISE NOTICEshows the statement each call built, which is worth doing while developing dynamic SQL.
Generating DDL
Dynamic SQL is the standard way to apply the same change to many objects, driven by metadata:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Generating DDL for many tables: add a created_at column to every table that lacks one
DO $$
DECLARE
t TEXT;
BEGIN
FOR t IN
SELECT tb.table_name FROM information_schema.tables tb
WHERE tb.table_schema = 'public' AND tb.table_type = 'BASE TABLE'
AND NOT EXISTS (SELECT 1 FROM information_schema.columns c
WHERE c.table_schema = 'public' AND c.table_name = tb.table_name
AND c.column_name = 'created_at')
ORDER BY tb.table_name
LOOP
EXECUTE format('ALTER TABLE %I ADD COLUMN created_at TIMESTAMPTZ NOT NULL DEFAULT now()', t);
RAISE NOTICE 'added created_at to %', t;
END LOOP;
END
$$;
SELECT table_name FROM information_schema.columns
WHERE table_schema = 'public' AND column_name = 'created_at'
ORDER BY table_name;
psql:/workspace/solution.sql:79: NOTICE: added created_at to customers
psql:/workspace/solution.sql:79: NOTICE: added created_at to order_items
psql:/workspace/solution.sql:79: NOTICE: added created_at to orders
psql:/workspace/solution.sql:79: NOTICE: added created_at to products
table_name
-------------
customers
order_items
orders
products
(4 rows)
The block finds every table without a created_at column, using NOT EXISTS on information_schema.columns, and runs an ALTER TABLE for each, with %I quoting the table name. Running it again does nothing, because the column now exists. Scripts that are safe to rerun like this, called idempotent, are valuable in migrations. The same pattern grants privileges on every table, creates the same trigger on every table (article 65), or creates monthly partitions in advance.
DDL changes affect the whole application, so run such scripts through the normal migration process (article 53), and review what they'll do first, for example by printing the statements with RAISE NOTICE before switching to EXECUTE.
Storing large values
Applications often need to store large values: product manuals, contracts, images, uploaded files. Databases offer several approaches.
Large text and bytea columns
-- Large values in ordinary columns: text and bytea hold up to 1 GB, stored out of line (TOAST)
CREATE TABLE documents (
doc_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
body TEXT,
scan BYTEA
);
INSERT INTO documents VALUES
(1, 'Tent manual', repeat('Peg the corners first. ', 50000), decode('89504e470d0a1a0a', 'hex')),
(2, 'Short note', 'Keep dry.', NULL);
SELECT doc_id, title,
octet_length(body) AS body_bytes,
pg_column_size(body) AS stored_bytes, -- after compression
encode(substring(scan FROM 1 FOR 4), 'hex') AS scan_starts_with
FROM documents ORDER BY doc_id;
-- Read part of a large value without fetching it all
SELECT left(body, 23) AS first_sentence FROM documents WHERE doc_id = 1;
doc_id | title | body_bytes | stored_bytes | scan_starts_with
--------+-------------+------------+--------------+------------------
1 | Tent manual | 1150000 | 13196 | 89504e47
2 | Short note | 9 | 10 |
(2 rows)
first_sentence
-------------------------
Peg the corners first.
(1 row)
In PostgreSQL, ordinary TEXT and BYTEA (binary) columns can hold values of up to 1 GB. Large values are handled automatically by TOAST (The Oversized-Attribute Storage Technique): values over about 2 kB are compressed, and moved to a separate table if still large, leaving a pointer in the row.
- The manual's 1,150,000 bytes of repetitive text are stored in about 13 kB. Real documents compress less well, but often still substantially.
- Queries that don't select the large column don't read it, so tables with big values stay fast to scan for their other columns.
byteaholds raw bytes, such as an image.decode(..., 'hex')andencode(..., 'hex')convert between bytes and text. The scan's first bytes,89504e47, are the signature of a PNG image.- Functions such as
left,substringandoctet_lengthwork on large values without the application having to fetch them in full.
For values up to a few megabytes, ordinary columns are the simplest choice: they're transactional, backed up with everything else, and work with any driver. Other databases have similar types: Oracle's CLOB and BLOB, SQL Server's VARCHAR(MAX) and VARBINARY(MAX) (up to 2 GB), and MySQL's LONGTEXT and LONGBLOB (up to 4 GB).
PostgreSQL large objects
For values larger than 1 GB, or that must be read and written in pieces like a file, PostgreSQL has the large object facility:
-- The large object facility: data stored separately, referenced by an OID
SELECT lo_from_bytea(424242, convert_to('Ridge 2 tent: full pitching guide...', 'UTF8')) AS lo_oid;
CREATE TABLE manuals (product_id INTEGER PRIMARY KEY, content_oid OID);
INSERT INTO manuals VALUES (1, 424242);
-- Read it back, or just a slice of it
SELECT product_id,
convert_from(lo_get(content_oid), 'UTF8') AS whole,
convert_from(lo_get(content_oid, 0, 12), 'UTF8') AS first_12_bytes
FROM manuals;
-- Deleting the row does NOT delete the large object: unlink it explicitly
DELETE FROM manuals WHERE product_id = 1;
SELECT COUNT(*) AS orphaned_objects FROM pg_largeobject_metadata WHERE oid = 424242;
SELECT lo_unlink(424242);
SELECT COUNT(*) AS after_unlink FROM pg_largeobject_metadata WHERE oid = 424242;
lo_oid
--------
424242
(1 row)
product_id | whole | first_12_bytes
------------+--------------------------------------+----------------
1 | Ridge 2 tent: full pitching guide... | Ridge 2 tent
(1 row)
orphaned_objects
------------------
1
(1 row)
lo_unlink
-----------
1
(1 row)
after_unlink
--------------
0
(1 row)
- A large object is stored in the system table
pg_largeobject, in chunks, and identified by an OID. A table stores that OID to refer to it. Large objects can be up to 4 TB. lo_from_byteacreates one,lo_getreads all of it or a slice, and client libraries offer file-likeopen,read,seekandwritecalls for streaming.- Deleting the row doesn't delete the large object. It's a separate object, so it becomes orphaned and keeps using space until
lo_unlinkremoves it. Theloextension provides a trigger that unlinks automatically, and thevacuumlotool removes orphans.
Large objects are more awkward than bytea: they need separate privileges, special handling in backups and replication tools, and care to avoid orphans. Use them only when their size or streaming access is really needed.
Files outside the database
For large media, such as videos, image libraries or user uploads, many systems store the files in a file store or object storage service and keep only metadata and a reference, such as a path or URL, in the database. Trade-offs:
| In the database | Outside, with a reference | |
|---|---|---|
| consistency | transactional with the rest of the data | the file and the row can get out of step |
| backups | included automatically, but backups grow | separate backups needed |
| serving | through the application | directly, from object storage or a CDN |
| size | database grows, which slows backups and replication | the database stays small |
A common rule of thumb: small and medium values that belong with the data, such as thumbnails, documents and JSON, in the database; large media in object storage, written first and referenced by the row only once the upload succeeds. SQL Server's FILESTREAM offers a hybrid, storing values as files managed by the database.
Large objects in Oracle
Oracle has three large-object types: CLOB for long text, BLOB for binary data, and BFILE, a read-only pointer to a file stored outside the database on the server. Plain VARCHAR2 holds at most 4,000 bytes in SQL, or 32,767 with MAX_STRING_SIZE = EXTENDED, and in PL/SQL variables 32,767, so longer text needs a CLOB.
LOB columns are worked with through locators, references to the data, and the DBMS_LOB package: DBMS_LOB.GETLENGTH, DBMS_LOB.SUBSTR, DBMS_LOB.APPEND and DBMS_LOB.INSTR read and change parts of a LOB without loading it whole, and EMPTY_BLOB() or EMPTY_CLOB() creates an empty LOB to write into. From application code, drivers stream LOBs, as with JDBC's setBinaryStream and getBinaryStream, so large files don't have to fit in memory.
What's current
- PostgreSQL 14 added
lz4as an alternative TOAST compression method, faster than the defaultpglz, selectable per column withCOMPRESSION lz4or by default withdefault_toast_compression. - PostgreSQL 16 added
pg_input_is_valid, useful for validating input before it reaches dynamic or static SQL. - Object storage has become the usual home for large media in cloud applications, with databases storing references and metadata.
Common questions
When do I need dynamic SQL? When the statement's structure isn't known until run time: table or column names from data, optional filters, or DDL applied to many objects. If only values change, use static SQL with parameters.
Is dynamic SQL slow? It's parsed and planned on every run, which costs a little. For complex searches, a plan tailored to the actual filters is often faster overall.
How do I pass a table name safely?
Quote it with format('%I', name) or quote_ident, or better, check it against a list of allowed names.
Should I store files in the database?
Small and medium files: often yes, in bytea columns, for simplicity and consistency. Large media: usually in object storage, with a reference in the database.
Why is my database growing after deleting rows that referenced large objects?
The large objects were orphaned. Unlink them with lo_unlink, use the lo extension's trigger, or run vacuumlo.
Summary
- Dynamic SQL builds statement text at run time and runs it with
EXECUTE, which is parsed and planned each time. - Quote identifiers with
%I, or use an allow-list. Pass values withUSING, never in the text. - Typical uses: statements over many tables, optional search filters, and generating DDL from metadata.
TEXTandBYTEAhold up to 1 GB, with automatic compression and out-of-line storage (TOAST).- Large objects hold up to 4 TB with streaming access, but must be unlinked explicitly.
- Large media often belongs in object storage, with references in the database.
Practice questions
Write a PL/pgSQL statement that counts the rows of the table whose name is in v_table where status equals v_status, storing the result in v_n.
Answer
EXECUTE format('SELECT COUNT(*) FROM %I WHERE status = $1', v_table)
INTO v_n
USING v_status;
What's wrong with EXECUTE 'SELECT * FROM products WHERE name = ''' || p_name || ''''?
Answer
p_name is pasted into the SQL text, so a value containing a quote can change the statement: SQL injection. Pass it as a parameter: EXECUTE 'SELECT * FROM products WHERE name = $1' USING p_name.
A user may choose to sort search results by name, price or stock. How should a dynamic query include the chosen column?
Answer
Map the input to one of the allowed columns with a CASE or lookup, falling back to a default for anything else, and concatenate the chosen, known-safe name. Column names can't be passed with USING.
A table stores large object OIDs for product manuals. Products are regularly deleted. What problem will appear, and how can it be prevented?
Answer
Deleting a product row leaves its manual's large object orphaned, still using space. Unlink the object when the row is deleted, for example with the lo extension's lo_manage trigger, or clean up periodically with vacuumlo. Storing manuals in a bytea column avoids the problem, since the value is deleted with the row.
Previous: SQL Triggers

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.