2
Hello, I didn’t find much information in research I did on... but I am currently having a problem which is as follows:
I have an appointment with many simple conditions, just sequences of and. But today I had to include some or, and lo and behold the query just can’t finish anymore, it runs for minutes until it stops for exceeding the memory limit of Postgressql or something like that. Behold, then I thought of separating these or inside a block, in this case, I put them in parentheses and then the query rotated very quickly and brought me a result without errors. So I decided to do a test with another query, this time it was much simpler and... when I put the parentheses, the query now would not bring me anything else, but if I removed them, it would perform as expected.
So I started asking myself, what was really going on and what is the right procedure to do and how the parentheses should be used in WHERE. A thank you already!
Example of the query I am using without parentheses:
nfe.id_empresa = 4 and
nfe.ano = '2016' and
nfe.id_empresa = nfe_item.id_empresa and
nfe.ano = nfe_item.ano and
nfe.mes = nfe_item.mes and
nfe_item.cst_icms = '010' or
nfe_item.cst_icms = '030' or
nfe_item.cst_icms = '060' or
nfe_item.cst_icms = '070' or
nfe_item.cst_icms = '110' ;
Now in parentheses:
nfe.id_empresa = 4 and
nfe.ano = '2016' and
nfe.id_empresa = nfe_item.id_empresa and
nfe.ano = nfe_item.ano and
nfe.mes = nfe_item.mes and
(
nfe_item.cst_icms = '010' or
nfe_item.cst_icms = '030' or
nfe_item.cst_icms = '060' or
nfe_item.cst_icms = '070' or
nfe_item.cst_icms = '110'
);
The second query is correct, has a
and
and all options withor
in parentheses (only one comment, could usein
removing theor
and simply for a row), now you have to see the number of records in the table (how many records does the table have? ). The fieldcst_icms
must bevarchar
, I’m sure?– Ricardo Pontual
Without parentheses, if nfe_item.cst_icms = '110' for example, it will already return a value independent of any other and that you have placed. I believe your logic requires parentheses to be correct. You’re probably not bringing anything for another logic flaw.
– Marcelo Vieira
Hello! Good then that I was doing correctly. Table posssui 109 thousand records, is a lot of stuff. and yes, it is a VARCHAR a cst_icms!
– Rafael Araujo
Try later to use
IN
to simplify the syntax and not need the parentheses:AND nfe_item.cst_icms IN ('010','030','060','070','110')
– Ricardo Pontual
Very good tip, I tested here and I’m already using. Thank you!
– Rafael Araujo