Home > Mobile >  SQL Query Where Condition to find something based on date range
SQL Query Where Condition to find something based on date range

Time:02-11

New to the world of SQL and struggling with something that I'm sure is pretty simple. Is it possible to query a where condition to look for a date in the future based off a date range?

Example. Anything sold between 2022-02-01 - 2022-02-05 for delivery outside of 120 days from sale date.

CodePudding user response:

Your query will be something like this:

SELECT 
    *
FROM 
    table_name
WHERE 
    (2022-02-01 < date_sold < 2022-02-05) 
        AND 
   DATEADD(DAY,120,date_sold) < delivery_date;

You obviously need to put in your table name and column names and there will be variations depending on the database you are using.For example you might have to write

2022-02-01 < date_sold 
   AND
date_sold < 2022-02-05

CodePudding user response:

In Snowflake:

WITH data(sold_date, delivery_date, details) AS (
    SELECT * FROM VALUES
        ('2022-02-02',  '2022-03-02', 'too soon'),
        ('2022-02-02',  '2022-06-02', 'just right')
)
SELECT d.*
FROM data AS d
WHERE d.sold_date BETWEEN '2022-02-01' AND '2022-02-05'
    AND d.delivery_date >= DATEADD('day', 120, d.sold_date)

gives:

SOLD_DATE DELIVERY_DATE DETAILS
2022-02-02 2022-06-02 just right
  • Related