Question

This function:

for i in Selection: 
    cursor.execute(Query)
    ydata[i] = [int(x[0]) for x in cursor.fetchall()]

raises:

ValueError: invalid literal for int(): NULL if a null value is found.

How can I make my query return zeros instead of nulls so that I can fix this? (I am plotting the data, so I cannot add "is not null" to my select statement.

Was it helpful?

Solution

You can fix this before it gets to Python with a case statement in your query:

CASE WHEN FIELD_NAME IS NULL THEN 0 ELSE FIELD_NAME END,

begin edit

Other SQL variants do it differently (taken from other answers):

COALESCE(FIELD_NAME, 0)

or

IFNULL(FIELD_NAME, 0)

end edit

Or handle it in your list comp like so (assumes NULL is a predefined object or constant):

ydata[i] = [(int(x[0]) if x[0] != NULL else 0) for x in cursor.fetchall()]

Or create a customer conversion function:

def field_to_int(val):
    if val == NULL:
        return 0
    else:
        return int(val)

for i in Selection: 
    cursor.execute(Query)
    ydata[i] = [field_to_int(x[0]) for x in cursor.fetchall()]

OTHER TIPS

Put IFNULL(fieldname, 0) AS fieldname in the field list of the query.

You'd use IFNULL

...IFNULL(MyField, 0) AS MyField...

The error doesn't make sense; Python doesn't have "NULL", it has "None".

The cleanest thing to do is use SQL coalesce: SELECT COALESCE(value, 0) to convert SQL NULL to 0.

If you're getting None, and you know the values are integers, then you can safely say int(x[0] or 0).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top