PostgreSQL: Show tables in PostgreSQL

后端 未结 24 2330
醉梦人生
醉梦人生 2020-11-28 16:58

What\'s the equivalent to show tables (from MySQL) in PostgreSQL?

相关标签:
24条回答
  • 2020-11-28 17:39

    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
    
    0 讨论(0)
  • 2020-11-28 17:41

    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

    0 讨论(0)
  • 2020-11-28 17:42

    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;        
    **************************
    
    0 讨论(0)
  • 2020-11-28 17:45

    (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');
    
    0 讨论(0)
  • 2020-11-28 17:45

    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.

    0 讨论(0)
  • 2020-11-28 17:48

    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
    
    0 讨论(0)
提交回复
热议问题