Stay Ahead, Stay ONMINE

Practical SQL Puzzles That Will Level Up Your Skill

There are some Sql patterns that, once you know them, you start seeing them everywhere. The solutions to the puzzles that I will show you today are actually very simple SQL queries, but understanding the concept behind them will surely unlock new solutions to the queries you write on a day-to-day basis. These challenges are all based on real-world scenarios, as over the past few months I made a point of writing down every puzzle-like query that I had to build. I also encourage you to try them for yourself, so that you can challenge yourself first, which will improve your learning! All queries to generate the datasets will be provided in a PostgreSQL and DuckDB-friendly syntax, so that you can easily copy and play with them. At the end I will also provide you a link to a GitHub repo containing all the code, as well as the answer to the bonus challenge I will leave for you! I organized these puzzles in order of increasing difficulty, so, if you find the first ones too easy, at least take a look at the last one, which uses a technique that I truly believe you won’t have seen before. Okay, let’s get started. I love this puzzle because of how short and simple the final query is, even though it deals with many edge cases. The data for this challenge shows tickets moving in between Kanban stages, and the objective is to find how long, on average, tickets stay in the Doing stage. The data contains the ID of the ticket, the date the ticket was created, the date of the move, and the “from” and “to” stages of the move. The stages present are New, Doing, Review, and Done. Some things you need to know (edge cases): Tickets can move backwards, meaning tickets can go back to the Doing stage. You should not include tickets that are still stuck in the Doing stage, as there is no way to know how long they will stay there for. Tickets are not always created in the New stage. “`SQL CREATE TABLE ticket_moves ( ticket_id INT NOT NULL, create_date DATE NOT NULL, move_date DATE NOT NULL, from_stage TEXT NOT NULL, to_stage TEXT NOT NULL ); “` “`SQL INSERT INTO ticket_moves (ticket_id, create_date, move_date, from_stage, to_stage) VALUES — Ticket 1: Created in “New”, then moves to Doing, Review, Done. (1, ‘2024-09-01’, ‘2024-09-03’, ‘New’, ‘Doing’), (1, ‘2024-09-01’, ‘2024-09-07’, ‘Doing’, ‘Review’), (1, ‘2024-09-01’, ‘2024-09-10’, ‘Review’, ‘Done’), — Ticket 2: Created in “New”, then moves: New → Doing → Review → Doing again → Review. (2, ‘2024-09-05’, ‘2024-09-08’, ‘New’, ‘Doing’), (2, ‘2024-09-05’, ‘2024-09-12’, ‘Doing’, ‘Review’), (2, ‘2024-09-05’, ‘2024-09-15’, ‘Review’, ‘Doing’), (2, ‘2024-09-05’, ‘2024-09-20’, ‘Doing’, ‘Review’), — Ticket 3: Created in “New”, then moves to Doing. (Edge case: no subsequent move from Doing.) (3, ‘2024-09-10’, ‘2024-09-16’, ‘New’, ‘Doing’), — Ticket 4: Created already in “Doing”, then moves to Review. (4, ‘2024-09-15’, ‘2024-09-22’, ‘Doing’, ‘Review’); “` A summary of the data: Ticket 1: Created in the New stage, moves normally to Doing, then Review, and then Done. Ticket 2: Created in New, then moves: New → Doing → Review → Doing again → Review. Ticket 3: Created in New, moves to Doing, but it is still stuck there. Ticket 4: Created in the Doing stage, moves to Review afterward. It might be a good idea to stop for a bit and think how you would deal with this. Can you find out how long a ticket stays on a single stage? Honestly, this sounds intimidating at first, and it looks like it will be a nightmare to deal with all the edge cases. Let me show you the full solution to the problem, and then I will explain what is happening afterward. “`SQL WITH stage_intervals AS (     SELECT         ticket_id,         from_stage,         move_date          – COALESCE(             LAG(move_date) OVER (                 PARTITION BY ticket_id                  ORDER BY move_date             ),              create_date         ) AS days_in_stage     FROM         ticket_moves ) SELECT     SUM(days_in_stage) / COUNT(DISTINCT ticket_id) as avg_days_in_doing FROM     stage_intervals WHERE     from_stage = ‘Doing’; “` The first CTE uses the LAG function to find the previous move of the ticket, which will be the time the ticket entered that stage. Calculating the duration is as simple as subtracting the previous date from the move date. What you should notice is the use of the COALESCE in the previous move date. What that does is that if a ticket doesn’t have a previous move, then it uses the date of creation of the ticket. This takes care of the cases of tickets being created directly into the Doing stage, as it still will properly calculate the time it took to leave the stage. This is the result of the first CTE, showing the time spent in each stage. Notice how the Ticket 2 has two entries, as it visited the Doing stage in two separate occasions. With this done, it’s just a matter of getting the average as the SUM of total days spent in doing, divided by the distinct number of tickets that ever left the stage. Doing it this way, instead of simply using the AVG, makes sure that the two rows for Ticket 2 get properly accounted for as a single ticket. Not so bad, right? The goal of this second challenge is to find the most recent contract sequence of every employee. A break of sequence happens when two contracts have a gap of more than one day between them.  In this dataset, there are no contract overlaps, meaning that a contract for the same employee either has a gap or ends a day before the new one starts. “`SQL CREATE TABLE contracts (     contract_id integer PRIMARY KEY,     employee_id integer NOT NULL,     start_date date NOT NULL,     end_date date NOT NULL ); INSERT INTO contracts (contract_id, employee_id, start_date, end_date) VALUES      — Employee 1: Two continuous contracts     (1, 1, ‘2024-01-01’, ‘2024-03-31’),     (2, 1, ‘2024-04-01’, ‘2024-06-30’),     — Employee 2: One contract, then a gap of three days, then two contracts     (3, 2, ‘2024-01-01’, ‘2024-02-15’),     (4, 2, ‘2024-02-19’, ‘2024-04-30’),     (5, 2, ‘2024-05-01’, ‘2024-07-31’),     — Employee 3: One contract     (6, 3, ‘2024-03-01’, ‘2024-08-31’); “` As a summary of the data: Employee 1: Has two continuous contracts. Employee 2: One contract, then a gap of three days, then two contracts. Employee 3: One contract. The expected result, given the dataset, is that all contracts should be included except for the first contract of Employee 2, which is the only one that has a gap. Before explaining the logic behind the solution, I would like you to think about what operation can be used to join the contracts that belong to the same sequence. Focus only on the second row of data, what information do you need to know if this contract was a break or not? I hope it’s clear that this is the perfect situation for window functions, again. They are incredibly useful for solving problems like this, and understanding when to use them helps a lot in finding clean solutions to problems. First thing to do, then, is to get the end date of the previous contract for the same employee with the LAG function. Doing that, it’s simple to compare both dates and check if it was a break of sequence. “`SQL WITH ordered_contracts AS (     SELECT         *,         LAG(end_date) OVER (PARTITION BY employee_id ORDER BY start_date) AS previous_end_date     FROM         contracts ), gapped_contracts AS (     SELECT         *,         — Deals with the case of the first contract, which won’t have         — a previous end date. In this case, it’s still the start of a new         — sequence.         CASE WHEN previous_end_date IS NULL             OR previous_end_date < start_date – INTERVAL '1 day' THEN             1         ELSE             0         END AS is_new_sequence     FROM         ordered_contracts ) SELECT * FROM gapped_contracts ORDER BY employee_id ASC; “` An intuitive way to continue the query is to number the sequences of each employee. For example, an employee who has no gap, will always be on his first sequence, but an employee who had 5 breaks in contracts will be on his 5th sequence. Funnily enough, this is done by another window function. “`SQL — — Previous CTEs — sequences AS (     SELECT         *,         SUM(is_new_sequence) OVER (PARTITION BY employee_id ORDER BY start_date) AS sequence_id FROM     gapped_contracts ) SELECT * FROM sequences ORDER BY employee_id ASC; “` Notice how, for Employee 2, he starts his sequence #2 after the first gapped value. To finish this query, I grouped the data by employee, got the value of their most recent sequence, and then did an inner join with the sequences to keep only the most recent one. “`SQL — — Previous CTEs — max_sequence AS (     SELECT         employee_id,         MAX(sequence_id) AS max_sequence_id FROM     sequences GROUP BY     employee_id ), latest_contract_sequence AS (     SELECT         c.contract_id,         c.employee_id,         c.start_date,         c.end_date     FROM         sequences c         JOIN max_sequence m ON c.sequence_id = m.max_sequence_id             AND c.employee_id = m.employee_id         ORDER BY             c.employee_id,             c.start_date ) SELECT     * FROM     latest_contract_sequence; “` As expected, our final result is basically our starting query just with the first contract of Employee 2 missing!  Finally, the last puzzle — I’m glad you made it this far.  For me, this is the most mind-blowing one, as when I first encountered this problem I thought of a completely different solution that would be a mess to implement in SQL. For this puzzle, I’ve changed the context from what I had to deal with for my job, as I think it will make it easier to explain.  Imagine you’re a data analyst at an event venue, and you’re analyzing the talks scheduled for an upcoming event. You want to find the time of day where there will be the highest number of talks happening at the same time. This is what you should know about the schedules: Rooms are booked in increments of 30min, e.g. from 9h-10h30. The data is clean, there are no overbookings of meeting rooms. There can be back-to-back meetings in a single meeting room. Meeting schedule visualized (this is the actual data).  “`SQL CREATE TABLE meetings (     room TEXT NOT NULL,     start_time TIMESTAMP NOT NULL,     end_time TIMESTAMP NOT NULL ); INSERT INTO meetings (room, start_time, end_time) VALUES     — Room A meetings     ('Room A', '2024-10-01 09:00', '2024-10-01 10:00'),     ('Room A', '2024-10-01 10:00', '2024-10-01 11:00'),     ('Room A', '2024-10-01 11:00', '2024-10-01 12:00'),     — Room B meetings     ('Room B', '2024-10-01 09:30', '2024-10-01 11:30'),     — Room C meetings     ('Room C', '2024-10-01 09:00', '2024-10-01 10:00'),     ('Room C', '2024-10-01 11:30', '2024-10-01 12:00'); “` The way to solve this is using what is called a Sweep Line Algorithm, or also known as an event-based solution. This last name actually helps to understand what will be done, as the idea is that instead of dealing with intervals, which is what we have in the original data, we deal with events instead. To do this, we need to transform every row into two separate events. The first event will be the Start of the meeting, and the second event will be the End of the meeting. “`SQL WITH events AS (   — Create an event for the start of each meeting (+1)   SELECT      start_time AS event_time,      1 AS delta   FROM meetings   UNION ALL   — Create an event for the end of each meeting (-1)   SELECT     — Small trick to work with the back-to-back meetings (explained later)     end_time – interval '1 minute' as end_time,     -1 AS delta   FROM meetings ) SELECT * FROM events; “` Take the time to understand what is happening here. To create two events from a single row of data, we’re simply unioning the dataset on itself; the first half uses the start time as the timestamp, and the second part uses the end time. You might already notice the delta column created and see where this is going. When an event starts, we count it as +1, when it ends, we count it as -1. You might even be already thinking of another window function to solve this, and you’re actually right! But before that, let me just explain the trick I used in the end dates. As I don’t want back-to-back meetings to count as two concurrent meetings, I’m subtracting a single minute of every end date. This way, if a meeting ends and another starts at 10h30, it won’t be assumed that two meetings are concurrently happening at 10h30. Okay, back to the query and yet another window function. This time, though, the function of choice is a rolling SUM. “`SQL — — Previous CTEs — ordered_events AS (   SELECT     event_time,     delta,     SUM(delta) OVER (ORDER BY event_time, delta DESC) AS concurrent_meetings   FROM events ) SELECT * FROM ordered_events ORDER BY event_time DESC; “` The rolling SUM at the Delta column is essentially walking down every record and finding how many events are active at that time. For example, at 9 am sharp, it sees two events starting, so it marks the number of concurrent meetings as two! When the third meeting starts, the count goes up to three. But when it gets to 9h59 (10 am), then two meetings end, bringing the counter back to one. With this data, the only thing missing is to find when the highest value of concurrent meetings happens. “`SQL — — Previous CTEs — max_events AS (   — Find the maximum concurrent meetings value   SELECT      event_time,      concurrent_meetings,     RANK() OVER (ORDER BY concurrent_meetings DESC) AS rnk   FROM ordered_events ) SELECT event_time, concurrent_meetings FROM max_events WHERE rnk = 1; “` That’s it! The interval of 9h30–10h is the one with the largest number of concurrent meetings, which checks out with the schedule visualization above! This solution looks incredibly simple in my opinion, and it works for so many situations. Every time you are dealing with intervals now, you should think if the query wouldn’t be easier if you thought about it in the perspective of events. But before you move on, and to really nail down this concept, I want to leave you with a bonus challenge, which is also a common application of the Sweep Line Algorithm. I hope you give it a try! Bonus challenge The context for this one is still the same as the last puzzle, but now, instead of trying to find the period when there are most concurrent meetings, the objective is to find bad scheduling. It seems that there are overlaps in the meeting rooms, which need to be listed so it can be fixed ASAP. How would you find out if the same meeting room has two or more meetings booked at the same time? Here are some tips on how to solve it: It’s still the same algorithm. This means you will still do the UNION, but it will look slightly different. You should think in the perspective of each meeting room. You can use this data for the challenge: “`SQL CREATE TABLE meetings_overlap (     room TEXT NOT NULL,     start_time TIMESTAMP NOT NULL,     end_time TIMESTAMP NOT NULL ); INSERT INTO meetings_overlap (room, start_time, end_time) VALUES     — Room A meetings     ('Room A', '2024-10-01 09:00', '2024-10-01 10:00'),     ('Room A', '2024-10-01 10:00', '2024-10-01 11:00'),     ('Room A', '2024-10-01 11:00', '2024-10-01 12:00'),     — Room B meetings     ('Room B', '2024-10-01 09:30', '2024-10-01 11:30'),     — Room C meetings     ('Room C', '2024-10-01 09:00', '2024-10-01 10:00'),     — Overlaps with previous meeting.     ('Room C', '2024-10-01 09:30', '2024-10-01 12:00'); “` If you’re interested in the solution to this puzzle, as well as the rest of the queries, check this GitHub repo. The first takeaway from this blog post is that window functions are overpowered. Ever since I got more comfortable with using them, I feel that my queries have gotten so much simpler and easier to read, and I hope the same happens to you. If you’re interested in learning more about them, you would probably enjoy reading this other blog post I’ve written, where I go over how you can understand and use them effectively. The second takeaway is that these patterns used in the challenges really do happen in many other places. You might need to find sequences of subscriptions, customer retention, or you might need to find overlap of tasks. There are many situations when you will need to use window functions in a very similar fashion to what was done in the puzzles. The third thing I want you to remember is about this solution to using events besides dealing with intervals. I’ve looked at some problems I solved a long time ago that I could’ve used this pattern on to make my life easier, and unfortunately, I didn’t know about it at the time. I really do hope you enjoyed this post and gave a shot to the puzzles yourself. And I’m sure that if you made it this far, you either learned something new about SQL or strengthened your knowledge of window functions!  Thank you so much for reading. If you have questions or just want to get in touch with me, don’t hesitate to contact me at mtrentz.com. All images by the author unless stated otherwise.

