diff --git a/README.md b/README.md index 3cf130d..0282771 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_509 TILs and counting..._ +_510 TILs and counting..._ --- @@ -276,6 +276,7 @@ _509 TILs and counting..._ - [Lower Is Faster Than ilike](postgres/lower-is-faster-than-ilike.md) - [Max Identifier Length Is 63 Bytes](postgres/max-identifier-length-is-63-bytes.md) - [pg Prefix Is Reserved For System Schemas](postgres/pg-prefix-is-reserved-for-system-schemas.md) +- [Prepare, Execute, And Deallocate Statements](postgres/prepare-execute-and-deallocate-statements.md) - [Pretty Print Data Sizes](postgres/pretty-print-data-sizes.md) - [Print The Query Buffer In psql](postgres/print-the-query-buffer-in-psql.md) - [Renaming A Sequence](postgres/renaming-a-sequence.md) diff --git a/postgres/prepare-execute-and-deallocate-statements.md b/postgres/prepare-execute-and-deallocate-statements.md new file mode 100644 index 0000000..457974a --- /dev/null +++ b/postgres/prepare-execute-and-deallocate-statements.md @@ -0,0 +1,45 @@ +# Prepare, Execute, and Deallocate Statements + +In PostgreSQL, you can prepare a named statement to be executed later using +[`prepare`](https://www.postgresql.org/docs/current/static/sql-prepare.html). + +```sql +> prepare column_names (text) as select column_name from information_schema.columns where table_name = $1; +PREPARE +``` + +These statements are kept around for the duration of the session. To see the +available statements, check out the `pg_prepared_statements` view. + +```sql +> select * from pg_prepared_statements; + name | statement | prepare_time | parameter_types | from_sql +--------------+-----------------------------------------------------------------------------+-------------------------------+-----------------+---------- + column_names | prepare column_names (text) as +| 2017-03-10 15:01:09.154528-06 | {text} | t + | select column_name from information_schema.columns where table_name = $1; | | | +``` + +To run a prepared statement, use `execute` with the name of the statement +and any arguments. + +```sql +> execute column_names('users'); + column_name +----------------- + id + email + password_digest + created_at + updated_at + first_name + last_name +``` + +You can also delete a statement with +[`deallocate`](https://www.postgresql.org/docs/current/static/sql-deallocate.html) +if you'd like. + +```sql +> deallocate column_names; +DEALLOCATE +```