title: How to perform count on table in "Create view" without knowing if table exists
body: <p>I have a piece of code running which makes calls to postgresql and which is being used (in a loop) over a large set of schemas. These schemas have identical layouts apart from 1 table which is optionally present in the schema. </p>
  
  <p>In one part of the code a simple count is done on the rows of this specific table. However, since this table is optionally present in the schema it might not exist. In that case the count should return 0.</p>
  
  <p>Of course I can make it in two steps:</p>
  
  <p>(simplified code:)</p>
  
  <p><strong>1 first check if table exists</strong></p>
  
  <pre><code>SELECT * 
  FROM information_schema.tables
  WHERE table_schema = 'X' 
      AND table_name = 'import'
  LIMIT 1;
  </code></pre>
  
  <p><strong>2 Next if table exist make a secondary call for the count of the table.</strong></p>
  
  <pre><code>Select count(*) as freq from X.import
  </code></pre>
  
  <p>If the table doesn't exist, just return 0, without a secondary call.</p>
  
  <p>However in this case the code is used to create a view. So the call would be something like this:</p>
  
  <pre><code>CREATE OR REPLACE VIEW Y AS
  WITH TABLES AS (SELECT table_schema||'.'||table_name FROM information_schema.tables)
  SELECT CASE 
  WHEN 'X.import' in (SELECT * FROM TABLES) 
  THEN (SELECT count(*) FROM X.import) 
  ELSE 0 
  END
  </code></pre>
  
  <p>Naturally this code will not work, because it won't except the use of X.import in the THEN clause, if import is no part of schema X.</p>
  
  <p>Is there a way around for this, or am I missing some other simple solution?</p>