Question

I'm setting up a database that will hold all sorts of equipment, and one of the entities holds warranty information for this equipment. One of the attributes I want is an 'Is_Valid' derived attribute that will basically be 'not valid' or 'valid' depending on if the end date of the warranty terms has passed.

I was able to do this in SQL with this query:

CREATE TABLE Warranty(
    Warranty_ID     varchar(5),
    Begin_Date      date,
    End_Date        date,
    Terms           varchar(15),
    Is_Valid as (IIF((GetDate() > Begin_Date) AND (GetDate() < End_date), 'valid','not valid')),
    Primary Key (Warranty_ID));

However, I've been trying to accomplish this in MySQL, but I cannot get it to work. The only way I got it to work was using an UPDATE Warranty query using case, but I'd rather the database do this automatically. If I'm understanding something wrong please forgive me, because I am new to database structure and implementation. Thanks.

Was it helpful?

Solution

To begin with, in MySQL dialect GetDate() becomes CURDATE() and IIF becomes IF.

Furthermore, I suggest that you use BETWEEN for checking for a range of values: this changes the behavior on Begin_Date and End_Date (the warranty will be valid including these dates) but maybe this is also what you'd prefer.

You could use a table and a view on the top of it as the following:

CREATE TABLE Warranty(
    Warranty_ID     varchar(5),
    Begin_Date      date,
    End_Date        date,
    Terms           varchar(15),
    Primary Key (Warranty_ID));

CREATE VIEW vw_Warranty AS
SELECT
    Warranty_ID,
    Begin_Date,
    End_Date,
    Terms,
    IF(CURDATE() BETWEEN Begin_Date AND End_date, 'valid', 'not valid') as IS_Valid;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top