SQL Date

Syntax:

When creating a table, you can use the DATE data type to define a column that will store date values.

                                  
                                    CREATE TABLE table_name (
    column_name DATE,
    other_columns datatype,
    ...
);
                                  
                                

Example:

Let's create a table named appointments with a column named appointment_date to store date values:

                                  
                                    CREATE TABLE appointments (
    appointment_id INT PRIMARY KEY,
    appointment_date DATE,
    patient_name VARCHAR(50),
    doctor_name VARCHAR(50)
);
                                  
                                

In this example:

  • appointment_date is a column of type DATE.
  • It is used to store dates when appointments occur.

Inserting Data:

When inserting data into a table with a DATE column, you need to provide date values in the format 'YYYY-MM-DD'.

                                
                                    INSERT INTO appointments (appointment_id, appointment_date, patient_name, doctor_name)
VALUES
    (1, '2023-10-15', 'John Doe', 'Dr. Smith'),
    (2, '2023-10-20', 'Jane Doe', 'Dr. Johnson');
                                
                              

Retrieving Data:

You can use the SELECT statement to retrieve data based on date values or to format the date in the desired output format.

                                  
                                    SELECT *
FROM appointments
WHERE appointment_date >= '2023-10-15';
                                  
                                

This query retrieves all appointments that occur on or after October 15, 2023.

Current Date:

You can use the CURRENT_DATE function to get the current date.

                                  
                                    INSERT INTO appointments (appointment_id, appointment_date, patient_name, doctor_name)
VALUES
    (3, CURRENT_DATE, 'Sam Smith', 'Dr. Brown');
                                  
                                

This inserts a new appointment with the current date.


Tips:

  • Be consistent with the date format 'YYYY-MM-DD' when inserting or querying date values.
  • Use the appropriate functions or operators to compare or manipulate date values (e.g., CURRENT_DATE, DATEDIFF, DATEADD).
  • Be aware of time zone considerations when dealing with date values, especially in distributed systems.