Search code examples
mysqlsql-update

Having error when trying to use 'From' clause in an 'Update' statement in MySQL Workbench


I'm pretty new to SQL so sorry if this is a dumb question.

I have a large table containing most of the counties from every state with a median home listing price. Each county/state has multiple observations because it has a new observation for every quarter for the past five years. I'm trying to create a new column that has the percentage change in median listing price from the previous quarter. mySQL says that I have a syntax error, but I can't for the life of me figure it out. Any help is appreciated.

Here is my code:

UPDATE housing AS current
    SET price_change =((current.medListingPrice - previous.prevMLP)/ previous.prevMLP)*100
FROM
    (SELECT
        county,
        state,
        year,
        quarter,
        medListingPrice,
        LAG(medListingPrice) OVER (PARTITION BY county, state ORDER BY year, quarter) AS prevMLP
    FROM housing) AS previous
    WHERE current.county = previous.county
        AND current.state = previous.state
        AND current.quarter = previous.quarter
        AND current.year = previous.year;

Solution

  • UPDATE housing AS current
    JOIN (
        SELECT
            id,
            county,
            state,
            year,
            quarter,
            medListingPrice,
            LAG(medListingPrice) OVER (PARTITION BY county, state ORDER BY year, quarter) AS prevMLP
        FROM housing
    ) AS previous ON current.id = previous.id  -- Replace 'id' with the unique identifier column
    SET current.price_change = ((current.medListingPrice - previous.prevMLP) / previous.prevMLP) * 100;
    

    UPDATE statement in MySQL doesn't support the FROM clause directly so I use a subquery with the useful data