Friday, 13 October 2023

MySQL Date Examples

Here are some examples of MySQL date values:

  • 2023-10-13
  • 2023-10-13 12:00:00
  • 2023-10-13 12:00:00.123456
  • 1970-01-01
  • 9999-12-31

MySQL also supports date literals, which are enclosed in single quotes. For example, the following statement assigns the value 2023-10-13 to the variable date_var:

SQL
SET date_var = '2023-10-13';

You can use date values in a variety of SQL statements, such as:

  • SELECT statements to filter the results of a query based on date criteria.
  • INSERT statements to insert new rows into a table with date columns.
  • UPDATE statements to update the date values in existing rows in a table.
  • DELETE statements to delete rows from a table based on date criteria.

Here are some examples of SQL statements that use date values:

SQL
# Select all rows from the `orders` table where the `order_date` column is greater than or equal to '2023-10-13'.
SELECT * FROM orders WHERE order_date >= '2023-10-13';

# Insert a new row into the `customers` table with the `created_at` column set to the current date.
INSERT INTO customers (name, email) VALUES ('John Doe', 'john.doe@example.com') SET created_at = CURRENT_DATE;

# Update the `order_date` column in the `orders` table for the row with the `order_id` of 1 to '2023-10-13'.
UPDATE orders SET order_date = '2023-10-13' WHERE order_id = 1;

# Delete all rows from the `orders` table where the `order_date` column is less than '2023-10-13'.
DELETE FROM orders WHERE order_date < '2023-10-13';

MySQL also supports a variety of date functions, which can be used to manipulate date values. For example, the following statement returns the current date:

SQL
SELECT CURRENT_DATE();

The following statement calculates the number of days between two dates:

SQL
SELECT DATEDIFF('2023-10-13', '2023-10-10');

MySQL date values and date functions are powerful tools for working with date and time data in your database. By using date values and date functions, you can easily store, retrieve, and manipulate date and time data in a variety of ways.

No comments:

Post a Comment