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 8867703
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T17:06:23+00:00 2026-06-14T17:06:23+00:00

I’m having a difficult time figuring out why a simple SELECT query is taking

  • 0

I’m having a difficult time figuring out why a simple SELECT query is taking such a long time with sqlalchemy using raw SQL (I’m getting 14600 rows/sec, but when running the same query through psycopg2 without sqlalchemy, I’m getting 38421 rows/sec).

After some poking around, I realized that toggling sqlalchemy’s use_native_unicode parameter in the create_engine call actually makes a huge difference.

This query takes 0.5secs to retrieve 7300 rows:

from sqlalchemy import create_engine

engine = create_engine("postgresql+psycopg2://localhost...",
                       use_native_unicode=True)
r = engine.execute("SELECT * FROM logtable")
fetched_results = r.fetchall()

This query takes 0.19secs to retrieve the same 7300 rows:

engine = create_engine("postgresql+psycopg2://localhost...",
                       use_native_unicode=False)
r = engine.execute("SELECT * FROM logtable")
fetched_results = r.fetchall()

The only difference between the 2 queries is use_native_unicode. But sqlalchemy’s own docs state that it is better to keep use_native_unicode=True (http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html).

Does anyone know why use_native_unicode is making such a big performance difference? And what are the ramifications of turning off use_native_unicode?

  • 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-06-14T17:06:24+00:00Added an answer on June 14, 2026 at 5:06 pm

    this issue is something you need to decide based on how much non-ASCII data you’re dealing with. psycopg2’s method of decoding unicode is faster than that of SQLAlchemy’s, assuming SQLA’s C extensions are not in use, but still adds latency for a result set versus not doing any kind of unicode conversion. In the code above, SQLAlchemy’s unicode facilities are not used; these are only used when a column is mapped to the Unicode or String types, which can only happen if you are using text(), select(), or an ORM-level equivalent, where a Unicode type is mapped to those result set columns using Table metadata the “typemap” parameter of text().

    Psycopg2’s native unicode facilities OTOH take effect at the cursor level so are always in effect, and apparently add some latency overall.

    Below is a series of illustrations of how the different methods work. the last one is the one most similar to that of SQLAlchemy, although when using SQLAlchemy’s C extensions we are probably just a fast as psycopg2:

    import psycopg2
    from psycopg2 import extensions
    
    conn = psycopg2.connect(user='scott', password='tiger', host='localhost', database='test')
    
    cursor = conn.cursor()
    cursor.execute("""
    create table data (
        id SERIAL primary key,
        data varchar(500)
    )
    """)
    
    cursor.executemany("insert into data (data) values (%(data)s)", [
            {"data":"abcdefghij" * 50} for i in xrange(10000)
        ])
    cursor.close()
    
    
    def one(conn):
        cursor = conn.cursor()
        cursor.execute("SELECT data FROM data")
        for row in cursor:
            row[0]
    
    def two(conn):
        cursor = conn.cursor()
        extensions.register_type(extensions.UNICODE, cursor)
        cursor.execute("SELECT data FROM data")
        for row in cursor:
            row[0]
    
    def three(conn):
        cursor = conn.cursor()
        cursor.execute("SELECT data FROM data")
        for row in cursor:
            row[0].decode('utf-8')
    
    def four(conn):
        cursor = conn.cursor()
        def conv_unicode(value):
            return value.decode('utf-8')
        cursor.execute("SELECT data FROM data")
        for row in cursor:
            conv_unicode(row[0])
    
    import timeit
    
    print "no unicode:", timeit.timeit("one(conn)", "from __main__ import conn, one", number=100)
    
    print "native unicode:", timeit.timeit("two(conn)", "from __main__ import conn, two", number=100)
    
    print "in Python unicode:", timeit.timeit("three(conn)", "from __main__ import conn, three", number=100)
    
    print "more like SQLA's unicode:", timeit.timeit("four(conn)", "from __main__ import conn, four", number=100)
    

    the timings I get:

    no unicode: 2.10434007645
    native unicode: 4.52875208855
    in Python unicode: 4.77912807465
    more like SQLA's unicode: 4.88325881958
    

    so what’s interesting here, is that SQLA’s approach, if perhaps we used the C extensions, might actually be a better choice than psycopg2’s native approach, if in fact you don’t make a lot of use of the Unicode type and most of your string values are only pure ASCII.

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

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
We're building an app, our first using Rails 3, and we're having to build
I'm making a simple page using Google Maps API 3. My first. One marker
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I am reading a book about Javascript and jQuery and using one of the
Seemingly simple, but I cannot find anything relevant on the web. What is the
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I am doing a simple coin flipping experiment for class that involves flipping a

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.