You're very close, but your query has a syntax error: the JOIN clause must come before the ORDER BY and LIMIT.
Here's the corrected and optimized version of your query:
SELECT *
FROM FORMDATARAW
JOIN FORMSCHEMA
ON FORMSCHEMA.IDX LIKE CONCAT(FORMDATARAW.FORM_IDX, '%')
ORDER BY FORMDATARAW.SAVED_DT DESC
LIMIT 10;
⚡ Performance Optimization Tips
Since you mentioned that the query is not running at all, and you want it to run as fast as possible, here are some performance considerations:
1. ✅ Fix Join Order (Optional for Performance)
If FORMDATARAW is much smaller than FORMSCHEMA, keep it as-is.
But if FORMSCHEMA is smaller or more selective, consider switching the join order:
SELECT *
FROM FORMSCHEMA
JOIN FORMDATARAW
ON FORMSCHEMA.IDX LIKE CONCAT(FORMDATARAW.FORM_IDX, '%')
ORDER BY FORMDATARAW.SAVED_DT DESC
LIMIT 10;
This can help the optimizer process fewer rows early on.
2. 🔍 Indexing Suggestions
The biggest performance hit comes from the LIKE CONCAT(FORMDATARAW.FORM_IDX, '%') — this is a prefix match, which can be slow without proper indexing.
These will speed up lookups in both tables.
3. 🧠 Consider Full-Text Search (Advanced)
If prefix matching is frequent and performance remains an issue, consider using generated columns + indexing or full-text search (depending on your DB engine).
For example in MySQL:
ALTER TABLE FORMDATARAW ADD COLUMN form_prefix VARCHAR(255) GENERATED ALWAYS AS (FORM_IDX) STORED;
CREATE INDEX idx_formdataraw_prefix ON FORMDATARAW(form_prefix);
-- Then use:
SELECT *
FROM FORMDATARAW
JOIN FORMSCHEMA
ON FORMSCHEMA.IDX LIKE CONCAT(FORMDATARAW.form_prefix, '%')
ORDER BY SAVED_DT DESC
LIMIT 10;
💡 Alternative: Use a Subquery for Speed
If you only need the latest 10 records from FORMDATARAW, and then find matches in FORMSCHEMA, this version might be faster:
SELECT *
FROM (
SELECT *
FROM FORMDATARAW
ORDER BY SAVED_DT DESC
LIMIT 10
) AS recent_raw
JOIN FORMSCHEMA
ON FORMSCHEMA.IDX LIKE CONCAT(recent_raw.FORM_IDX, '%');
This limits the number of rows being joined from FORMDATARAW first, reducing the total number of comparisons.
✅ Final Fast Query Example:
SELECT *
FROM (
SELECT *
FROM FORMDATARAW
ORDER BY SAVED_DT DESC
LIMIT 10
) AS recent_raw
JOIN FORMSCHEMA
ON FORMSCHEMA.IDX LIKE CONCAT(recent_raw.FORM_IDX, '%');
Let me know your database engine (MySQL, PostgreSQL, SQL Server, etc.), and I can tailor the optimizations even more!