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 data boom gives tape storage a new lease on life

“We are seeing unprecedented data growth combined with increasing cost, energy, and cyber resilience pressures across the industry,” said Hugues Meyrath, CEO of Quantum in a statement. “As organizations adapt to this new reality, tape is increasingly viewed as a strategic component of modern data infrastructure, delivering predictable economics and

Read More »

DOE’s Alternative Fuels and Feedstocks Office Announces up to $58 Million to Promote Chemical Innovation

WASHINGTON—The U.S. Department of Energy’s (DOE) Alternative Fuels and Feedstocks Office (AFFO) today announced up to $58 million in funding to advance novel, high-impact chemical technologies that use domestically sourced alternative and waste feedstocks. Projects funded through this initiative will advance new methods of chemical production that maximize the use of America’s vast biomass and waste resources. This funding supports President Trump’s Executive Order, Unleashing American Energy, which calls for targeted federal investment in technology innovation that strengthens the U.S. chemical sector.  “By investing in projects that use our abundant domestic resources and build strong industry partnerships, DOE will bolster American chemical manufacturing,” said AFFO Director Valerie Sarisky-Reed. “This funding will turn cutting-edge research into market-ready industrial solutions, strengthening our chemical supply chain, lowering costs for U.S. businesses and consumers, and securing America’s economic future.” The Accelerating Scale-up and Pre-piloting of Emerging Chemical Technologies (ASPECT) funding opportunity promotes the development and commercialization of chemical technologies that lower costs, enhance performance, reduce reliance on imports, and unlock strong market growth potential. ASPECT seeks to reduce time to market by moving projects from laboratory research to pre-pilot scale testing. It includes two main topic areas:  Topic Area 1: Bench ASPECT Proposals should support the development and adoption of new technologies for producing chemicals from alternative feedstocks, moving beyond proof-of-concept to bench and pre-pilot scale. Topic Area 2: Pre-pilot ASPECT Proposals should aim to accelerate the development and market entry of strategically valuable, domestically produced chemicals. AFFO will host an informational webinar for potential applicants on September 11, 2026, to explain the streamlined application and review process.  Applicants must submit concept papers by October 9, 2026, at 5:00 p.m. ET, to be eligible to submit a Stage 1 full application. To learn more about topic areas, registration requirements, applicant eligibility, webinar registration, and the Teaming Partner list, visit the

Read More »

Energy Secretary Secures Carolinas’ Grid Ahead of Holiday Weekend

WASHINGTON—The U.S. Department of Energy (DOE) today issued an emergency order to mitigate the risk of blackouts in the Carolinas amid hot weather conditions. Issued pursuant to Section 202(c) of the Federal Power Act, the order authorizes Duke Energy Carolinas, LLC (Duke) to dispatch specified units and to order their operation as needed to maintain reliability. The order also authorizes Duke, in collaboration with its Transmission Owners, to direct backup generation resources to operate as a last resort before declaring an Energy Emergency Alert (EEA) 3 or during an EEA 3. This order was issued pursuant to an application from Duke submitted on September 3, 2026. “Thanks to this emergency order, Americans will not have to worry about losing access to affordable power this Labor Day weekend,” said U.S. Secretary of Energy Chris Wright. “The previous administration’s energy subtraction policies weakened the grid, leaving Americans more vulnerable during events like this. Under President Trump’s leadership, we are ensuring that hardworking American families and businesses in the Carolinas’ have continued access energy to power and cool their homes.” On day one, President Trump declared a national energy emergency after the Biden administration’s energy subtraction agenda left behind a grid increasingly vulnerable to the risk of blackouts. The order is in effect beginning on September 3, 2026, through September 8, 2026. 

Read More »

President Trump’s Energy Dominance Agenda is Delivering for American Energy Workers