There are some Sql patterns that, once you know them, you start seeing them everywhere. The solutions to the puzzles that I will show you today are actually very simple SQL queries, but understanding the concept behind them will surely unlock new solutions to the queries you write on a day-to-day basis.

These challenges are all based on real-world scenarios, as over the past few months I made a point of writing down every puzzle-like query that I had to build. I also encourage you to try them for yourself, so that you can challenge yourself first, which will improve your learning!

All queries to generate the datasets will be provided in a PostgreSQL and DuckDB-friendly syntax, so that you can easily copy and play with them. At the end I will also provide you a link to a GitHub repo containing all the code, as well as the answer to the bonus challenge I will leave for you!

I organized these puzzles in order of increasing difficulty, so, if you find the first ones too easy, at least take a look at the last one, which uses a technique that I truly believe you won’t have seen before.

Okay, let’s get started.

I love this puzzle because of how short and simple the final query is, even though it deals with many edge cases. The data for this challenge shows tickets moving in between Kanban stages, and the objective is to find how long, on average, tickets stay in the Doing stage.

The data contains the ID of the ticket, the date the ticket was created, the date of the move, and the “from” and “to” stages of the move. The stages present are New, Doing, Review, and Done.

Some things you need to know (edge cases):

  • Tickets can move backwards, meaning tickets can go back to the Doing stage.
  • You should not include tickets that are still stuck in the Doing stage, as there is no way to know how long they will stay there for.
  • Tickets are not always created in the New stage.
