Query to replace NULL values ​​in the table

advertisements

I have table like this,

Current Table1

id | car_name | model | year
---+----------+-------+-----
1  |a         | abc   | 2000
2  |b         | xyx   | 2001
3  |null      | asd   | 2003
4  |c         | qwe   | 2004
5  |null      | xds   | 2005
6  |d         | asd   | 2006

as you can see i have some null values , i want to replace them with the previous row values.

So it should become like this

Desired Table1

id | car_name | model | year
---+----------+-------+-----
1  |a         | abc   | 2000
2  |b         | xyx   | 2001
3  |b         | asd   | 2003
4  |c         | qwe   | 2004
5  |c         | xds   | 2005
6  |d         | asd   | 2006

I googled, but didn't find any solution for this.

Any suggestions always welcome.

Thanks in advance.


This query should work even if there are several records in a row with NULL

Query:

SQLFIDDLEExample

UPDATE Table1
SET car_name = (SELECT t1.car_name
                FROM (SELECT * FROM Table1) t1
                WHERE t1.id < Table1.id
                AND t1.car_name is not null
                ORDER BY t1.id DESC
                LIMIT 1)
WHERE car_name is null

Result:

| ID | CAR_NAME | MODEL | YEAR |
--------------------------------
|  1 |        a |   abc | 2000 |
|  2 |        b |   xyx | 2001 |
|  3 |        b |   asd | 2003 |
|  4 |        c |   qwe | 2004 |
|  5 |        c |   xds | 2005 |
|  6 |        d |   asd | 2006 |