WASHINGTON—This Labor Day, the U.S. Department of Energy (DOE) is celebrating the hardworking men and women who power America with the release of the 2026 U.S. Energy and Employment Report (USEER). The annual report highlights strong job growth across critical energy sectors at the heart of President Trump’s Energy Dominance agenda. America’s most reliable energy sectors are adding jobs and powering industries across the country. These critical sectors deliver the affordable, reliable, and secure energy that American families, businesses, and industries depend on. After years of decline under the previous administration, America’s coal and nuclear power workforces are growing again under President Trump’s leadership. “Energy is the sector that enables every other sector of our economy, and America’s energy workers make it all possible,” said U.S. Secretary of Energy Chris Wright. “These hardworking men and women keep our lights on, our factories running, and our economy growing. President Trump’s Energy Dominance agenda is putting them first and delivering the affordable, reliable, and secure energy America needs.” Energy careers are also delivering bigger paychecks for American workers. The median energy-sector salary reached $63,000—24% higher than the U.S. median salary. America’s growing energy needs are creating the jobs of the future. The 2026 USEER’s new Future Outlook chapter highlights rising demand for skilled energy workers and growing competition for talent across energy and other expanding industries. These trends are opening new pathways to high-paying, skilled careers for American workers. As energy demand grows, America’s energy workforce will power the next generation of American industry, innovation, and economic growth. Highlights from the report include:  •    The median energy-sector salary was $63,000, 24% higher than the national median salary of $51,000. •    Natural gas transmission and distribution added 12,500 workers, growing employment by 5%. •    Nuclear power added 2,300 workers, growing employment by 4%. •    Coal power generation added 2,800 workers, growing

Read More »

Hydrocarbons and Geothermal Energy Office Issues Request for Information to Advance Private Investment in Innovative American Energy Technologies

WASHINGTON — The U.S. Department of Energy’s (DOE) Hydrocarbons and Geothermal Energy Office (HGEO), in collaboration with the Office of Technology Commercialization, today announced a Request for Information (RFI) seeking stakeholder input on opportunities to better connect private capital and public-private partnership programs with coal, oil and gas, and geothermal energy technologies.  The RFI supports President Trump’s American Energy Dominance agenda by strengthening connections among American energy innovators, industry and private capital to accelerate commercialization, lower energy costs, strengthen reliability and energy security, and power American prosperity. This effort builds on the recently announced Small Business Investment Company-Energy (SBIC-E) Initiative, announced by U.S. Energy Secretary Chris Wright and SBA Administrator Kelly Loeffler to mobilize private capital for American energy technologies and businesses.  “President Trump has made American energy innovation and dominance a priority, and connecting promising technologies with the right technical expertise, industry partners and sources of capital is critical to delivering on that vision,” said DOE Acting Assistant Secretary for the Hydrocarbons and Geothermal Energy Office Curt Coccodrilli. “Through this Request for Information, we would like to hear directly from investors, innovators and industry about the opportunities and challenges they see in commercializing coal, oil and gas, and geothermal energy technologies.” “Too often, promising American technologies face barriers between development and commercial deployment,” said Anthony Pugliese, DOE Chief Commercialization Officer and Director of the Office of Technology Commercialization. “We want to better understand where those barriers exist and how DOE can work with the private sector to create stronger pathways to market, helping more American energy technologies scale, compete, and succeed.”  DOE is soliciting feedback from investors, industry, academia, research laboratories, government agencies and other stakeholders to better understand investor interest, barriers and opportunities related to the development and commercialization of subsurface energy technologies.   Areas of interest include, but are not

Read More »

Energy Department Announces Geothermal Center of Excellence to Advance Geothermal Technology Innovation and Development

WASHINGTON — The U.S. Department of Energy’s (DOE) Hydrocarbons and Geothermal Energy Office today established a Geothermal Center of Excellence (CoE) to advance President Trump and Secretary Wright’s commitment to delivering affordable, reliable, and secure energy.  The Center will unite expertise and world-class capabilities from across DOE’s National Laboratories to accelerate the discovery and development of gigawatt-scale geothermal energy, resource discovery, and commercial development.  The National Laboratory of the Rockies (NLR) will lead the consortium, with support from the National Energy Technology Laboratory (NETL).  “America has vast geothermal resources beneath our feet that can provide reliable, around-the-clock energy while strengthening our energy dominance,” said DOE Under Secretary for Energy Kyle Haustveit. “Under President Trump’s leadership, the Geothermal Center of Excellence will leverage the world-class scientific and engineering expertise of our national laboratories in partnership with industry to unlock gigawatt-scale power generation, expand American energy production, and deliver more affordable, reliable, and secure energy to the American people.” DOE formally launched the Center at NLR’s campus in Golden, Colorado, bringing together DOE leadership, elected officials, NLR and NETL leadership, laboratory staff, and industry representatives to advance the Center’s vision and priorities.  “The Geothermal Center of Excellence marks an important step in our work to accelerate gigawatt-scale geothermal energy on the U.S. grid,” said DOE Acting Assistant Secretary for the Hydrocarbons and Geothermal Energy Office Curt Coccodrilli. “By driving innovation and enhancing lab-industry collaboration, the Center will help us achieve our goals to enhance reliable baseload power, strengthen grid reliability, and improve long-term energy security.” The Center will also serve as industry’s main entry point to DOE’s National Laboratories. An Industry Advisory Board will provide objective insight into industry-relevant geothermal research needs, accelerate industry-lab partnerships, and advise on Center priorities.  For more information, contact geo.centerofexcellence@nlr.gov.