```SQL

CREATE TABLE ticket_moves (
    ticket_id INT NOT NULL,
    create_date DATE NOT NULL,
    move_date DATE NOT NULL,
    from_stage TEXT NOT NULL,
    to_stage TEXT NOT NULL
);

```
```SQL

INSERT INTO ticket_moves (ticket_id, create_date, move_date, from_stage, to_stage)
    VALUES
        -- Ticket 1: Created in "New", then moves to Doing, Review, Done.
        (1, '2024-09-01', '2024-09-03', 'New', 'Doing'),
        (1, '2024-09-01', '2024-09-07', 'Doing', 'Review'),
        (1, '2024-09-01', '2024-09-10', 'Review', 'Done'),
        -- Ticket 2: Created in "New", then moves: New → Doing → Review → Doing again → Review.
        (2, '2024-09-05', '2024-09-08', 'New', 'Doing'),
        (2, '2024-09-05', '2024-09-12', 'Doing', 'Review'),
        (2, '2024-09-05', '2024-09-15', 'Review', 'Doing'),
        (2, '2024-09-05', '2024-09-20', 'Doing', 'Review'),
        -- Ticket 3: Created in "New", then moves to Doing. (Edge case: no subsequent move from Doing.)
        (3, '2024-09-10', '2024-09-16', 'New', 'Doing'),
        -- Ticket 4: Created already in "Doing", then moves to Review.
        (4, '2024-09-15', '2024-09-22', 'Doing', 'Review');
```

A summary of the data:

  • Ticket 1: Created in the New stage, moves normally to Doing, then Review, and then Done.
  • Ticket 2: Created in New, then moves: New → Doing → Review → Doing again → Review.
  • Ticket 3: Created in New, moves to Doing, but it is still stuck there.
  • Ticket 4: Created in the Doing stage, moves to Review afterward.

It might be a good idea to stop for a bit and think how you would deal with this. Can you find out how long a ticket stays on a single stage?

Honestly, this sounds intimidating at first, and it looks like it will be a nightmare to deal with all the edge cases. Let me show you the full solution to the problem, and then I will explain what is happening afterward.

```SQL

WITH stage_intervals AS (
    SELECT
        ticket_id,
        from_stage,
        move_date 
        - COALESCE(
            LAG(move_date) OVER (
                PARTITION BY ticket_id 
                ORDER BY move_date
            ), 
            create_date
        ) AS days_in_stage
    FROM
        ticket_moves
)
SELECT
    SUM(days_in_stage) / COUNT(DISTINCT ticket_id) as avg_days_in_doing
FROM
    stage_intervals
WHERE
    from_stage = 'Doing';
```

The first CTE uses the LAG function to find the previous move of the ticket, which will be the time the ticket entered that stage. Calculating the duration is as simple as subtracting the previous date from the move date.

What you should notice is the use of the COALESCE in the previous move date. What that does is that if a ticket doesn’t have a previous move, then it uses the date of creation of the ticket. This takes care of the cases of tickets being created directly into the Doing stage, as it still will properly calculate the time it took to leave the stage.

This is the result of the first CTE, showing the time spent in each stage. Notice how the Ticket 2 has two entries, as it visited the Doing stage in two separate occasions.

With this done, it’s just a matter of getting the average as the SUM of total days spent in doing, divided by the distinct number of tickets that ever left the stage. Doing it this way, instead of simply using the AVG, makes sure that the two rows for Ticket 2 get properly accounted for as a single ticket.

Not so bad, right?

The goal of this second challenge is to find the most recent contract sequence of every employee. A break of sequence happens when two contracts have a gap of more than one day between them. 

In this dataset, there are no contract overlaps, meaning that a contract for the same employee either has a gap or ends a day before the new one starts.

```SQL
CREATE TABLE contracts (
    contract_id integer PRIMARY KEY,
    employee_id integer NOT NULL,
    start_date date NOT NULL,
    end_date date NOT NULL
);

INSERT INTO contracts (contract_id, employee_id, start_date, end_date)
VALUES 
    -- Employee 1: Two continuous contracts
    (1, 1, '2024-01-01', '2024-03-31'),
    (2, 1, '2024-04-01', '2024-06-30'),
    -- Employee 2: One contract, then a gap of three days, then two contracts
    (3, 2, '2024-01-01', '2024-02-15'),
    (4, 2, '2024-02-19', '2024-04-30'),
    (5, 2, '2024-05-01', '2024-07-31'),
    -- Employee 3: One contract
    (6, 3, '2024-03-01', '2024-08-31');
```

