#๐Ÿ”’ is there an easier way to do this SQL query

14 messages ยท Page 1 of 1 (latest)

echo plinth
#

if there are any results from today, give me those
otherwise, give me the ten most recent results

chatGPT has me down a rabbit hole of shit like this

SELECT *
FROM (
    SELECT *,
           EXISTS (SELECT 1 FROM your_table WHERE DATE(date_column) = CURDATE()) AS has_today
    FROM your_table
    ORDER BY has_today DESC,
             CASE WHEN has_today = 1 THEN date_column ELSE NULL END DESC,
             date_column DESC
    LIMIT 10
) AS combined_results;

and this

SELECT *
FROM your_table
WHERE DATE(date_column) = CURDATE() OR 
      (SELECT COUNT(*) FROM your_table WHERE DATE(date_column) = CURDATE()) = 0
ORDER BY IF(DATE(date_column) = CURDATE(), 0, 1), date_column DESC
LIMIT 10;

but there has to be an easier way, right?

sorry not python but whatever

azure willowBOT
#

@echo plinth

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

solid crow
#

wouldn't the "ten most recent" also contain the ones from today?

#

what if there are more than 10 for today?

#

(I honestly would just do two separate queries)

winter verge
#

hello guys i need a help i want to connect my django project with mongodb

opaque cloud
#

sorry not python but whatever
๐Ÿ‘ questions about query languages are permitted as they pertain to something you are doing in Python @echo plinth

echo plinth
#

and yeah the top 10 would include the ones from today too but

it seemed like this would be doable so ....

#

thank!

random spindle
#

I don't see how any of the chatgpt solutions make sense.

azure willowBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.