Revealing the Queries Behind Psql's Backslash Commands
Psql has a lot of super useful backslash commands, but sometimes it's even more useful to know the queries behind them.
Join the DZone community and get the full member experience.Join For Free
PostgreSQL's psql interactive terminal tool provides several useful "backslash list commands" such as
\d (lists "relations" such as tables, views, indexes, and sequences),
\dt (lists tables),
\di (lists indexes),
\ds (lists sequences),
\dv (lists views),
\df (lists functions),
\du (lists roles), and
\? (displays help/usage details on backslash commands). These commands are concise and much simpler to use than writing the queries against PostgreSQL system catalogs ( pg_class, pg_roles, pg_namespace, pg_trigger, pg_index, etc.) and information_schema that would provide the same types of details.
psql backslash commands are easier to use than their associated queries, there are situations when it is important to know the full query behind a particular command. These situations include needing to perform a slightly different/adapted query from that associated with the pre-built command and needing to perform similar queries in scripts or code that are being used as PostgreSQL clients instead of
psql. These situations make it important to be able to determine what queries
psql is performing and the
--echo-hidden) allow that.
The PostgreSQL psql documentation states that the
--echo-hidden "echo the actual queries generated by
\d and other backslash commands." The documentation adds commentary on why this is useful. "You can use this to study psql's internal operations." When
psql is started with the
--echo-hidden options, it will display the query associated with a backslash command before executing that command. The next screen snapshot illustrates this for the
\du command used to show roles.
From use of
psql -E and execution of the command
\du, we're able to see that the query underling
\du is this:
SELECT r.rolname, r.rolsuper, r.rolinherit, r.rolcreaterole, r.rolcreatedb, r.rolcanlogin, r.rolconnlimit, r.rolvaliduntil, ARRAY(SELECT b.rolname FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid) WHERE m.member = r.oid) as memberof , r.rolreplication , r.rolbypassrls FROM pg_catalog.pg_roles r WHERE r.rolname !~ '^pg_' ORDER BY 1;
Although the query is not nearly as nice to use as
\du, we are now able to adapt this query for a related but different use case and are able to run this query from a PostgreSQL client other than
Published at DZone with permission of Dustin Marx, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.