As a summary of the data:

  • Employee 1: Has two continuous contracts.
  • Employee 2: One contract, then a gap of three days, then two contracts.
  • Employee 3: One contract.

The expected result, given the dataset, is that all contracts should be included except for the first contract of Employee 2, which is the only one that has a gap.

Before explaining the logic behind the solution, I would like you to think about what operation can be used to join the contracts that belong to the same sequence. Focus only on the second row of data, what information do you need to know if this contract was a break or not?

I hope it’s clear that this is the perfect situation for window functions, again. They are incredibly useful for solving problems like this, and understanding when to use them helps a lot in finding clean solutions to problems.

First thing to do, then, is to get the end date of the previous contract for the same employee with the LAG function. Doing that, it’s simple to compare both dates and check if it was a break of sequence.

```SQL
WITH ordered_contracts AS (
    SELECT
        *,
        LAG(end_date) OVER (PARTITION BY employee_id ORDER BY start_date) AS previous_end_date
    FROM
        contracts
),
gapped_contracts AS (
    SELECT
        *,
        -- Deals with the case of the first contract, which won't have
        -- a previous end date. In this case, it's still the start of a new
        -- sequence.
        CASE WHEN previous_end_date IS NULL
            OR previous_end_date < start_date - INTERVAL '1 day' THEN
            1
        ELSE
            0
        END AS is_new_sequence
    FROM
        ordered_contracts
)
SELECT * FROM gapped_contracts ORDER BY employee_id ASC;
```

An intuitive way to continue the query is to number the sequences of each employee. For example, an employee who has no gap, will always be on his first sequence, but an employee who had 5 breaks in contracts will be on his 5th sequence. Funnily enough, this is done by another window function.

```SQL
--
-- Previous CTEs
--
sequences AS (
    SELECT
        *,
        SUM(is_new_sequence) OVER (PARTITION BY employee_id ORDER BY start_date) AS sequence_id
FROM
    gapped_contracts
)
SELECT * FROM sequences ORDER BY employee_id ASC;
```

Notice how, for Employee 2, he starts his sequence #2 after the first gapped value. To finish this query, I grouped the data by employee, got the value of their most recent sequence, and then did an inner join with the sequences to keep only the most recent one.

```SQL
--
-- Previous CTEs
--
max_sequence AS (
    SELECT
        employee_id,
        MAX(sequence_id) AS max_sequence_id
FROM
    sequences
GROUP BY
    employee_id
),
latest_contract_sequence AS (
    SELECT
        c.contract_id,
        c.employee_id,
        c.start_date,
        c.end_date
    FROM
        sequences c
        JOIN max_sequence m ON c.sequence_id = m.max_sequence_id
            AND c.employee_id = m.employee_id
        ORDER BY
            c.employee_id,
            c.start_date
)
SELECT
    *
FROM
    latest_contract_sequence;
```

As expected, our final result is basically our starting query just with the first contract of Employee 2 missing! 

Finally, the last puzzle — I’m glad you made it this far. 

For me, this is the most mind-blowing one, as when I first encountered this problem I thought of a completely different solution that would be a mess to implement in SQL.

For this puzzle, I’ve changed the context from what I had to deal with for my job, as I think it will make it easier to explain. 

Imagine you’re a data analyst at an event venue, and you’re analyzing the talks scheduled for an upcoming event. You want to find the time of day where there will be the highest number of talks happening at the same time.

This is what you should know about the schedules:

  • Rooms are booked in increments of 30min, e.g. from 9h-10h30.
  • The data is clean, there are no overbookings of meeting rooms.
  • There can be back-to-back meetings in a single meeting room.

Meeting schedule visualized (this is the actual data). 

```SQL
CREATE TABLE meetings (
    room TEXT NOT NULL,
    start_time TIMESTAMP NOT NULL,
    end_time TIMESTAMP NOT NULL
);

INSERT INTO meetings (room, start_time, end_time) VALUES
    -- Room A meetings
    ('Room A', '2024-10-01 09:00', '2024-10-01 10:00'),
    ('Room A', '2024-10-01 10:00', '2024-10-01 11:00'),
    ('Room A', '2024-10-01 11:00', '2024-10-01 12:00'),
    -- Room B meetings
    ('Room B', '2024-10-01 09:30', '2024-10-01 11:30'),
    -- Room C meetings
    ('Room C', '2024-10-01 09:00', '2024-10-01 10:00'),
    ('Room C', '2024-10-01 11:30', '2024-10-01 12:00');
```

The way to solve this is using what is called a Sweep Line Algorithm, or also known as an event-based solution. This last name actually helps to understand what will be done, as the idea is that instead of dealing with intervals, which is what we have in the original data, we deal with events instead.

To do this, we need to transform every row into two separate events. The first event will be the Start of the meeting, and the second event will be the End of the meeting.

```SQL
WITH events AS (
  -- Create an event for the start of each meeting (+1)
  SELECT 
    start_time AS event_time, 
    1 AS delta
  FROM meetings
  UNION ALL
  -- Create an event for the end of each meeting (-1)
  SELECT 
   -- Small trick to work with the back-to-back meetings (explained later)
    end_time - interval '1 minute' as end_time,
    -1 AS delta
  FROM meetings
)
SELECT * FROM events;
```

Take the time to understand what is happening here. To create two events from a single row of data, we’re simply unioning the dataset on itself; the first half uses the start time as the timestamp, and the second part uses the end time.

You might already notice the delta column created and see where this is going. When an event starts, we count it as +1, when it ends, we count it as -1. You might even be already thinking of another window function to solve this, and you’re actually right!

But before that, let me just explain the trick I used in the end dates. As I don’t want back-to-back meetings to count as two concurrent meetings, I’m subtracting a single minute of every end date. This way, if a meeting ends and another starts at 10h30, it won’t be assumed that two meetings are concurrently happening at 10h30.

Okay, back to the query and yet another window function. This time, though, the function of choice is a rolling SUM.

```SQL
--
-- Previous CTEs
--
ordered_events AS (
  SELECT
    event_time,
    delta,
    SUM(delta) OVER (ORDER BY event_time, delta DESC) AS concurrent_meetings
  FROM events
)
SELECT * FROM ordered_events ORDER BY event_time DESC;
```

The rolling SUM at the Delta column is essentially walking down every record and finding how many events are active at that time. For example, at 9 am sharp, it sees two events starting, so it marks the number of concurrent meetings as two!

When the third meeting starts, the count goes up to three. But when it gets to 9h59 (10 am), then two meetings end, bringing the counter back to one. With this data, the only thing missing is to find when the highest value of concurrent meetings happens.

```SQL
--
-- Previous CTEs
--
max_events AS (
  -- Find the maximum concurrent meetings value
  SELECT 
    event_time, 
    concurrent_meetings,
    RANK() OVER (ORDER BY concurrent_meetings DESC) AS rnk
  FROM ordered_events
)
SELECT event_time, concurrent_meetings
FROM max_events
WHERE rnk = 1;
```

That’s it! The interval of 9h30–10h is the one with the largest number of concurrent meetings, which checks out with the schedule visualization above!

