Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7030769
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T00:42:55+00:00 2026-05-28T00:42:55+00:00

Is there the possibility to do something like this inside the SQL-Query? Maybe provide

  • 0

Is there the possibility to do something like this inside the SQL-Query? Maybe provide a list as input-argument?
The dates I want are consecutive, but not all dates exist in the database. If a date doesn’t exist, the result should be “None”.

dates = [dt.datetime(2008,1,1), dt.datetime(2008,1,2), dt.datetime(2008,1,3), dt.datetime(2008,1,4), dt.datetime(2008,1,5)]
id = "361-442"
result = []
for date in dates:
    curs.execute('''SELECT price, date FROM prices where date = ? AND id = ?''', (date, id))
    query = curs.fetchall()
    if  query == []:
        result.append([None, arg])
    else:
        result.append(query)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T00:42:56+00:00Added an answer on May 28, 2026 at 12:42 am

    To perform all the work in sqlite, you could use a LEFT JOIN to fill in missing prices with None:

    sql='''
    SELECT p.price, t.date
    FROM ( {t} ) t
    LEFT JOIN price p
    ON p.date = t.date
    WHERE p.id = ?
    '''.format(t=' UNION ALL '.join('SELECT {d!r} date'.format(d=d) for d in date))
    
    cursor.execute(sql,[id])
    result=cursor.fetchall()
    

    However, this solution requires forming a (potentially) huge string in Python in order to create a temporary table of all desired dates. It is not only slow (including the time it takes sqlite to create the temporary table) it is also brittle: If len(date) is greater than about 500, then sqlite raises

    OperationalError: too many terms in compound SELECT
    

    You might be able to get around this if you already have all the desired dates in some other table. Then you could replace the ugly “UNION ALL” SQL above with
    something like

    SELECT p.price, t.date
    FROM ( SELECT date from dates ) t
    LEFT JOIN price p
    ON p.date = t.date
    

    While this is an improvement, my timeit tests (see below) show that doing part of the work in Python is still faster:


    Doing part of the work in Python:

    If you know that the dates are consecutive and can therefore be expressed as a range, then:

    curs.execute('''
        SELECT date, price
        FROM prices
        WHERE date <= ?
            AND date >= ?
            AND id = ?''', (max(date), min(date), id))
    

    Otherwise, if the dates are arbitrary then:

    sql = '''
        SELECT date, price
        FROM prices
        WHERE date IN ({s})
            AND id = ?'''.format(s={','.join(['?']*len(dates))})
    curs.execute(sql,dates + [id])
    

    To form the result list with None inserted for missing prices, you could form a dict out of (date,price) pairs, and use the dict.get() method to
    supply the default value None when the date key is missing:

    result = dict(curs.fetchall())
    result = [(result.get(d,None), d) for d in date]
    

    Note to form the dict as a mapping from dates to prices, I swapped the order of date and price in the SQL queries.


    Timeit tests:

    I compared these three functions:

    def using_sqlite_union():
        sql = '''
            SELECT p.price, t.date
            FROM ( {t} ) t
            LEFT JOIN price p
            ON p.date = t.date
        '''.format(t = ' UNION ALL '.join('SELECT {d!r} date'.format(d = str(d))
                                          for d in dates))
        cursor.execute(sql)
        return cursor.fetchall()
    
    def using_sqlite_dates():
        sql = '''
            SELECT p.price, t.date
            FROM ( SELECT date from dates ) t
            LEFT JOIN price p
            ON p.date = t.date
        '''
        cursor.execute(sql)
        return cursor.fetchall()
    
    def using_python_dict():
        cursor.execute('''
            SELECT date, price
            FROM price
            WHERE date <= ?
                AND date >= ?
                ''', (max(dates), min(dates)))
    
        result = dict(cursor.fetchall())
        result = [(result.get(d,None), d) for d in dates]
        return result
    
    N = 500
    m = 10
    omit = random.sample(range(N), m)
    dates = [ datetime.date(2000, 1, 1)+datetime.timedelta(days = i) for i in range(N) ]
    rows = [ (d, random.random()) for i, d in enumerate(dates) if i not in omit ]
    

    rows defined the data which was INSERTed into the price table.


    Timeit tests results:

    Running timeit like this:

    python -mtimeit -s'import timeit_sqlite_union as t' 't.using_python_dict()'
    

    produced these benchmarks:

    ·────────────────────·────────────────────·
    │  using_python_dict │ 1.47 msec per loop │
    │ using_sqlite_dates │ 3.39 msec per loop │
    │ using_sqlite_union │ 5.69 msec per loop │
    ·────────────────────·────────────────────·
    

    using_python_dict is about 2.3 times faster than using_sqlite_dates. Even if we increase the total number of dates to 10000, the speed ratio remains the same:

    ·────────────────────·────────────────────·
    │  using_python_dict │ 32.5 msec per loop │
    │ using_sqlite_dates │ 81.5 msec per loop │
    ·────────────────────·────────────────────·
    

    Conclusion: shifting all the work into sqlite is not necessarily faster.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there any possibility to return multiple values from method? Something like this: def
Is there a possibility to use Octave headless. Something like this octave < 5+4
Is there a possibility to overload __cinit__ or __add__ ? Something like this: cdef
I was always curious is there any possibility to overload function literal, something like
If there is any possibility to use the parameters in zsh aliases? Something like
In postgresql a query in the querylog gets something like this: 2009-02-05 00:12:27 CET
I'd like to know if there is a possibility to create something like named
Is there a possibility to access a i.e background-image:url() property inside an inline style
Is there a possibility to literally override a target or emulate this somehow? So,
In my WPF Window_Loaded event handler I have something like this: System.Threading.Tasks.Task.Factory.StartNew(() => {

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.