Building a where clause based on user selections My group and I are developing a multi agent system (MAS), a system that is supposed to conduct statistics on specific fields of the agents' databases using semantic search and ontology (the user chooses the fields to be considered).

For example, the user might want to know the number of people stored in the database that are male, over 20 years old, lives in NYC, blood type: A, and are single.

So I was wondering if there is a way to write the query in MySQL(MySQL 5.7.10.0) that returns the number of matching tuples (matches the user's selection and conditions) in the database, or if the jsc.jar in JAVA (java statistical classes) or any other JAVA jar can perform the required operation. I know that I should use the "count(*)" in the query, but I'm not sure how to build the "where" part of the query (that relies on the user's selection of fields) at runtime.

I'm looking for a way that a query builds itself (to be specific the "where" part) according to what the user chooses during runtime. Is it possible?
Non-dynamic dynamic where clause:

create table foo (
  gender char(1),
  age smallint,
  blood_type varchar(50)
);

insert into foo values
('m', 40, 'o+'),
('m', 20, 'b-'),
('f', 30, 'b+');

set @gender = 'm';
set @age = 40;
set @blood_type = null;

select
*
from foo
where
  (@gender is null or gender = @gender)
  and (@age is null or age = @age)
  and (@blood_type is null or blood_type = @blood_type)


http://sqlfiddle.com/#!9/c9d888/3