This solution looks incredibly simple in my opinion, and it works for so many situations. Every time you are dealing with intervals now, you should think if the query wouldn’t be easier if you thought about it in the perspective of events.

But before you move on, and to really nail down this concept, I want to leave you with a bonus challenge, which is also a common application of the Sweep Line Algorithm. I hope you give it a try!

Bonus challenge

The context for this one is still the same as the last puzzle, but now, instead of trying to find the period when there are most concurrent meetings, the objective is to find bad scheduling. It seems that there are overlaps in the meeting rooms, which need to be listed so it can be fixed ASAP.

How would you find out if the same meeting room has two or more meetings booked at the same time? Here are some tips on how to solve it:

  • It’s still the same algorithm.
  • This means you will still do the UNION, but it will look slightly different.
  • You should think in the perspective of each meeting room.

You can use this data for the challenge:

```SQL
CREATE TABLE meetings_overlap (
    room TEXT NOT NULL,
    start_time TIMESTAMP NOT NULL,
    end_time TIMESTAMP NOT NULL
);

INSERT INTO meetings_overlap (room, start_time, end_time) VALUES
    -- Room A meetings
    ('Room A', '2024-10-01 09:00', '2024-10-01 10:00'),
    ('Room A', '2024-10-01 10:00', '2024-10-01 11:00'),
    ('Room A', '2024-10-01 11:00', '2024-10-01 12:00'),
    -- Room B meetings
    ('Room B', '2024-10-01 09:30', '2024-10-01 11:30'),
    -- Room C meetings
    ('Room C', '2024-10-01 09:00', '2024-10-01 10:00'),
    -- Overlaps with previous meeting.
    ('Room C', '2024-10-01 09:30', '2024-10-01 12:00');
```

If you’re interested in the solution to this puzzle, as well as the rest of the queries, check this GitHub repo.

The first takeaway from this blog post is that window functions are overpowered. Ever since I got more comfortable with using them, I feel that my queries have gotten so much simpler and easier to read, and I hope the same happens to you.

If you’re interested in learning more about them, you would probably enjoy reading this other blog post I’ve written, where I go over how you can understand and use them effectively.

The second takeaway is that these patterns used in the challenges really do happen in many other places. You might need to find sequences of subscriptions, customer retention, or you might need to find overlap of tasks. There are many situations when you will need to use window functions in a very similar fashion to what was done in the puzzles.

The third thing I want you to remember is about this solution to using events besides dealing with intervals. I’ve looked at some problems I solved a long time ago that I could’ve used this pattern on to make my life easier, and unfortunately, I didn’t know about it at the time.


I really do hope you enjoyed this post and gave a shot to the puzzles yourself. And I’m sure that if you made it this far, you either learned something new about SQL or strengthened your knowledge of window functions! 

Thank you so much for reading. If you have questions or just want to get in touch with me, don’t hesitate to contact me at mtrentz.com.

All images by the author unless stated otherwise.

Shape
Shape
Stay Ahead

Explore More Insights

Stay ahead with more perspectives on cutting-edge power, infrastructure, energy,  bitcoin and AI solutions. Explore these articles to uncover strategies and insights shaping the future of industries.

Shape

AI workloads shake up observability market

There are 19 vendors that made the cut for Gartner’s new report. Its Leaders quadrant includes (alphabetically) Chronosphere, Coralogix, Datadog, Dynatrace, Elastic, Grafana Labs, IBM, and New Relic. The Challengers are Alibaba Cloud, Amazon Web Services, LogicMonitor, Microsoft, and Splunk. The two Visionaries are BMC Helix and Honeycomb. Those dubbed

Read More »

Huawei eying possible DRAM market entry

Chinese tech giant Huawei is reportedly entering the DRAM manufacturing business in a bid to cash in on the insane profitability of memory sales. Three firms – Micron Technology, SK hynix, and Samsung Electronics — account for 95% of the DRAM on the market worldwide. The rest is small players,

Read More »

IBM targets AI edge with Power server, software upgrades

IBM has bolstered its Power server portfolio with a new edge S1112 server and announced IBM Power Autonomous Operations, an AI agent that helps customers monitor Power systems and autonomously resolve issues to keep operations running smoothly. Additional software upgrades are aimed at helping customers deploy and manage AI infrastructure

Read More »

S&P Global: Hormuz vessel transits fall amid heightened security risks

Vessel traffic through the Strait of Hormuz remained subdued July 10-12 as heightened regional security risks continued to weigh on movements through the strategic waterway, according to S&P Global MINT and S&P Global Commodities at Sea data. A total of 73 vessels transited the strait during the 3-day period, averaging fewer than 25 crossings/day. Transits fell to 11 on July 12, the lowest since June 14, after Iran declared the strait closed amid what the Persian Gulf Strait Authority described as “illegal movements” of US military forces in the region. No inbound crossings were recorded July 12, the first such occurrence since June 12. Six of the day’s 11 transits were assessed as compliant vessels. Total crossings were 32 on July 10 and 30 on July 11. The Joint Maritime Information Center (JMIC) said July 12 that the regional threat level remained severe. Despite Iran’s closure declaration, JMIC said the southern route remained available and had been expanded for two-way vessel traffic. Energy carriers—including oil, chemical, LPG, and LNG tankers—accounted for about 48% of transits July 10-12. About two-thirds of energy-carrier crossings involved compliant vessels, although only 10 compliant energy carriers entered the Persian Gulf, mostly without visible automatic identification system (AIS) signals. Inbound tanker capacity also softened. An average 6.5 million b/d of new oil and LPG tanker capacity entered the Gulf through Hormuz July 1-12, with VLCCs and Suezmaxes accounting for nearly 80%. Average inbound capacity fell to 6 million b/d July 10-12 from 8.5 million b/d in the first week of July. All compliant outbound energy carriers transiting Hormuz during the 3-day period did so without visible AIS signals, including ADNOC-operated LNG carrier AL HAMRA and several VLCC and product tankers. Iran-linked and US-sanctioned vessels accounted for nearly 60% of all crossings during the period.

Read More »

Beyond AI Pilots: Scaling AI-Enabled Decision Making in Energy

Date: Thursday, August 6, 2026Time: 11:00 AM (GMT-04:00) Eastern Time – New YorkDuration: 60 minutes Already registered? Click here to log in now. Artificial Intelligence is rapidly becoming a strategic priority across industrial organizations, yet many companies continue to struggle with fragmented data, disconnected workflows, and AI initiatives that never move beyond pilot projects. The challenge is not access to AI—it is creating the business context, governance, and lifecycle intelligence needed to transform AI insights into measurable operational outcomes. Join Siemens Digital Industries Software to learn how Intelligence Center X, part of the Siemens Xcelerator portfolio, helps organizations connect enterprise data, workflows, and AI capabilities into a single governed environment where people and AI work together to drive faster, more informed decisions. In this session, we’ll explore how organizations can: • Move beyond isolated AI experiments to enterprise-scale deployment • Connect engineering, manufacturing, operations, supply chain, and service data into a unified intelligence framework • Enable AI agents to operate within governed, human-in-the-loop business processes • Improve operational performance through AI-assisted decision-making • Accelerate issue resolution, reduce manual effort, and increase organizational agility Attendees will also learn how Intelligence Center X combines lifecycle intelligence, industrial data models, AI orchestration, and low-code application development to create production-ready AI solutions that deliver measurable business value. Real-world examples will demonstrate how organizations have achieved significant improvements, including reductions in manual effort, faster issue resolution, improved data quality, and enhanced decision-making capabilities. Whether you are responsible for digital transformation, operations, manufacturing, engineering, or executive strategy, this webinar will provide practical insight into building a scalable foundation for industrial AI and creating a future where people and AI work together to drive business outcomes.

