Site icon Database Tutorials

PostgreSQL – psql – gexec

As database administrators or software developers, we sometimes write sqls that produce sqls. We save the output to the file. Then we run this file again and get the actual result we want. If the generated script is not too large, we can complete the process with the copy / paste method.

Previously, I also saw functions that were written in order to solve this situation practically. The gexec command in psql that comes with PostgreSQL 9.6 makes this process very easy. In fact, it is a meta-command that is not in the syntax of PostgreSQL but is in the client application psql.

So, if you try the following on a client other than psql, you probably won’t get results.

First, write a sql that produces sql. This will create 5 tables. It is good to check before executing.

Let’s create them. All we have to do is add \gexec to the end of the query we wrote above.

Our tables are created. We can see the result with \dt.

Let’s drop them.

We checked the output first. Then we execute it and saw the result. Very easy/practical.

Notes

Exit mobile version