Read More »

San Matías Pipeline secures $900 million for Vaca Muerta-to-LNG gas pipeline

The remaining $400 million will be contributed by the consortium’s shareholders: Pan American Energy, YPF, Pampa Energía, Harbour Energy, and Golar LNG. The 472-km, 36-in. OD San Matías Pipeline, which will originate at Tratayén, one of Vaca Muerta’s main gas hubs, is designed to transport 27 million cu m/d (MMcmd) of natural gas, aligned with the gas requirements of the two FLNG units. Hilli Episeyo will have LNG production capacity of 2.45 million tonnes/year (tpy) and will require about 11.5 MMcmd of feed gas. Esperanza, previously known as MKII, will add another 3.5 million tpy and require close to 16 MMcmd of feed gas. Hilli Episeyo is expected to begin operations in 2027, followed by Esperanza in 2028. The project also will include a compressor station with about 46,000 hp of installed capacity to maintain required pressure and flow across the system. Pipeline construction has been awarded to the SICIM-Víctor Contreras consortium, while OPS will be responsible for the Allen compressor station. IEB Construcciones was selected to manage and coordinate the project’s different construction fronts. In August, the first 36-in. line pipe manufactured in India began arriving at the Port of San Antonio Este. Construction is scheduled to begin in August 2026, with completion targeted for mid-2028. The project was admitted to Argentina’s Large Investment Incentive Regime (RIGI) in June and has environmental impact approvals from Neuquén and Río Negro provinces.

Read More »

ERCOT Puts Texas AI Megawatts to the Test

Texas has no shortage of proposed data center megawatts. The harder question is how many of them are real. That distinction is becoming central to the Electric Reliability Council of Texas (ERCOT) as the state works through an unprecedented wave of AI, hyperscale and other large-load requests. In June, ERCOT said it was tracking more than 438 GW of proposed large loads, nearly 89% associated with data centers. By Aug. 3, Gov. Greg Abbott said ERCOT was considering approximately 474 GW of connection requests, roughly 90% from data centers and more than five times the system’s record peak demand. Neither figure represents a forecast of what will actually get built. And that is increasingly the point. ERCOT’s new Batch Zero process is beginning to put harder boundaries around Texas’ enormous development pipeline, asking which projects have enough maturity, technical information and commitment to warrant space in the transmission plan. At the same time, new requirements surrounding voltage ride-through and dynamic modeling are forcing another realization on the AI infrastructure industry: at hundreds of megawatts, a data center is no longer simply a customer at the edge of the grid. Its behavior can affect the grid itself. For developers, utilities and investors, Texas is becoming a large-scale test of what separates an announced AI campus from executable infrastructure. The Queue Is Not the Grid The sheer scale of ERCOT’s large-load queue can obscure how early many projects remain. ERCOT’s April 2026 monthly report offered a revealing snapshot. Large-load applications totaled 445.8 GW through 2033, but 321 GW had no studies submitted to ERCOT. Another 93.7 GW was under ERCOT review, while 22 GW had met the applicable Section 9.5 requirements. Against that enormous development funnel, ERCOT reported just 5.9 GW of observed energized large loads, with another 3.2 GW approved to

Read More »

DCF Trends Summit: AI Compresses the Data Center Hardware Lifecycle and Raises the Stakes for ITAD

