Merrill
Merrill

Reputation: 21

Conditional values for calculated column in MySql

I'm trying to calculate the difference between two date columns, which works just fine as:

select (ship_date - due_date) AS DaysTaken;

Basically, I want to determine if orders were shipped on time and, if not, how many days late. This works fine, as expected, except, if the order is shipped early, I get a negative number. What I'd like to do is to evaluate the results and return 0, if it calculates a negative value.

I don't know how to do this in a MySQL select statement. Can anyone help?

Upvotes: 2

Views: 1077

Answers (2)

Quassnoi
Quassnoi

Reputation: 425341

SELECT  GREATEST(ship_date - due_date, 0) AS DaysTaken

Upvotes: 1

Ike Walker
Ike Walker

Reputation: 65537

You can use the GREATEST() function to replace negative numbers with 0:

select GREATEST((ship_date - due_date),0) AS DaysTaken;

Upvotes: 2

Related Questions