SQL UPDATE DATE
The SQL UPDATE DATE statement allows you to modify date values in a table. This is useful for correcting incorrect dates or updating timestamps for specific records. The date values can be updated dynamically using date functions.
Example
In this example, the date of an order is updated in the OrderDetails table.
Code Example
-- Add a new column for order dates
ALTER TABLE Orders
ADD OrderDate DATE;
-- Update the date for specific orders
UPDATE Orders
SET OrderDate = '2024-11-21'
WHERE Product = 'Tablet';
-- View the updated table
SELECT * FROM Orders;
Output
Product | Category | Price | OrderDate |
---|---|---|---|
Laptop | Electronics | 1300.00 | NULL |
Phone | Mobile Devices | 800.00 | NULL |
Tablet | Gadgets | 600.00 | 2024-11-21 |
Smartwatch | Gadgets | 250.00 | NULL |
Headphones | Gadgets | 150.00 | NULL |
Camera | Electronics | 500.00 | NULL |
Explanation
- The ALTER TABLE statement adds a new column OrderDate to the Orders table.
- The UPDATE statement sets the date for the "Tablet" product.
- The updated table shows the new date for the specified product while other rows remain unaffected.