Read More »

TotalEnergies lets drilling, completions contract for Suriname deepwater oil project

TotalEnergies has let contracts to Halliburton for work on the GranMorgu deepwater oil development project offshore Suriname. The workscope includes drilling and completions services for a long-term program that includes applying integrated digital workflows, real time data, and remote operations control for drilling and completions. As part of the project scope, Halliburton worked with local suppliers to upgrade its liquid mud and cement plant and supported construction of Suriname’s first completions and drilling workshop, featuring advanced maintenance and repair capabilities, the service provider said in a release July 13. The aim of the GranMorgu project is to develop resources on Block 58, which lies about 150 km off the Surinamese coast. Specifically, Sapakara and Krabdagu fields, which contain estimated recoverable reserves of nearly 760 million bbl, TotalEnergies noted on its website. The project’s floating production, storage, and offloading unit (FPSO), with a capacity of 220,000 b/d, is based on tested design principles of units in nearby Guyana and designed for potential future tie-in of satellite fields. Production start-up is expected in 2028. TotalEnergies is operator of the project with 40% interest. Partners are APA Corp. (40%) and state-owned Staatsolie Maatschappij Suriname NV (20%).

Read More »

Aramco lets stimulation, completion services contract for unconventional gas development

Saudi Aramco has awarded Halliburton a multi-year contract to provide stimulation and completion services for the company’s unconventional gas development program in Saudi Arabia. Halliburton said July 15 that the award is part of a broader multibillion-dollar contract framework supporting the Kingdom’s unconventional resource expansion. Under the agreement, Halliburton will deploy intelligent fracturing automation technologies designed to optimize treatment performance in real time and support execution across multiwell development campaigns. The company said the technologies will enable greater digital integration across field operations. Development of the Jafurah unconventional gas field, the Middle East’s largest liquids-rich shale gas play, is under way. In support of the program, Halliburton plans to expand local manufacturing capacity, strengthen its supply chain network, and increase workforce development initiatives within the Kingdom as activity levels continue to grow. “Beginning in the third quarter of 2026, Halliburton will deploy the Kingdom’s first fully integrated intelligent fracturing platform through OCTIV® Auto Frac and Sensori™ fracturing monitoring services to contribute to asset value for one of the world’s largest unconventional fields,” said Rami Yassine, senior vice-president, Eastern Hemisphere, Halliburton. Jafurah background Jafurah is a key component of Aramco’s gas expansion strategy intended to help meet rising demand for natural gas in power generation and industry. In February 2026, the operator said it seeks to expand sales gas production capacity by about 80% by 2030 compared with 2021 production levels. At the time, Aramco said unconventional shale gas output from Jafurah began in December 2025. The field covers about 17,000 sq km and is estimated to contain 229 tcf of raw gas and 75 billion stb of condensate. Aramco expects the development to produce 2 bcfd of sales gas, 420 MMscfd of ethane, and about 630,000 b/d of high-value liquids by 2030.

Read More »

Digitalization paying off for Rompetrol’s Petromidia refinery

Rompetrol Rafinare SA—jointly owned by Kazakhstan’s state-owned JSC NC KazMunayGas (KMG) subsidiary KMG International NV (54.63%) and Romania’s Ministry of Economy, Energy & Business Environment (44.7%)—is using proprietary operations management software from Emerson Electric Co. to improve alarm performance its more than 5-million tonne/year Petromidia refinery in Năvodari, Romania, on the Black Sea. To date, implementation of Emerson’s DeltaV AgileOps operations management software has helped reduce distributed control system (DCS) alarm volumes at the Petromidia refinery by more than 95%, the service provider said on July 14. Emerson said the project improved alarm performance, increased operator effectiveness, and brought alarm rates within the Engineering Equipment and Materials Users Association (EEMUA) 191 guideline recommendations. Before implementation of DeltaV AgileOps, alarm behavior at the refinery—Romania’s largest—expanded beyond recommended best practices, including high alarm volumes during plant disturbances, nuisance-chattering alarms, and alarms that remained active during normal operation. To address those issues, Rompetrol Rafinare worked with KMG International’s engineering and maintenance services provider SC Rominserv SRL to improve alarm quality and reduce nuisance alarms across the refinery. Use of DeltaV AgileOps—which pulls alarm and event data directly from the DeltaV DCS running the plant—provided continuous visibility into alarm performance, including average and peak alarm rates, recurring alarm sequences, and time spent outside recommended operating thresholds, Emerson said. Following implementation, engineering teams at the refinery used performance dashboards and historical trending to identify high-frequency alarms, stale alarms, and nuisance “bad actor” alarms responsible for disproportionate alarm activity. The teams evaluated alarm behavior during steady-state operation, startup conditions, and process disturbances, then assessed proposed changes to alarm limits, priorities, and suppression strategies against plant data. Emerson said the project reduced alarm generation to fewer than 50,000 alarms/month from more than 2 million alarms/month during normal operation. Emerson—which linked the outcome to EEMUA 191 guidance that

Read More »

EIA: US crude inventories down 1.7 million bbl

US crude oil inventories for the week ended July 10, excluding the Strategic Petroleum Reserve, decreased by 1.7 million bbl from the previous week, according to data from the US Energy Information Administration (EIA). At 409.7 million bbl, US crude oil inventories are about 6% below the 5-year average for this time of year, the EIA report indicated. EIA said total motor gasoline inventories decreased by 1.5 million bbl from last week and are 8% below the 5-year average for this time of year. Finished gasoline inventories and blending components inventories both decreased last week. Distillate fuel inventories increased by 4.6 million bbl last week and are about 11% below the 5-year average for this time of year. Propane-propylene inventories increased by 3 million bbl from last week and are 28% above the 5-year average for this time of year, EIA said. US crude oil refinery inputs averaged 17.1 million b/d for the week ended July 10, which was 99,000 b/d more than the previous week’s average. Refineries operated at 96.2% of capacity. Gasoline production decreased, averaging 9.6 million b/d. Distillate fuel production increased, averaging 5.3 million b/d. US crude oil imports averaged 5.7 million b/d, up 60,000 b/d from the previous week. Over the last 4 weeks, crude oil imports averaged about 5.5 million b/d, 12.2% less than the same 4-week period last year. Total motor gasoline imports averaged 354,000 b/d. Distillate fuel imports averaged 93,000 b/d.

Read More »

The AI Infrastructure Split Screen: Capital Rush Meets Community Resistance

