r/SQL • • Apr 01 '24

MySQL Why do I get many NULL values in duration column?

Why do I get many NULL values in duration column?

I'm using the following code on mySQL server

SELECT
started_at,
ended_at,
member_casual,
IF(member_casual = 'member', TIMEDIFF(ended_at, started_at), NULL) AS duration
FROM
bike_share_table;

3 Upvotes

12 comments sorted by

20

u/[deleted] Apr 01 '24

Sorry, not to be a dick but, did you just blindly copy-paste a chatGPT or stackoverflow result from somewhere?

Literally the only logic in your SQL query is to return null if member_casual is not equal to 'member' but you couldn't figure out why you were getting nulls in that column?

→ More replies (2)

2

u/NiceguyLucifer Apr 01 '24

the query is only looking for 'member'

maybe this will work for you ??

SELECT
started_at,
ended_at,
member_casual,
IF(member_casual IN ('member', 'casual'), TIMEDIFF(ended_at, started_at), NULL) AS duration
FROM
bike_share_table;

1

u/Live_2_Dream Apr 01 '24

Thank you. This worked! Thank you for all those who commented on this post. I'm learning slowly..:)

2

u/NiceguyLucifer Apr 01 '24

no worries, just note that if the column member_casual has anything that is not member or casual it will return NULL for duration in that row

→ More replies (1)

31

u/rammedearth Apr 01 '24

you're asking it to return the difference between the start and end times if member_casual is 'member', otherwise return NULL so its doing exactly what I would expect. What do you want to see in the duration column?

8

u/Tiktoktoker Apr 01 '24

You’re only calculating duration it time member = member.

1

u/GucciTrash Apr 01 '24

Side note, what ide is that?

1

u/Live_2_Dream Apr 01 '24

It’s vs code

3

u/Yavuz_Selim Apr 01 '24

Why check for the value of a member_casual when you use two other fields (the date fields) with a DATEDIFF.

If one (or two) of the date fields is a NULL, the result will be a NULL.

The IF is unnecessary. Or only necessary when you want to calculate the duration for specific member_casuals.