How to select value from table with current date - mysql

I am trying to pull the value from the 'dwgm_10am_final_price' column with today's current date (2021-01-06). In this case it will be null until a value is inserted into the table at 10am. as depicted in the image below.
This is the current query I am trying but it is returning 'No Data' on my Grafana dashboard. How can I edit my query to always pull the data with today's timestamp, regardless of it is NULL or a numerical value.
SELECT gas_date AS time, dwgm_10am_final_price
FROM gas_market_prices
WHERE DATE('time') = CURDATE()

You are trying to get a date from the String time, which doesn't exist
You need to use backticks for your query
SELECT gas_date AS time, dwgm_10am_final_price
FROM gas_market_prices
WHERE DATE(`time`) = CURDATE()
You can read this canonical thread When to use single quotes, double quotes, and backticks in MySQL

Related

How to convert a date in an order by statement? (MySQL)

I'm trying to order my results by date, but the dates are strings, not date objects, so the results aren't showing up properly. I tried converting the date string to a date object in the sql request, but now nothing returns. There are no results showing on the screen. Here's my code:
SELECT * FROM tblnewsftb
WHERE Status = 'Active'
ORDER BY CONVERT(datetime, ItemDate, 102) DESC
What am I doing wrong?
In MySQL, CONVERT() only takes two arguments, the expression and a data type. The data type goes second.
Example:
CONVERT(ItemDate, DATETIME)
But this will work only if the expression (your ItemDate column in this example) is convertible as-is to a DATETIME. I would guess you're using some date format that MySQL doesn't support, like 'MM/DD/YYYY' or something else.
You'll have to use STR_TO_DATE() if you have a custom format.
Example:
STR_TO_DATE(ItemDate, '%m/%d/%Y')
It would really be best if you store datetime values in a proper DATETIME column instead of a string column if you want them to sort correctly.

Why is my AND statement not working in MySQL/PHPMyAdmin

I am trying to retrieve tickets from a database that are created in the last 6 weeks. Therefore i am trying to use an delimiter which filters that period but the database time is based on an UNIX timestamp and i want to search on a logical date.
I've tried date(), timestamp(), CAST() in the last line of my query but most throw errors or don't actually filter the wanted results
SELECT ticket,
company,
title,
status,
department,
user,
(FROM_UNIXTIME(timestamp,"%d-%m-%Y")) AS 'Start date',
(FROM_UNIXTIME(close_time,"%d-%m-%Y")) AS 'Close date'
FROM ticket_database
WHERE department IN ('stack_mysql')
**AND DATE_FORMAT(timestamp,'%d-%m-%Y') > '11-02-19'**
;
I expect that all tickets created on or after 11-02-19 are shown but instead it ignored this date and throws everything at me since 2006.
Help is appriciated
It is not the best idea to use a function on a field in the WHERE Clause. This will generate a FULL TABLE SCAN. MySQL must read each ROW, run the function and the compare.
Better is to use the function on the constant part of the compare, but here
is it is not nesecary
SELECT ticket,
company,
title,
status,
department,
user,
(FROM_UNIXTIME(`timestamp`,"%d-%m-%Y")) AS 'Start date',
(FROM_UNIXTIME(close_time,"%d-%m-%Y")) AS 'Close date'
FROM ticket_database
WHERE department IN ('stack_mysql')
AND `timestamp` > unix_timestamp('2019-02-11 00:00:00');
Note: Make your life easier. Dont use reserved Keywords like timestamp not as fieldnames. if you do that you must quote it in backticks
You have a couple of issues. Firstly, based on this line:
(FROM_UNIXTIME(timestamp,"%d-%m-%Y")) AS 'Start date',
the timestamp column is a unix timestamp, not a date and thus can't be passed to DATE_FORMAT. Secondly, 11-02-19 is not a valid MySQL date format and thus can't be compared to a date directly; you need to use STR_TO_DATE to convert that to a date instead. So, to make it work, try this:
AND FROM_UNIXTIME(timestamp) > STR_TO_DATE('11-02-19', '%d-%m-%y')
To allow MySQL to use an index on the timestamp column, remove the FROM_UNIXTIME call and convert the date into a timestamp instead:
AND timestamp > UNIX_TIMESTAMP(STR_TO_DATE('11-02-19', '%d-%m-%y'))

Date between query in mysql not generated correct output

