I have a SQL query and I want to know how many rows will that SQL query return. Now the problem is that I want to know the number of results beforehand which means before running the SQL query.
I would have done this easily by ResultSet.getRow()
to get the total number of rows from resultset. But as per the requirement, I can get the resultset only after knowing the number of rows to be returned by that query.
I tried the below Java Regex to solve the issue:
String orgQuery = "select * from emp where id<1210 and salary>55000;"
Pattern p= Pattern.compile("(?:)from\\s+(.*)*" , Pattern.CASE_INSENSITIVE);
Matcher m= p.matcher(orgQuery);
if (m.find()) {
countQuery = "SELECT COUNT(*) as total "+ m.group(1);
System.out.println(countQuery);
}
This work perfectly file and I get the "countQuery" as:
SELECT COUNT(*) as total from emp where id<1210 and salary>55000
By this I can easily know the number of rows to be returned beforehand but the problem occurs when my query become more complex like these two:-- even more complex in case of nested queries i.e. #query2.
#query1: select * from emp where id<1210 and salary>55000 order by dept, salary desc;
#query2: select name from emp where id IN (select id from emp where id < 1210 group by salary , id order by id ASC limit 10) order by id DESC limit 10
I think the main issue is with "Order By" clause. I can remove the "Order By" clause too by below regex:
Pattern.compile("(?:)from\\s+(.*)*" , Pattern.CASE_INSENSITIVE);
But it becomes more complex in case of Nested queries.
Can any Java Regex expert help????? I am using postgres as DB.