Sobes.tech
Junior

You analyze the sessions table, where status can be 'success', 'failed', 'pending', and the 'ended_at' field can be NULL if the session is not finished. You need to select all unfinished sessions except those with 'pending' status. What can be said about the correctness of the following query? select * from sessions where ended_at is null and status != 'pending';

sobes.tech AI

Answer from AI

Query:

select * from sessions
where ended_at is null and status != 'pending';

has a potential issue related to handling NULL in the condition status != 'pending'.

If the status field can take values 'success', 'failed', 'pending', then the condition status != 'pending' will return TRUE for 'success' and 'failed', and FALSE for 'pending'. But if NULLs are possible in the status field, then the comparison status != 'pending' will return UNKNOWN (not TRUE), and such records will not be included in the result.

If the table guarantees no NULLs in the status field, then the query is correct and will select all sessions where ended_at IS NULL (i.e., unfinished), and the status is not 'pending'.

If NULLs are possible, it's better to explicitly handle this, for example:

select * from sessions
where ended_at is null and (status != 'pending' or status is null);

In summary, correctness depends on the presence of NULLs in the status field. Otherwise, the query logic matches the condition: select unfinished sessions except those with 'pending' status.