Skip to content
Advertisement

How to find the condition of SQL WHERE clause pragmatically

I have created an API Gateway that will accept an SQL statement, run the statement against the database and return its result as a response. For every SQL statement, I receive as input I have to append a WHERE condition in the SQL. For example:-

Input SQL- SELECT * FROM contacts WHERE last_name = ‘Johnson’;

Append Condition- country = ‘India’

New SQL- SELECT * FROM contacts WHERE last_name = ‘Johnson’ AND (country = ‘India’);

For the above SQL, it was easy to find the WHERE keyword and its condition as it was at the end. But for some SQL we can have OFFSET, HAVING, ORDER BY, GROUP BY, FETCH NEXT and many more after the WHERE. So, cannot find a robust way to find out the WHERE condition and append to it.

Possible usage of WHERE is as below-

One approach would be to list down all the keywords that come after WHERE to find its condition. But I want to check if there is any better approach for this. Any suggestions or documents will be appreciated.

Advertisement

Answer

Use subqueries:

So, this query becomes:

If you find that you also need to append an ORDER BY/OFFSET, I would recommend passing that in as a separate argument — as you do with the WHERE.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement