Alternatives to Common Table Expressions in IRIS
Hi everybody,
I am writing an SQL query of the following form:
SELECT
(SELECT COUNT(*) FROM DataTable WHERE Condition1 AND Condition2),
(SELECT COUNT(*) FROM DataTable WHERE Condition1 AND Condition3),
(SELECT COUNT(*) FROM DataTable WHERE Condition1 AND Condition4),
(SELECT COUNT(*) FROM DataTable WHERE Condition1 AND Condition5),
user.id
FROM UserTable userwhere Condition1 depends on user and is the same for all four COUNT(*) subqueries. This query is very slow, and I believe that it can be sped up significantly if Condition1 would be checked once rather than four times. With a Common Table Expression, the query could select based on Condition1 once and then reuse the results:
WITH cte AS (
SELECT id
FROM DataTable
WHERE Condition1
)
...However, as far as I know, IRIS does not support Common Table Expressions. Is it possible to achieve similar results using the functionality available in IRIS? Thanks!
Comments
UserTable and DataTable are related? I'm guessing that if Condition1 is the relation between the tables you would try this query:
SELECT
COUNT(CASE WHEN data.a = "Condition1" then 1 ELSE NULL END) as "ValueA",
COUNT(CASE WHEN data.b = "Condition2" then 1 ELSE NULL END) as "ValueB",
COUNT(CASE WHEN data.c = "Condition3" then 1 ELSE NULL END) as "ValueC",
user.id
FROM UserTable user left join DataTable data on user.id = data.userThanks, that did what I needed! You are right, part of Condition1 is the relation between the tables, but it also includes conditions on UserTable and DataTable (it's a conjunction of three sub-conditions). adding the join and a where clause after it took care of all of them.
awesome! So glad this led you to a solution :)
Hi, I don't think CTEs would help here, as you still should make sure to include the fields required for the Condition2-5. I think @Luis Angel Pérez Ramos suggestion is the right way to go, using a JOIN and then CASE statements in the COUNT. If you can provide more details on the two tables and exact conditions, I'm sure we can help with the actual query you'll need.
CTEs are also mostly there for readability and wouldn't impact query performance by themselves. It's worth checking out if there aren't any opportunities for indices to speed up the JOIN and Condition1 parts.
All this said, we are planning to add CTE support to IRIS SQL in the near term.
my tool irissqlci supports CTE (except recursive). As well as SQLAlchemy with SQLAlchemy-IRIS