I'm relatively new to SQL and I find my self wanting macros in SQL a lot.
Consider:
SELECT
session_id,
user_id,
hitnumber,
IF(
eventinfo.eventcategory = 'search' AND eventinfo.eventaction = 'RunSearch',
TRUE, FALSE
) issued_search,
FROM google_analytics.hits
JOIN (
SELECT
session_id
FROM google_analytics.hits
WHERE eventinfo.eventcategory = 'search' AND eventinfo.eventaction = 'RunSearch'
GROUP BY session_id
) sessions_with_search ON hits.session_id = sessions_with_search.session_id
Note that eventinfo.eventcategory = 'search' AND eventinfo.eventaction = 'RunSearch'
is repeated twice in the query. This clause represents rows that are search rows. Soon I will want to expand the notion of search row to include a very long list of OR'ed clauses that look like this. I don't want to repeat this in 2 places. Moreover I think it's a good source of bugs to repeat the same SQL in 2 places – I might change one place and not the other without thinking about it.
I want a notion of a macro, but to my knowledge these don't exist. I want to be able to specify this above the query
SEARCH_HIT=`eventinfo.eventcategory = 'search' AND eventinfo.eventaction = 'RunSearch'`
And then the query above would become:
SELECT
session_id,
user_id,
hitnumber,
IF(@SEARCH_HIT, TRUE, FALSE) issued_search,
FROM google_analytics.hits
JOIN (
SELECT
session_id
FROM google_analytics.hits
WHERE @SEARCH_HIT
GROUP BY session_id
) sessions_with_search ON hits.session_id = sessions_with_search.session_id
The query is already cleaner but imagine how much clearer and more maintainable the macro makes the query when @SEARCH_HIT is 20 clauses long.
Questions
- Do SQL macros exist in any IDEs?
- Do SQL macros exist in any SQL languages?
- Do SQL macros exist in any Presto SQL in particular?
- If macros do not exist then why not? And what do we replace them with for the sake of query maintainability?