Horje
SQL Query to Compare Results With Today's Date

To compare query results with today’s date, use the CASE() function with the SQL GETDATE() function.

SQL GETDATE() function is used to return the present date and time of the database system and the CASE() function can used to compare two dates in SQL.

Query to check the current date in SQL:

SELECT GETDATE();

Output:

get current date in SQL

SQL Compare Results With Today’s Date Example

Let’s look at an example of comparing result with today’s date in SQL.

Query to create a demo database and table.

CREATE DATABASE geeks;
USE geeks;
CREATE TABLE demo_table(
NAME VARCHAR(20),
ITEM varchar(20),
date DATE);

INSERT INTO demo_table 
VALUES ('Romy','shirt','2021-10-21'),
('Shalini', 'shoes', '2021-10-14'),
('Sambhavi','hat','2021-10-10'),
('Pushkar','mobile','2021-11-21'),
('Nikhil','home_decor','2021-09-09');
SELECT * FROM demo_table;

Output:

demo sql table

Compare the result with today’s date in SQL

For this, we will return a column named ‘After comparison’ which returns a value after comparing today’s date with the value in the ‘Deliver’ column. After comparison column contains the following string:

  • Lesser than- If the date is less than today’s date
  • Greater- If the date is greater than today’s date
  • Today- If the date is the same as today’s date.

Query:

SELECT NAME, ITEM,date,
CASE  
    WHEN date=GETDATE() THEN 'Today'
    WHEN date<GETDATE() THEN 'Lesser'
    ELSE 'Greater'  
END AS "AFTER COMPARISON"
FROM demo_table;

Output:

output




Reffered: https://www.geeksforgeeks.org


SQL

Related
SQL Query to Convert Date to Datetime SQL Query to Convert Date to Datetime
SQL - Logical Operators SQL - Logical Operators
How to Export SQL Server Data to a CSV File? How to Export SQL Server Data to a CSV File?
SQL - Using GROUP BY to COUNT the Number of Rows For Each Unique Entry in a Column SQL - Using GROUP BY to COUNT the Number of Rows For Each Unique Entry in a Column
How to Use NULL Values Inside NOT IN Clause in SQL? How to Use NULL Values Inside NOT IN Clause in SQL?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13