I have two tables table A and table B.

table B has a field called condition (where some sql conditions are stored).

Now i wanted to query like this

select * 
from table_A  as a
where a.id = 1 
  and (select b.condition from tableB as b)

I would like get the output for which of the condition satisfies.

  • 4
    Please Edit your question and add some sample data and the expected output based on that data. Formatted text please, no screen shots – a_horse_with_no_name Jan 27 '17 at 10:59
  • There is one table A and one table B. – McNets Jan 27 '17 at 11:16
  • 2
    You're selecting conditions from table B, you said: table A has a field called condition – McNets Jan 27 '17 at 12:32
  • Is there any related field between table A and B? – McNets Jan 27 '17 at 13:44
  • 3
    The question is not clear. Edit the question and add all needed information there. Also add the CREATE TABLE scripts and - even better - sample data. – ypercubeᵀᴹ Jan 27 '17 at 15:20

Your question isn't terribly clear but I think what you are expecting is that if there is a row in TableB where column condition contains the text of a SQL clause like someField = 123 then the query will do:

SELECT * FROM table_A AS a 
WHERE  a.id = 1 
AND    (SELECT b.condition FROM tableB AS b)

would have the effect of:

SELECT * FROM table_A AS a 
WHERE  a.id = 1 
AND    (someField = 123)

This is not possible in the SQL standard nor directly possible in any SQL implementation that I am aware of. In MS SQL Server you could achieve this in a stored procedure by putting together ad-hoc SQL and running that via calls like EXEC (@VaraiableContainingSQL) and I presume the same is also possible in postgres' implementation of stored procedures, but it cannot be done in a simple single statement as described in the question.

As a side note: if those conditions are being provided by your users or any third party then this a very bad idea as it is an easy way to introduce SQL injection attacks. See https://www.owasp.org/index.php/SQL_Injection and https://xkcd.com/327/, amongst other references, for details and implications of this.

With regard to:

table b itself is a foreign key for table A

... that sentence does not really make any sense. A table can not be a foreign key, a column (or group of columns) with a table can.

As suggested by a_horse_with_no_name you need to edit the question to provide much more detail of the schema (table layouts, their columns, keys and indexes), inputs, data, and intended outputs, to improve our ability to help you.


It is not clear what you are asking for, but maybe this solve your problem.

select * 
from table_A  as a
     inner join table_B as b on a.sass = b.sass
where a.id = 1 
      and b.condition = 'something';

Not the answer you're looking for? Browse other questions tagged or ask your own question.