It would be difficult to construct a more revealing snapshot of the AI infrastructure market than the one delivered in mid-July. In the same news cycle, Csquare completed a billion-dollar initial public offering, Switch was linked to a potential $10 billion IPO, and Databricks reached a reported valuation of $188 billion. At the project level, developers advanced or disclosed campuses measured not in tens or hundreds of megawatts, but in gigawatts—from Meta’s expanding Louisiana complex and Google’s reported Wyoming plans to new Crusoe, QTS, MARA and Tract developments. Yet the same week brought a state-level permitting pause in New York, a decisive project rejection in Palm Beach County, planned protests across more than 20 states, and fresh disputes over parkland, water availability and local control. This is the data center and AI landscape in 2026: capital is abundant but increasingly discriminating; power is more valuable than the underlying real estate; and community consent has become nearly as important as interconnection capacity. Public Markets Put Different Prices on the AI Stack The capital-market headlines illustrated how differently investors are valuing the various layers of AI infrastructure. Csquare priced 50 million shares at $21, raising approximately $1.05 billion and establishing an equity valuation of roughly $3.2 billion. The offering was substantial, but it priced below the proposed $23-to-$27 range, and the shares finished their first trading day slightly below the offer price. Brookfield retained approximately 67% of the company’s voting power following the transaction. That reception contrasts sharply with the valuation being discussed for Switch. The DigitalBridge-backed operator has reportedly engaged Goldman Sachs and JPMorgan for a potential IPO that could raise as much as $10 billion and value Switch near $80 billion, including debt. The transaction remains prospective, but the figure is striking when compared with the $11 billion take-private agreement

Read More »

New York State just hit pause on the AI data center boom

The moratorium could result in some “border-hopping,” with enterprises hosting local servers in adjacent states like Pennsylvania, Connecticut, or New Jersey, but that’s not likely to be widespread, Kimball noted. The realistic regional impact will be “more of a slow squeeze rather than a shock,” he said. This could result in tighter colocation availability and firmer pricing in the New York Metropolitan area over the next few years. Cloud providers may also steer new AI capacity to regions like Georgia, Ohio, Texas, and Utah, where power and permitting are more predictable. An inflection point, but more trickle-down than direct impact Indeed, noted Jeremy Roberts, senior director for research and content at Info-Tech Research Group, the moratorium is an “inflection point” and a “way to placate an increasingly angry public,”.

Read More »

TeraWulf’s $19B Anthropic Lease Puts Its Brownfield AI Strategy to the Test

He added that the company’s strategy is centered on owning and operating critical infrastructure, maintaining direct relationships with customers and controlling the long-term evolution of its campuses. This Model Differs Significantly from the Previous Abernathy JV TeraWulf and Fluidstack created the Abernathy venture in 2025 to develop a 168-MW critical IT load campus on approximately 120 acres near Abernathy, Texas. The project’s total utility requirement has been described as approximately 240 MW. Fluidstack committed to a 25-year lease at the campus, with Google providing approximately $1.3 billion of credit support for Fluidstack’s obligations. TeraWulf acquired a 50.1% interest in the joint venture through an investment of approximately $450 million. The project subsequently issued $1.3 billion in senior secured notes to support construction and related expenses. The Abernathy agreements were expected to produce approximately $9.5 billion in contracted revenue for the joint venture over the initial 25-year term. Construction has been advancing toward delivery during the second half of 2026. Following the sale, Fluidstack and the other purchasers will control the project. TeraWulf agreed to sell its Abernathy interest for approximately $530 million, compared with its $450 million investment in the joint venture. The consideration is scheduled to be paid in three installments through April 2027, with the proceeds expected to support investment in infrastructure opportunities that TeraWulf intends to own and operate directly. The decision does not necessarily indicate that TeraWulf has become less interested in partnerships with Fluidstack. Fluidstack remains an important tenant at TeraWulf’s Lake Mariner campus in New York, and the companies have built a substantial pipeline of AI infrastructure together. In infrastructure terms, TeraWulf is acting as both developer and capital allocator. It originated the Abernathy project, helped secure the customer and financing structure, advanced construction and is now monetizing its interest before the campus begins

Read More »

Comparing Space-Driven Data Center Strategies: Modular Satellites vs. Integrated Rocket Nodes

In addition to developing radiation-tolerant computing, optical communications, deployable solar arrays and orbital thermal-management systems, Cowboy must successfully design, manufacture, test and license a new rocket. Its launch vehicle would require authorization from the Federal Aviation Administration in addition to the approvals needed for the satellite constellation. Cowboy nevertheless enters the race with considerably more capital than Orbital. The company announced a $275 million Series B round in May at a reported $2 billion valuation. Founded in 2024 by Robinhood co-founder Baiju Bhatt, with a focus on space-based solar power before expanding into orbital computing and launch systems. One Hundred Kilowatts Versus One Megawatt The clearest distinction between the two proposals is the capacity assigned to each node. Orbital’s production design calls for approximately 100 kilowatts of computing power per satellite. Cowboy is targeting megawatt-class spacecraft, potentially giving each Stampede node approximately 10 times the power capacity of an Orbital satellite. At their stated maximum scales, Orbital’s 100,000 satellites would provide approximately 10 gigawatts. If Cowboy ultimately achieved one megawatt across all 20,000 Stampede spacecraft, its theoretical aggregate capacity would approach 20 gigawatts. Those figures should be treated as design objectives, not capacity forecasts. Neither company has demonstrated even one operational node at its proposed production power level. Orbital’s smaller satellites may be easier to test and deploy incrementally. The company can begin with a single hosted GPU, progress to a purpose-built prototype and expand as launch economics and customer demand permit. Cowboy’s larger nodes could provide more useful computing capacity with fewer satellites and potentially fewer launches. Combining the rocket stage and data center would also reduce the amount of structural mass that does not directly support power generation or computing. The tradeoff is concentration risk. The failure of a megawatt Cowboy spacecraft would remove considerably more capacity than

Read More »

Google Cloud configuration update disrupts VMware Engine stretched clusters

“Google made a network setting change that accidentally broke the connection between the two data center zones in VMware Engine. The virtual machines themselves kept running fine, but nobody could reach them, and there was a risk that some machines might lose the ability to save data properly. This indicates that even managed cloud infrastructure can experience failures in critical shared network components,” said Pareekh Jain, CEO at  EIIRTrend & Pareekh Consulting. Neil Shah, vice president at Counterpoint Research, said the real culprit here is the SDN orchestration control plane, where a routine internal network update or configuration tweak introduced routing failure across multiple zones. “While most of the physical nodes are distributed for exactly this redundancy purpose, they are still tightly coupled to a singular shared orchestration fabric, so if that control plane crashes, then everything comes crashing down, and the physical distributed nodes become irrelevant.” Stretched clusters fall short Although the outage did not bring down virtual machines, the incident undermined the primary reason enterprises deploy stretched clusters.

Read More »

AI’s Future Must Return to the Edge: How Power Constraints and Local Politics Are Redefining AI Infrastructure

