0

Using postgres I have wrote a query to list the tables inside a database

SELECT table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
AND table_schema NOT IN
('pg_catalog', 'information_schema');

Query returns results from the wrong database. It automatically selects the first database from the list of databases in postgres.

How do I specify the database to query? 'j220190_data' being the database to query

I've tried things like:

    SELECT table_name
FROM information_schema.tables
WHERE Databases = 'j220190_data'
AND table_schema NOT IN
('pg_catalog', 'information_schema');

SELECT table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE' AND
WHERE Databases = 'j220190_data'
AND table_schema NOT IN
('pg_catalog', 'information_schema');
Vivek S.
  • 19,945
  • 7
  • 68
  • 85
John
  • 3,965
  • 21
  • 77
  • 163
  • 2
    "Works fine. but it doesnt work"... – jarlh Nov 28 '16 at 10:43
  • "*How do I specify the database to query*" - you can't you need to first _connect_ to the other database. Postgres does not support cross-database queries –  Nov 28 '16 at 10:44
  • "*It automatically selects the first database from the list of databases in postgres*" - that's wrong. That query returns the information of the database you are currently connected to. –  Nov 28 '16 at 10:45
  • I tried connecting to the database first using \connect 'j220190_data' but this didnt work either – John Nov 28 '16 at 10:46
  • How do I connect to a database of my choosing please? – John Nov 28 '16 at 10:46
  • see http://stackoverflow.com/questions/46324/possible-to-perform-cross-database-queries-with-postgres – Balan Nov 28 '16 at 10:49
  • How you connect to a different database depends on the SQL client you are using. –  Nov 28 '16 at 10:57

2 Answers2

0

When you connect to postgres select database;
for example:

psql mydb

and after you post the select, because when you try whit this select, postgres checks on default database.

el fuser
  • 606
  • 1
  • 6
  • 10
  • 1
    @John: [psql](https://www.postgresql.org/docs/current/static/reference-client.html) is a **command line** program, not a SQL statement. –  Nov 28 '16 at 10:59
  • when u connect at postgres db, you can connect at db that you want, you try with psql j220190_data, if your database is this. You connect from shell obviously – el fuser Nov 28 '16 at 11:00
0

If I understood correctly you can query another database using dblink().

Create extension CREATE EXTENSION dblink;

SELECT tbl.*
FROM dblink('dbname=DB1 port=5432   
            host=localhost user=usr password=123', 'SELECT table_name
FROM information_schema.tables
WHERE table_type = ''BASE TABLE'' 
AND table_schema NOT IN(''pg_catalog'', ''information_schema'');') 
AS tbl(table_name varchar(30));
Vivek S.
  • 19,945
  • 7
  • 68
  • 85