M
M
MaxGoodWork2021-05-06 11:26:38
SQL
MaxGoodWork, 2021-05-06 11:26:38

How to write a condition that is always true?

I make a selection of rows according to several conditions - sale or purchase (expressed as bool in the table), price (if it is not more than the specified one), quantity (also not more than the user-specified one). This results in a request like this:

SELECT * FROM products WHERE (bay=1) AND (price <= 5500) AND (quantity <= 3);

But there is one problem - the user may not filter rows by one or more parameters. For example, for such a case, you can write a negative number for the price, it naturally cannot be such, but this condition is absolutely not universal, but at least for bool.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
ComodoHacker, 2021-05-06
@MaxGoodWork

AND 1=1

D
Dmitry Shitskov, 2021-05-06
@Zarom

If I understand your problem correctly, you just need to construct a query depending on the passed values. Those. if the user has not specified a filter, then such an AND condition should not be present in the query either. For a PL not specified by you, there should be some SQL Builder that is conveniently suitable for solving such a problem.

D
d-stream, 2021-05-06
@d-stream

For a more advanced filtering in the form of a set of something - you should think about a stored procedure, which, for example, will receive a bunch of filter parameters
, and in it, in the simple case, it is already uniform
where
param1 is null or filed1=param1
...
and paramN is null or filedN=paramN
of course, the parameter can be some kind of enum-like one that will drag a bunch of preliminary requests / calculations (for example, only goods that were sold to other customers from the same group, etc.)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question