2

I want to check whether the emp_id and date has been already there in both bill_item and bill_item_temp tables or not? if not exists then i have to do insert?

s = CONN.cursor()                 
query = """insert into bill_item (id,product_name,price,create_date,emp_id)
           select %s,%s,%s,%s,%s where not exists ( select 1 from bill_item where emp_id = %s and 
           select 1 from bill_item_ref where emp_id = %s);"""
s.execute(query,(id,product_name,price,create_date,emp_id,)); 

table: bill_item

id product_name price create_date                   emp_id
1  rice         10    2021-03-09 10:10:10.231321    12345
2  tea          10    2021-03-09 08:10:10.231321    22345

table: bill_item_temp

id product_name   price create_date                   emp_id
1  drinks         10    2021-03-09 10:10:10.231321    67345
2  snacks         10    2021-03-09 08:10:10.231321    92345
2
  • 1
    Unrelated to your problem, but: Postgres 9.1 is no longer supported you should plan an upgrade as soon as possible. Commented Mar 9, 2021 at 7:15
  • could you give a alternate solution for how to check the 2 select queries by using exists at the same time Commented Mar 9, 2021 at 7:21

1 Answer 1

1

The FROM clause is missing in this query:

select %s,%s,%s,%s,%s where not exists(...)

And the SELECT statement has incorrect syntax here:

where not exists ( select 1 from bill_item where emp_id = %s and 
                   select 1 from bill_item_ref where emp_id = %s);

You can't have AND between two SELECT statements.

Either use UNION/UNION ALL or use separate EXISTS for individual SELECT statement.

This is how you can use UNION ALL:

where not exists ( select 1 from bill_item where emp_id = %s UNION ALL 
                   select 1 from bill_item_ref where emp_id = %s);

And this is how you can use separate EXISTS for individual SELECT statement:

where not exists (select 1 from bill_item where emp_id = %s) and
      not exists (select 1 from bill_item_ref where emp_id = %s);
Sign up to request clarification or add additional context in comments.

6 Comments

Could you please give me the code by using union.. i am a fresher i dono how to use
@pythoncoder That depends on your use case here. Do you want both entries to be present? What should happen if there is an entry in bill_item but it's missing in bill_item_ref (and vice versa)?
either one of the tables has the record means (exists) means then insertion should not happen.
@pythoncoder I have updated my answer to include UNION ALL.
This is a Python exception. Can you try executing this query directly in Postgres?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.