The AI infrastructure race is largely a story about getting more computing into data centers faster. But the accelerated hardware cycle is creating an equally consequential problem at the other end of the rack: getting yesterday’s equipment back out while it is still valuable. GPU systems built around increasingly dense and specialized AI architectures are beginning to challenge traditional assumptions about IT asset disposition, or ITAD. Where conventional enterprise infrastructure might remain in service for three to five years, newer GPU platforms can face refresh cycles of 18 to 24 months, according to Josh Humm, Data Center Solutions Manager at Dynamic Lifecycle Innovations. That compression changes the economics as well as the mechanics of decommissioning. “The faster we can get the materials out of your building, the more it’s worth, the more we can return to your program,” Humm said. Humm joined DCF Contributing Editor Doug Black for a DCF Show podcast recorded at the third annual Data Center Frontier Trends Summit, held Aug. 4-6 in Reston, Virginia. Their conversation focused on a less visible part of the AI infrastructure buildout: what happens to servers, accelerators, memory, storage and networking gear when the next generation arrives. The answer increasingly touches facility operations, data security, logistics, sustainability and potentially millions of dollars in recoverable hardware value. AI Hardware Changes the Exit Path AI systems create some obvious physical challenges for decommissioning. Traditional ITAD teams accustomed to pulling 1U and 2U servers out of air-cooled racks may instead encounter liquid-cooling manifolds, substantially heavier systems and equipment requiring specialized rigging and handling procedures. Humm said some systems can weigh between 5,000 and 6,000 pounds. “We’re not pulling out just 1U, 2U servers out of racks anymore,” he said. Liquid cooling adds another layer. Removing infrastructure designed around direct-to-chip or other liquid-cooling architectures can

Read More »

Data Center Jobs: Engineering, Construction, Commissioning, Sales, Field Service and Facility Tech Jobs Available in Major Data Center Hotspots

Each month Data Center Frontier, in partnership with Pkaza, posts some of the hottest data center career opportunities in the market. Here’s a look at some of the latest data center jobs posted on the Data Center Frontier jobs board, powered by Pkaza Critical Facilities Recruiting. Looking for Data Center Candidates? Check out Pkaza’s Active Candidate / Featured Candidate Hotlist  CFD Engineer – Data Center Mechanical Design New York, NY (remote)This position is also available as a remote role anywhere in the U.S. in addition to key markets such as Cedar Rapids, IA; Kansas City, CA or White Plains, NY. Our client is an engineering design and commissioning company that has a national footprint and specializes in MEP critical facilities design. They provide design, commissioning, consulting and management expertise in the critical facilities space. They have a mindset to provide reliability, energy efficiency, and sustainable design expertise when providing these consulting services for enterprise, colocation and hyperscale companies. This career-growth minded opportunity offers exciting projects with leading-edge technology and innovation as well as competitive salaries and benefits.  Electrical Commissioning Agent – Data Centers Columbus, OH (limited travel) Non-traveling CxA positions available in: Indianapolis, IN; Cedar Rapids, IA; Phoenix, AZ; Atlanta, GA and Austin, TX. Traveling CxA based near any major airport, otherwise traveling to: New York, NY; White Plains, NY; Dallas, TX; Richmond, VA; Montvale, NJ; Charlotte, NC; Salt Lake City, UT; Kansas City, MO; Chesterton, IN or Chicago, IL. *** Also looking for a lead EE, ME CxA agents and CxA PMs. *** This opportunity is with a leading EPC company of data center design / build / commissioning solutions. This company provides a complete life cycle of solutions that are custom-fit to the requirements of their client’s mission-critical facilities. This opportunity provides a career-growth minded role with exciting projects with

Read More »

DCFTS 2026: Data Center Development Moves From Projection to Execution

