I have these tables: CREATE TABLE labels(user_id INT, session_id INT, start_time TIMESTAMP,mode TEXT); INSERT INTO labels (user_id,session_id,start_time,mode) VALUES (48,652,’2016-04-01 00:47:00+01′,’foot’), (9,656,’2016-04-01 00:03:39+01′,’car’),(9,657,’2016-04-01 00:26:51+01′,’car’), (9,658,’2016-04-01 00:45:19+01′,’car’),(46,663,’2016-04-01 00:13:12+01′,’car’); CREATE TABLE raw_data(user_id INT, session_id INT,timestamp TIMESTAMP) ; INSERT INTO raw_data(user_id, session_id,timestamp) VALUES (8,652,’2016-04-01 00:46:11.638+01′),(8,652,’2016-04-01 00:47:00.566+01′), (8,652,’2016-04-01 00:48:06.383+01′),(9,656,’2016-04-01 00:14:17.707+01′), (9,656,’2016-04-01 00:15:18.664+01′),(9,656,’2016-04-01 00:16:19.687+01′), (9,656,’2016-04-01 00:24:20.691+01′),(9,656,’2016-04-01 00:25:23.681+01′), (9,657,’2016-04-01 00:24:50.842+01′),(9,657,’2016-04-01 00:26:51.096+01′), (9,657,’2016-04-01… Read More Gap-and-island for more than time threshold