3

I need to apply a java regex on sql query string to calculate the count of it. I have to get what is between the "first select" and "from" of the principal query. This is my example :

Query :
select name,(select age from subtable), adress from table where name in (select name from subtable1)

Result :
select count(*) from table where name in (select name from subtable1)

I was using replaceFirst("^(.*?)from", "select count(*) from") but it is not working because there is an sql query in the attribute.

Please anyone can help ?

8
  • Are you sure that is the correct approach? I feel an XY problem here. Commented Apr 28, 2017 at 9:06
  • @Thomas, I need to get the count of the query without executing the original one, it is just a performance problem. If you have another approach, I'm all ears, thanks. Commented Apr 28, 2017 at 9:13
  • What kind of performance problems do you want to solve? In most cases really executing the query should provide the best information especially since you could do the count on the results. Any alteration of the query is likely to falsify the information anyways. So if you're after a general indicator on query performance wouldn't a simple EXPLAIN <query> be sufficient? And since you've also added the hibernate tag: AFAIK Hibernate can collect a bunch of statistics that might help as well. Commented Apr 28, 2017 at 9:20
  • @Thomas, I need to get only the count information which will be used for pagination. Executing the whole query (20 attributes or more) is really expensive. All I want is to get the count directly by altering the query. Commented Apr 28, 2017 at 9:26
  • 1
    If it's for pagination it might be safer to dynamically build 2 queries with the same from clause (we're using a similar approach). Alternatively, some databases support returning the count of the query even if you just load a page (via offset and limit) thus it could be done in one query. Altering queries using regular expressions is very risky imo. Commented Apr 28, 2017 at 10:37

1 Answer 1

1

You can solve your problem using this regex ^(.*?)from(?![^(]*\\)):

str = str.replaceFirst("^(.*?)from(?![^(]*\\))", "select count(*) from");

Output

select count(*) from table where name in (select name from subtable1)

The idea is match from that is inside () parenthesis.


Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.