Using alias from COALESCE from SELECT in WHERE clause

Michi :

DB Fiddle

CREATE TABLE logistics (
    id int primary key,
    campaign VARCHAR(255),
    inbound_date VARCHAR(255),
    outbound_date VARCHAR(255)
);

INSERT INTO logistics
(id, campaign, inbound_date, outbound_date)
VALUES 
("1", "C001", "2019-01-01", "2019-02-08"),
("2", "C001", "2019-05-10", "2019-05-12"),
("3", "C001", "2019-06-12", "2019-06-15"),
("4", "C001", "2019-08-13", "2019-08-20"),
("5", "C001", "2019-11-14", "2019-11-22");

In the table above I have the columns inbound_date and outbound_date for date values.
In my query I coalesce them to one column called event_date.

Now, I want to use the alias for the coalesce in the WHERE clause of my query but I get error Unknown column 'event_date' in 'where clause':

SELECT
campaign,
coalesce(inbound_date, outbound_date) as event_date
FROM logistics
WHERE
event_date BETWEEN "2019-06-01" AND "2019-10-01"

I know I could solve the issue by using the inbound_date and outbound_date as two seperate conditions in the WHERE clause but isn't there a smarter way using the alias of the coalesce?

Gordon Linoff :

You can repeat the expression or use a having clause:

SELECT campaign,
       coalesce(inbound_date, outbound_date) as event_date
FROM logistics
HAVING event_date BETWEEN '2019-06-01' AND '2019-10-01';

I don't recommend a subquery in MySQL. MySQL has a tendency to materialize subqueries (although this has improved with more recent versions). That can impede optimization.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19343&siteId=1