The Data Center Map Gets More Selective For EdgeCore, finding viable development locations has become an exercise in aggressive filtering. Kestler said the company evaluated 172 sites during the previous 12 months to narrow the field to seven locations it wanted to actively manage. Its requirements include roughly 100 acres or more, the ability to support a 300-MVA-or-larger substation, credible utility development timelines and sufficient network proximity to support what Kestler called “interdependent compute” locations. The distinction matters. Not every AI workload needs the same geography, and not every site marketed as available for AI infrastructure can support the combination of land, network, power and timing required to make a project real. Miller placed that process in the context of a data center map already being redrawn by power availability. Northern Virginia’s power constraints in 2022 provided an early warning, redirecting capacity into markets including Atlanta and driving developers farther afield in search of large blocks of electricity. AI has intensified the process. As campus requirements move toward hundreds of megawatts and, in some cases, gigawatt scale, Miller said, fewer locations can satisfy all of the requirements simultaneously. Community acceptance is narrowing the map further. At the same time, Miller pointed to a potential countertrend: the growth of AI inference could create another layer of data center geography. Some inference architectures may favor smaller, distributed facilities rather than concentrating every workload inside enormous campuses. The result could be a more stratified infrastructure market. “Everything everywhere all at once,” Miller said. Build Where Data Centers Are Wanted For large campus development, Kestler offered another increasingly important filter. EdgeCore wants to build where it is wanted. In practical terms, that means targeting municipalities and jurisdictions that have already made deliberate decisions about where data center or other light industrial development belongs. Kestler

Read More »

How States Are Rewriting the Rules for Data Center Growth

Pennsylvania has moved from courting data center investment to setting much stricter terms for how the industry grows. Governor Josh Shapiro’s August 18 executive order creates one of the country’s most comprehensive state-level frameworks for large data centers, linking a more favorable environmental permitting process and state tax treatment to requirements covering power supply, grid costs, local approval, workforce commitments, water use and environmental performance. The order is the latest stage of Shapiro’s Governor’s Responsible Infrastructure Development, or GRID, initiative. GRID was announced in February, detailed in May and partially reinforced through Pennsylvania’s 2026-27 budget in July. The Pennsylvania House also passed legislation intended to codify the standards, but the Senate did not act. Shapiro has now used existing executive and agency authority to put much of the framework into effect immediately. Pennsylvania’s debate has also produced more direct proposals to slow development. Senate Bill 1359 would impose a statewide moratorium on hyperscale data center development and permitting, although the measure remains in the Senate Local Government Committee. A separate measure, Senate Bill 1345, would authorize municipalities to temporarily stop accepting or considering new applications for high-impact data centers for up to 18 months. SB 1345 advanced to second consideration in the Senate in July. Neither measure has become law. What is the Impact on Data Center Development? For data center projects with peak demand exceeding 25 MW, Pennsylvania’s template GRID Consent Order and Agreement provides the mechanism for binding developers to the requirements while allowing the states Department of Environmental Protection (DEP) to review qualifying permit applications on a rolling basis. Developers that decline to sign can still seek permits, but DEP will not begin reviewing their applications until local approvals and required water or wastewater authorizations are secured, and permits will not be handled on a rolling basis.

Read More »

PwC Maps $31.6 Trillion AI Data Center Buildout Through 2050

The scale of the AI infrastructure buildout is becoming easier to describe in trillions than billions. PwC’s inaugural Global Data Centre Outlook 2026–50 projects $31.6 trillion in cumulative global data center capital expenditure through 2050 under its central scenario, with annual spending rising from roughly $800 billion in 2026 to $1.1 trillion in 2030 and $1.8 trillion by 2050. There is also an enormous range around that central case. PwC, working with Oxford Economics, puts plausible cumulative investment at roughly $22 trillion to nearly $50 trillion, depending primarily on how quickly AI adoption progresses. But the most important finding may not be the $31.6 trillion headline. PwC argues that the economics of AI infrastructure are creating a fundamentally different capital cycle from previous infrastructure booms. Data centers are long-lived assets, but the increasingly expensive computing equipment inside them is not. Servers, GPUs, networking systems and other information and communications technology equipment are expected to require replacement on roughly four- to six-year cycles. PwC calculates that every $1 of construction spending can effectively commit the market to approximately $12 of subsequent ICT investment. ICT equipment accounts for about 70% of total data center CapEx in 2026 under its model, rising to 93% by 2050. That creates something closer to a continuously renewing technology platform than a conventional construction cycle. Over a 20-year data center asset life, PwC estimates that a facility could undergo three to five rounds of ICT investment. Increasing rack densities can force corresponding power and cooling upgrades, but the largest recurring expense remains the compute hardware itself. For data center developers and operators, that distinction matters. The economic life of the building increasingly diverges from the technical and financial life of the infrastructure filling it. AI Fragments the Data Center Demand Model The report also sees AI broadening

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 »