SQL DATE() function Example
Welcome readers, in this tutorial, we will learn how to use the DATE()
function in SQL.
1. Introduction
In SQL, dates are a complicated feature for the developers, and working with them is a complex thing as the format of the date in the database table must match the date format required for the SQL insert operation to work.
- The
DATE()
function in SQL extracts the date part from the date/time expression - The
DATE()
expression returns a valid date value and returns NULL if the expression is not a date or a DateTime
To start with this tutorial, I am hoping that users at present have their preferred database installed on their machines. For easy usage, I am using MySQL on a Windows operating system. If someone needs to go through the MySQL installation, please watch this video.
2. SQL DATE() function Example
The following tutorial will illustrate the different syntax for the DATE()
function.
2.1 Create a Table
Readers can use the following script to create a table named – employee
in a database named – jcg
and add some sample data to it.
Query 1
01 02 03 04 05 06 07 08 09 10 | /* QUERY 1 = CREATING A TABLE AND ADDING RECORDS INTO IT. */ create table employee (id INT , first_name VARCHAR (50), last_name VARCHAR (50), date_of_birth DATE ); insert into employee (id, first_name, last_name, date_of_birth) values (1, 'Ginnie' , 'Searsby' , '2020-01-19 04:41:02' ); insert into employee (id, first_name, last_name, date_of_birth) values (2, 'Pearle' , 'Tresvina' , '2020-07-21 07:36:51' ); insert into employee (id, first_name, last_name, date_of_birth) values (3, 'Sergio' , 'Caunce' , '2020-04-27 18:06:30' ); insert into employee (id, first_name, last_name, date_of_birth) values (4, 'Jules' , 'Faulkener' , '2019-12-09 07:34:12' ); insert into employee (id, first_name, last_name, date_of_birth) values (5, 'Cathyleen' , 'Grieveson' , '2019-11-12 19:35:13' ); select * from employee; |
If everything goes well, the employee
the table will be created, and the data will be displayed.
2.2 Using the DATE() function
Programmers can use the following script to have a DATE()
function understanding.
Query 2
1 | select first_name, date (date_of_birth) as dob from employee; |
If everything goes well, the query result will be shown.
That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!
3. Summary
In this section, we learned:
- How to use the
DATE()
function - Steps required to set up the MySQL database on a Windows operating system
You can download the sample script in the Downloads section.
4. Download the SQL Script
This was an example of DATE()
function in SQL.
You can download the full source code of this example here: SQL DATE() function Example