2
First good afternoon, I work specifically with Java in the Back-end using Webservices Rest and Postgresql, after some professional enhancements I was instructed to pass ordering and pagination of my application to SQL, that would burden the application server less and the results would return in an agile way. So far paging was not the problem, I could use FETCH or LIMIT to be able to control it, but I reached an impasse when I went ahead to sort. Using CASE in ORDER BY in SQL could not use it dynamically to sort different typing columns. Follow the example:
SELECT
a.idade,
a.nome,
a.cpf
FROM
cadastro a
ORDER BY
(
CASE 1 WHEN 1 THEN
a.idade
WHEN 2 THEN
a.nome
WHEN 3 THEN
a.cpf
END
)
This example quoted above would not successfully execute columns that are not of the same type. And doing several CASE would not be cool and productive to set so many parameters in Java Prepared. I asked in the SQL community and they guided me to do the scripts in functions and pass sort as parameter, but I did not find this form very attractive. So I thought about String formatting before moving to Prepared, but it is susceptible to SQL Injection and I certainly do not want to risk this option.
So I ask for tips, I thank you already!
Obs.: About having mentioned XY problem. I tried to do CASE in SQL as mentioned above and thought about the hypothesis of mounting the script in Function and view, but it is not a solution that pleased my boss, conversion of types would not work for all cases of scripts system, so I am looking for alternative solutions. String concatenation before sending to Preparedstatement also thought, however how to avoid an SQL Injection?
I’m not sure I understand what you’re trying to do, but it seems to me to be a case of a XY problem. It would not be better if you just assemble 3 different Sqls queries, one ordering by age, one ordering by name and one ordering by CPF and let the application choose which of these queries will be sent to the database, as the case may be?
– Victor Stafusa
try SELECT a.age, a.name, a.Cpf FROM register a ORDER BY ( CASE 1 WHEN 1 THEN lpad(a. age, 3, '0') WHEN 2 THEN a.name WHEN 3 THEN a.Cpf END )
– Motta
Does sorting come according to the sequence of fields per parameter? Wouldn’t it be simpler for you to pass the field?
– karanalpe
@Victorstafusa in my view could be a better solution than this. If every system script I go to do server side ordering I do this, it will be nonproductive.
– Dorcílio Neto
@Motta is not a suitable solution, do conversion.
– Dorcílio Neto
@Karanalvespereira Preparedstatment does not accept column name pass.
– Dorcílio Neto