Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use MAX in update statement using sql?

i am trying to use the MAX function in sql statement. Here is what i am trying to do: something like this:

UPDATE MainTable
        SET [Date] = GETDATE()

        where [ID] = Max

I know this is wrong specially where i put the where condition but cannot figure out how to use max and update in the same statement. thanks

like image 880
user1858332 Avatar asked Jan 03 '13 20:01

user1858332


People also ask

Can we update more than one value using update statement?

The UPDATE statement is capable of updating more than one row.

Can we use MAX function for date in SQL?

MAX function works with “date” data types as well and it will return the maximum or the latest date from the table.

Can we use having clause in update statement?

The Having clause is used only with the Select statement The Having clause can be used only with a Select statement. If you use the Having clause with an update or delete query in SQL, it will not work.


Video Answer


3 Answers

UPDATE MainTable
   SET [Date] = GETDATE()
 where [ID] = (SELECT MAX([ID]) FROM MainTable)
like image 155
zerkms Avatar answered Nov 17 '22 00:11

zerkms


One way

DECLARE @MaxID INT = (select MAX(id) FROM MainTable)

UPDATE MainTable
        SET [Date] = GETDATE()
        where [ID] = @MaxID

That is SQL 2008 syntax, in 2005 you need to do the declaraion and assignment of the variable in two steps

You could also use a common table expression

;WITH cte
AS (
SELECT TOP 1 * FROM MainTable
ORDER BY ID DESC

)

UPDATE cte SET [Date] = GETDATE()

Example you can run

CREATE TABLE testNow(id int)
INSERT testNow VALUES(1)
INSERT testNow VALUES(2)

;WITH cte
AS (
SELECT TOP 1 * FROM testNow
ORDER BY ID DESC

)

-- id with 2 will become 5
UPDATE cte SET ID = 5

SELECT * FROM testNow

Output

1
5
like image 38
SQLMenace Avatar answered Nov 17 '22 01:11

SQLMenace


UPDATE MainTable
SET [Date] = GETDATE()
WHERE [ID] = (SELECT MAX(your column) FROM yourtable)
like image 32
Melanie Avatar answered Nov 17 '22 01:11

Melanie