Criteria to SQL Converter
Difficulty: Hard · Topics: Recursion, SQL, Parsing, Tree · Acceptance: 100.0% of 1 submissions
Difficulty: Hard | Tags: SQL, Parsing, Tree, Recursion
Description
Given a criteria object (similar to Zoho CRM API criteria), convert it to a SQL WHERE clause.
A criteria object has the structure:
{
"group_operator": "and",
"group": [
{"field": "name", "comparator": "equals", "value": "Alice"},
{"field": "age", "comparator": "greater_than", "value": 25},
{
"group_operator": "or",
"group": [
{"field": "city", "comparator": "equals", "value": "NYC"},
{"field": "city", "comparator": "equals", "value": "LA"}
]
}
]
}
Implement:
criteriaToSQL(criteria) → String
Examples
Example 1:
Input:
{"field": "name", "comparator": "equals", "value": "Alice"}
Output: "name = 'Alice'"
Example 2:
Input:
{
"group_operator": "and",
"group": [
{"field": "age", "comparator": "greater_than", "value": 25},
{"field": "status", "comparator": "equals", "value": "active"}
]
}
Output: "(age > 25 AND status = 'active')"
Example 3 — Nested:
Input: (the full example above)
Output: "(name = 'Alice' AND age > 25 AND (city = 'NYC' OR city = 'LA'))"
Supported Comparators
| Comparator | SQL |
|---|---|
equals | = |
not_equals | != |
greater_than | > |
less_than | < |
greater_equal | >= |
less_equal | <= |
contains | LIKE '%value%' |
starts_with | LIKE 'value%' |
ends_with | LIKE '%value' |
is_null | IS NULL |
is_not_null | IS NOT NULL |
in | IN (...) |
Constraints
- Nesting depth ≤ 5.
- String values must be SQL-escaped (prevent SQL injection with parameterized output or proper escaping).
group_operatoris either"and"or"or".
Hints
Hint 1
Recursively process: if the node has a group field, recurse into each item and join with the operator. Otherwise, it's a leaf — convert the single condition.