I stored date field as Varchar.
When I use this query :
SELECT date
FROM g_m_tit
WHERE date BETWEEN '01.10.2015' AND '31.10.2015';
it generates the wrong output, as shown below
With VARCHAR column, comparing to strings, that will be a character by character comparison, from left to right.
If you want string comparisons to be used for "date" comparisons, the date values will need to be stored in a consistent and canonical format, with the year first, then the month, then the day. e.g. '2016.01.13'.
MySQL provides datatypes other than VARCHAR specifically for storing date and time values... DATE, DATETIME, TIMESTAMP.
Dealing with date values stored in VARCHAR columns, in the format you have, is going to be some messy SQL. And MySQL is going to have to scan all rows to evaluate the expression; it won't be able to use a range scan operation.
One way to do it is to convert the strings into DATE values, and compare the DATE values.
WHERE STR_TO_DATE(`date` ,'DD.MM.YYYY')
BETWEEN STR_TO_DATE('01.10.2015','DD.MM.YYYY')
AND STR_TO_DATE('31.10.2015','DD.MM.YYYY')
If there are any string values in date that can't be converted to a DATE, because the format doesn't match the specification, or an "invalid" date value, e.g. 32.13.2015, the STR_TO_DATE function will return a NULL or throw an error (depending the SQL_MODE setting).
In your image note how the first 2 characters are between '01' and '31'. The between operator works on varchars using varchar "rules" e.g. '19' IS between '01' and '31' and that is why you are getting unwanted results. You are expecting date rules to be applied but your expectation isn't accurate.
Do not store dates as a string; but if you simply had to do it for some reason only a sequence such as YYYYMMDD allows you to reliably use between.
If you persist in storing the column as varchar with the pattern dd.mm.yyyy then try these:
SELECT
`date`
FROM g_m_tit
WHERE str_to_date(`date`,'%d.%m.%Y') BETWEEN '2015-10-01' AND '2015-10-31';
SELECT
`date`
FROM g_m_tit
WHERE str_to_date(`date`,'%d.%m.%Y') >= '2015-10-01')
AND str_to_date(`date`,'%d.%m.%Y') < '2015-11-01';
both of these, as you can see, force you into changing the data, and you would need to do that every time you reference that "date" column - that is very inefficient.
Also, date is a reserved word, please avoid using such words as column names.
A final note: I prefer the second query above as I never use between for date ranges.
create new column with "date" or "bigint" type
Update all rows inserting value from old column to new (based on new column type)
Delete old column
Rename new one to "g_m_tit"
do not use varchar for dates! It causing probelms as u can see and its slower than date/bigint
To store date in:
"varchar(10)" u need 11 bytes + charset collate every query
"bigint" u need 8 bytes (available range condition)
"date" u need 3 bytes (available range, by part of date conditions and much more )

How to run a query with date from a form?

I have a select query that returns records based on 2 dates from a form - >=Forms!frmReport!StartDate AND <=Forms!frmReport!EndDate.
The problem is that whenever the user enters the same date in the both StartDate and EndDate no record is returned even though I'm sure there is data in the table that matches the criteria. Can anyone say why the query isn't returning any information?
Cast the form values to just date values in your query:
>= cdate(Forms![frmReport]![StartDate]) and <= cdate(Forms![frmReport]![EndDate])
And set your field default to =date() to capture the date only, instead of =now().
If the field being compared is rs("Date"), try
Int(rs("Date")) >=Forms!frmReport!StartDate AND Int(rs("Date")) <=Forms!frmReport!EndDate
For the Query Builder, modify your date checking field to something like this:
Replace YourDateField with the name of your field.
And if time is relevant, get rid of the field expression in the query builder, and instead compare the record's field to:
>=Forms!frmReport!StartDate AND <= iif(Forms!frmReport!EndDate = Forms!frmReport!StartDate, dateadd("d",1,Forms!frmReport!EndDate), Forms!frmReport!EndDate)
This expression says if the end date is the same as the start date add a day, otherwise just use the end date.

SQL Server: Want to use between clause with dates, but dates in string form (YYYY.MM.DD)

Help! One column in my database is for dates. All of my dates are unfortunately in the String form (YYYY.MM.DD). I have a MASSIVE database (300+GB) so ideally would like to avoid transformations.
Is there a way I can select rows for dates in between YYYY.MM.DD and YYYY.MM.DD? What would the script look like?
Thank you!
If the months and days are stored with leading zeroes, the BETWEEN operator will work as expected. So will ORDER BY.
create table your_table (
date_value varchar(10) not null
);
insert into your_table values
('2013.01.01'), ('2013.01.13'), ('2013.01.30'), ('2013.01.31'),
('2013.02.01'), ('2013.02.13'), ('2013.02.28'), ('2013.02.31'),
('2013.03.01'), ('2013.03.15'), ('2013.03.30'), ('2013.03.31');
select date_value
from your_table
where date_value between '2013.01.01' and '2013-01-31'
order by date_value;
2013.01.01
2013.01.13
2013.01.30
One of the main problems with your structure is that you lose type safety. Look at this query.
select date_value
from your_table
where date_value between '2013.02.01' and '2013.02.31'
order by date_value;
2013.02.01
2013.02.13
2013.02.28
2013.02.31
If you'd used a column of type date or datetime or timestamp, the dbms would not have allowed inserting the values '2013.02.31', because that's not a value in the domain of date. It is a value in the domain of varchar. (And so is "Arrrrgh!", unless you've got a CHECK constraint on that column that severely restricts the acceptable values.)
Not good solution, but works (cost much performance).
You have formated date in order year, month, day (good order to compare strings, without transformation to datetime), so you can try
SELECT * FROM Table WHERE StringDate > '2013.07.10' AND StringDate < '2013.07.14'
It returns bad results if there are dates before year 1000 without leading zero ('999.07.14').
But I dont know how it works on big database.
SQL Fiddle
Between in SQL is inclusive of both bounds. If that is what you want, you can just use between:
where col between 'YYYY.MM.DD' and 'YYYY.MM.DD'
Where the two constants are whatever values you are looking for.
If you have an index on the column, then between (as well as >, >=, and so on) will use the index. You do not need to transform the values. If your constants are dates of one form or another, then you can use date_format() to create a string in the right format. For instance, to get dates within the past week:
where col >= date_format(adddate(now(), -7), '%Y.%m.%d')