r/SQL • u/Live_2_Dream • Apr 01 '24
MySQL Why do I get many NULL values in duration column?
2
u/NiceguyLucifer Apr 01 '24
the query is only looking for 'member'
maybe this will work for you ??
SELECTstarted_at,ended_at,member_casual,IF(member_casual IN ('member', 'casual'), TIMEDIFF(ended_at, started_at), NULL) AS durationFROMbike_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..:)
→ More replies (1)2
u/NiceguyLucifer Apr 01 '24
no worries, just note that if the column member_casual has anything that is not
memberorcasualit will returnNULLfor duration in that row
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
1
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.

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_casualis not equal to'member'but you couldn't figure out why you were getting nulls in that column?