What\'s the equivalent to show tables
(from MySQL) in PostgreSQL?
Using psql : \dt
Or:
SELECT c.relname AS Tables_in FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE pg_catalog.pg_table_is_visible(c.oid)
AND c.relkind = 'r'
AND relname NOT LIKE 'pg_%'
ORDER BY 1
First Connect with the Database using following command
\c database_name
And you will see this message - You are now connected to database database_name
. And them run the following command
SELECT * FROM table_name;
In database_name and table_name just update with your database and table name
Running psql with the -E flag will echo the query used internally to implement \dt and similar:
sudo -u postgres psql -E
postgres=# \dt
********* QUERY **********
SELECT n.nspname as "Schema",
c.relname as "Name",
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' END as "Type",
pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','')
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;
**************************
(For completeness)
You could also query the (SQL-standard) information schema:
SELECT
table_schema || '.' || table_name
FROM
information_schema.tables
WHERE
table_type = 'BASE TABLE'
AND
table_schema NOT IN ('pg_catalog', 'information_schema');
You can list the tables in the current database with \dt
.
Fwiw, \d tablename
will show details about the given table, something like show columns from tablename
in MySQL, but with a little more information.
as a quick oneliner
# just list all the postgres tables sorted in the terminal
db='my_db_name'
clear;psql -d $db -t -c '\dt'|cut -c 11-|perl -ne 's/^([a-z_0-9]*)( )(.*)/$1/; print'
or if you prefer much clearer json output multi-liner :
IFS='' read -r -d '' sql_code <<"EOF_CODE"
select array_to_json(array_agg(row_to_json(t))) from (
SELECT table_catalog,table_schema,table_name
FROM information_schema.tables
ORDER BY table_schema,table_name ) t
EOF_CODE
psql -d postgres -t -q -c "$sql_code"|jq