Over the past two years, AI build plans have driven a sharp escalation in projected data center power demand. One recent assessment1 found that the U.S. disclosed data center development pipeline reached roughly 241 gigawatts by the end of 2025—an increase of about 159% in a single year—illustrating the unprecedented pace at which AI infrastructure demand is expanding. Forecasts from major analysts indicate that total data center power consumption could grow at least 50% by 2027 and potentially as much as 165% by 2030, with AI training and inference responsible for most of the incremental load.2 At this pace, planned AI capacity is growing faster than electric infrastructure can realistically be expanded. In many markets, available land and fiber are not the limiting factors; dependable megawatt delivery is.3 At the facility level, AI hardware is moving standard designs into new ranges. Power densities that once centered around 10–20 kW per rack are being replaced by configurations nearer 40 kW, with dense AI racks pushing toward 85 kW today and credible roadmaps to 200–250 kW per rack by 2030, though we’ve all seen the reports of even larger. These levels do not only affect cooling and white‑space layouts; they materially change the electrical infrastructure required per room and per building, and by extension the strain on local grids. On the power‑system side, constraints are now explicit. Transmission operators and regulators are stating that current generation, interconnection, and build‑out timelines are not sufficient to accommodate another decade of large demand centers in their present form. Analysts tracking AI data center energy demand point to electricity, grid access, and firm capacity as the primary constraints on new builds, with grid bottlenecks and transmission limitations flagged as risks for up to 20% of planned projects.4, 5  At the facility level, AI hardware is moving

Read More »

Microsoft will invest $80B in AI data centers in fiscal 2025

And Microsoft isn’t the only one that is ramping up its investments into AI-enabled data centers. Rival cloud service providers are all investing in either upgrading or opening new data centers to capture a larger chunk of business from developers and users of large language models (LLMs).  In a report published in October 2024, Bloomberg Intelligence estimated that demand for generative AI would push Microsoft, AWS, Google, Oracle, Meta, and Apple would between them devote $200 billion to capex in 2025, up from $110 billion in 2023. Microsoft is one of the biggest spenders, followed closely by Google and AWS, Bloomberg Intelligence said. Its estimate of Microsoft’s capital spending on AI, at $62.4 billion for calendar 2025, is lower than Smith’s claim that the company will invest $80 billion in the fiscal year to June 30, 2025. Both figures, though, are way higher than Microsoft’s 2020 capital expenditure of “just” $17.6 billion. The majority of the increased spending is tied to cloud services and the expansion of AI infrastructure needed to provide compute capacity for OpenAI workloads. Separately, last October Amazon CEO Andy Jassy said his company planned total capex spend of $75 billion in 2024 and even more in 2025, with much of it going to AWS, its cloud computing division.

Read More »

John Deere unveils more autonomous farm machines to address skill labor shortage

Join our daily and weekly newsletters for the latest updates and exclusive content on industry-leading AI coverage. Learn More Self-driving tractors might be the path to self-driving cars. John Deere has revealed a new line of autonomous machines and tech across agriculture, construction and commercial landscaping. The Moline, Illinois-based John Deere has been in business for 187 years, yet it’s been a regular as a non-tech company showing off technology at the big tech trade show in Las Vegas and is back at CES 2025 with more autonomous tractors and other vehicles. This is not something we usually cover, but John Deere has a lot of data that is interesting in the big picture of tech. The message from the company is that there aren’t enough skilled farm laborers to do the work that its customers need. It’s been a challenge for most of the last two decades, said Jahmy Hindman, CTO at John Deere, in a briefing. Much of the tech will come this fall and after that. He noted that the average farmer in the U.S. is over 58 and works 12 to 18 hours a day to grow food for us. And he said the American Farm Bureau Federation estimates there are roughly 2.4 million farm jobs that need to be filled annually; and the agricultural work force continues to shrink. (This is my hint to the anti-immigration crowd). John Deere’s autonomous 9RX Tractor. Farmers can oversee it using an app. While each of these industries experiences their own set of challenges, a commonality across all is skilled labor availability. In construction, about 80% percent of contractors struggle to find skilled labor. And in commercial landscaping, 86% of landscaping business owners can’t find labor to fill open positions, he said. “They have to figure out how to do

Read More »

2025 playbook for enterprise AI success, from agents to evals

Join our daily and weekly newsletters for the latest updates and exclusive content on industry-leading AI coverage. Learn More 2025 is poised to be a pivotal year for enterprise AI. The past year has seen rapid innovation, and this year will see the same. This has made it more critical than ever to revisit your AI strategy to stay competitive and create value for your customers. From scaling AI agents to optimizing costs, here are the five critical areas enterprises should prioritize for their AI strategy this year. 1. Agents: the next generation of automation AI agents are no longer theoretical. In 2025, they’re indispensable tools for enterprises looking to streamline operations and enhance customer interactions. Unlike traditional software, agents powered by large language models (LLMs) can make nuanced decisions, navigate complex multi-step tasks, and integrate seamlessly with tools and APIs. At the start of 2024, agents were not ready for prime time, making frustrating mistakes like hallucinating URLs. They started getting better as frontier large language models themselves improved. “Let me put it this way,” said Sam Witteveen, cofounder of Red Dragon, a company that develops agents for companies, and that recently reviewed the 48 agents it built last year. “Interestingly, the ones that we built at the start of the year, a lot of those worked way better at the end of the year just because the models got better.” Witteveen shared this in the video podcast we filmed to discuss these five big trends in detail. Models are getting better and hallucinating less, and they’re also being trained to do agentic tasks. Another feature that the model providers are researching is a way to use the LLM as a judge, and as models get cheaper (something we’ll cover below), companies can use three or more models to

Read More »

OpenAI’s red teaming innovations define new essentials for security leaders in the AI era

Join our daily and weekly newsletters for the latest updates and exclusive content on industry-leading AI coverage. Learn More OpenAI has taken a more aggressive approach to red teaming than its AI competitors, demonstrating its security teams’ advanced capabilities in two areas: multi-step reinforcement and external red teaming. OpenAI recently released two papers that set a new competitive standard for improving the quality, reliability and safety of AI models in these two techniques and more. The first paper, “OpenAI’s Approach to External Red Teaming for AI Models and Systems,” reports that specialized teams outside the company have proven effective in uncovering vulnerabilities that might otherwise have made it into a released model because in-house testing techniques may have missed them. In the second paper, “Diverse and Effective Red Teaming with Auto-Generated Rewards and Multi-Step Reinforcement Learning,” OpenAI introduces an automated framework that relies on iterative reinforcement learning to generate a broad spectrum of novel, wide-ranging attacks. Going all-in on red teaming pays practical, competitive dividends It’s encouraging to see competitive intensity in red teaming growing among AI companies. When Anthropic released its AI red team guidelines in June of last year, it joined AI providers including Google, Microsoft, Nvidia, OpenAI, and even the U.S.’s National Institute of Standards and Technology (NIST), which all had released red teaming frameworks. Investing heavily in red teaming yields tangible benefits for security leaders in any organization. OpenAI’s paper on external red teaming provides a detailed analysis of how the company strives to create specialized external teams that include cybersecurity and subject matter experts. The goal is to see if knowledgeable external teams can defeat models’ security perimeters and find gaps in their security, biases and controls that prompt-based testing couldn’t find. What makes OpenAI’s recent papers noteworthy is how well they define using human-in-the-middle

Read More »