Skip to content
Advertisement

python sql ORDER date doesn’t work

I ran into another (probably self inflicted) issue. Python3.6 and sqlite I’m very sufficient in creating a db and adding tables and info and all that. My issue is, that the info I’m ading is not sequential. But I’d like it to be sorted inside the db, so it’s easier to process. Below is my code that is supposed to Sort (ORDER) my table entries by the Timestamp named “datum”. If I run the same query from within sqliteman on ubuntu it works and reorders the lines as I want it to. However if I try it in python it doesn’t work?

con = lite.connect(db_name)

with con:
    try:
        cur = con.cursor()

        strExec = "SELECT * FROM " + db_table_name + " ORDER BY datum ASC"
        cur.execute(strExec)
        con.commit()
    except Error as e:
        print(e)
cur.close()
con.close()

Here are the entries for datum in that table. There are hundreds of entries, but I’m only showing a few here.

2017-12-23T00:00:00
2017-12-25T00:00:00
2017-12-24T00:00:00
2017-12-21T00:00:00
2017-12-24T00:00:00
2017-12-26T00:00:00
2017-12-12T00:00:00

Any idea what I’m missing here? Thanks!

# ============================
# EDIT
# ============================

As answered below, the order in which data resides inside the db’s tables is completely irrelevant. The data needs to be ordered and put in whatever sequence is needed when working with the data only. Therefore the code snippet below is one example to get that data into the desired order.

db_result = cur.fetchall() 
for row in db_result:
    print(row)

Advertisement

Answer

SQL tables are unordered.

If you want to retrieve rows from a table in a specific order, you have to add an ORDER BY clause to every query that retrieves rows.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement