Fastest way to find not null filed in sqlite

2019-09-09 12:48发布

问题:

I have sqlite table

CREATE TABLE IF NOT EXISTS [app_status](
[id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
[status] TEXT DEFAULT NULL
) 

This table is having multiple records like

1 "success"
2 NULL

where NULL is sqlite NULL

What is the fastest way to find out if table at-least one row where status IS NOT NULL? Can I create some index or something else which I can use to count Not NULL fields ?

I have written following query

SELECT 1 \
FROM [app_status]\
WHERE [status] IS NOT NULL

But it is taking 3 ms to 50 ms. I want to further optimize this time. How can I do that ?

回答1:

Add an index on that column if it doesn't already have one, and/or limit your select.

select 1 from [app_status] where [status] is not null limit 1;

You don't need to go through the whole table if you're just checking if the column contains at least one non-null field.