Hello,

I try with the following query to calculate the working time of employees:

SELECT 
	TIME_FORMAT(
		ADDTIME(
			TIMEDIFF(TIMEDIFF(hour_end, hour_begin),(hour_pause)), 
			TIMEDIFF(TIMEDIFF(hour_end_o, hour_begin_o),(hour_pause_o))
				) ,'%H:%i'
				) AS total
FROM 
	hour

This works correct, if the pause is filled, if no pause is given, no total is displayed (NULL). How can I calculate the correct total, when pause is given or not?

Dani AI

Generated

identified the underlying cause: zero/placeholder date/time values in the table were breaking the arithmetic. Two practical, complementary paths fix this reliably — make the query tolerant of missing values, and fix the stored data/type so future rows cannot introduce the same problem.

A tolerant-query pattern converts any "zero" datetime into NULL (so it behaves like "no pause") and uses seconds arithmetic to add/subtract times safely. Example approach:

SELECT SEC_TO_TIME(
  COALESCE(TIME_TO_SEC(TIMEDIFF(hour_end, hour_begin)), 0)
  + COALESCE(TIME_TO_SEC(TIMEDIFF(hour_end_o, hour_begin_o)), 0)
  - COALESCE(TIME_TO_SEC(TIME(NULLIF(hour_pause,'0000-00-00 00:00:00'))), 0)
) AS total
FROM hour;

This treats zero-date placeholders as "no pause" and falls back to 0 seconds when fields are missing. See MySQL date/time functions for the used helpers (TIME_TO_SEC / SEC_TO_TIME / TIMEDIFF) and the null-handling function (COALESCE).

For a long-term fix, normalize the schema and data: convert meaningless zero-dates to NULL, use TIME for time-of-day or store durations as integer seconds, and prevent zero-dates from being inserted. Example maintenance steps:

UPDATE hour
SET hour_pause = NULL
WHERE hour_pause = '0000-00-00 00:00:00';

ALTER TABLE hour
  MODIFY hour_pause TIME NULL DEFAULT '00:00:00';

To avoid future zero-date inserts, enable appropriate SQL modes or validate at the application layer (SQL mode flags). Extra notes: if shifts can span midnight, add 24h when end < start or use DATETIME arithmetic; storing durations as seconds makes aggregation (SUM) and comparisons much simpler.

It is solved, but I have it not solved in the query itself.
There where fields that has 0000-00-00 00:00 instead of 2008-02-05 00:00
Thus the build of my table was incorrect, so that MySQL cannot calculate:

(2008-02-05 10:00 - 0000-00-00 00:00) = 10:00

But my problem is gone, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.