'Can you use objects in SQL like you can in R for strings/dates to avoid typing the information each time?
I'm new to SQL, and I'm trying to determine if you can define objects in it like you can in R. For instance, I have a query where I need to make sure the date is the same in each table.
SELECT *
FROM table_1 AS t1
WHERE t1.date = '2021-02-14'
LEFT JOIN table_2 AS t2
ON t1.id = t2.id
WHERE t2.date = '2021-02-14';
I want to run this query over and over, but it's cumbersome to change the date each time and opens the chance for typos. If this were R, I could do something like:
my_date <- '2021-02-14'
SELECT *
FROM table_1 AS t1
WHERE t1.date = my_date
LEFT JOIN table_2 AS t2
ON t1.id = t2.id
WHERE t2.date = my_date;
And only have to change it in one place. Is something like this possible in SQL? If not, what would you recommend as the easiest way to avoid copy-and-pasting or using Control + F.
Currently, my main focus is on dates, but if you have a solution that would work for any data type (i.e., a number value that's used in many WHERE statements), that'd be awesome.
Solution 1:[1]
Update:
A coworker shared with me his solution that works and is extendable beyond dates. You make a common-table expression (CTE) at the start of your query that contains your filters. Then, plug it in throughout, so you only need to change it in one place. For instance:
WITH filt AS (
SELECT
*
FROM (
VALUES
('2021-02-14')
) AS tbl (date_filter)
)
SELECT
*
FROM table_1
WHERE
date IN (
SELECT
date_filter
FROM filt
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | J.Sabree |