I want to retrieve all patients who have lab results greater than 100, but I get a conversion error because some results are not numeric even though I'm filtering them out. FIx the error.

Ik wil alle patiënten ophalen met laboratoriumresultaten hoger dan 100, maar ik krijg een conversiefout omdat sommige resultaten niet numeriek zijn, ook al filter ik ze eruit. Los de fout op.

-- Conversion failed when converting the varchar value 'Pending' to data type int
SELECT
    patient_id,
    result_value
FROM lab_results
WHERE result_value NOT LIKE '%[^0-9]%'
    AND CAST(result_value AS INT) > 100;

SELECT
    patient_id,
    result_value
FROM lab_results
WHERE TRY_CAST(result_value AS INT) > 100;

CREATE TABLE lab_results (
    patient_id INT,
    result_value VARCHAR(50)
);

INSERT INTO lab_results VALUES (1, '150');
INSERT INTO lab_results VALUES (2, '50');
INSERT INTO lab_results VALUES (3, 'Pending');

    @Test
    public void testSafeCast(Connection conn) throws SQLException {
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {

         assertTrue(rs.next(), "Should return the valid numeric row > 100");
            assertEquals("150", rs.getString("result_value"));

         assertFalse(rs.next(), "Should filter out low numbers and non-numeric strings without crashing.");
        }
    }

The solution MUST use TRY_CAST (or similar) to attemp conversion safely, otherwise the conversion will raise an error because SQL is not procedural so order of operations can't be controlled


This query retrieves the names, the total spend and the date of the most recent order of our top buyers (spent more than 1000$ total). Refactor this query to make it more efficient and readable without changing functionality.

Deze query haalt de namen, het totale bedrag en de datum van de meest recente bestelling van onze topkopers (die in totaal meer dan 1000$ hebben uitgegeven) op. Herstructureer deze query om hem efficiënter en leesbaarder te maken zonder de functionaliteit te wijzigen.

SELECT
    c.customer_name,
    (SELECT SUM(amount) FROM orders o WHERE o.customer_id = c.id) as total_spend,
    (SELECT MAX(order_date) FROM orders o WHERE o.customer_id = c.id) as last_order_date
FROM customers c
WHERE (SELECT SUM(amount) FROM orders o WHERE o.customer_id = c.id) > 1000;

WITH CustomerStats AS (
    SELECT
        customer_id,
        SUM(amount) AS total_spend,
        MAX(order_date) AS last_order_date
    FROM orders
    GROUP BY customer_id
),
HighValueCustomers AS (
    SELECT
        customer_id,
        total_spend,
        last_order_date
    FROM CustomerStats
    WHERE total_spend > 1000
)
SELECT
    c.customer_name,
    hvc.total_spend,
    hvc.last_order_date
FROM customers c
INNER JOIN HighValueCustomers hvc
    ON c.id = hvc.customer_id;

CREATE TABLE customers (
    id INT PRIMARY KEY,
    customer_name VARCHAR(50)
);
CREATE TABLE orders (
    id INT PRIMARY KEY,
    customer_id INT,
    amount INT,
    order_date DATE
);
INSERT INTO customers VALUES (1, 'Alice');
INSERT INTO orders VALUES (101, 1, 600, '2023-01-01');
INSERT INTO orders VALUES (102, 1, 500, '2023-01-05');
INSERT INTO customers VALUES (2, 'Bob');
INSERT INTO orders VALUES (201, 2, 900, '2023-02-01');
INSERT INTO customers VALUES (3, 'Charlie');
INSERT INTO orders VALUES (301, 3, 1000, '2023-03-01');

    @Test
    public void testRefactoring(Connection conn) throws SQLException {
        String sql = generatedSqlQuery.toUpperCase().replaceAll("\\s+", " ");

        boolean usesCTE = sql.contains("WITH ");
        boolean usesJoin = sql.contains("JOIN ");

      assertTrue(usesCTE || usesJoin, "Refactoring failed: You must optimize the query using a CTE (WITH) or JOINs instead of correlated subqueries.");

      try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {

            assertTrue(rs.next(), "Should return high value customers.");
            assertEquals("Alice", rs.getString("customer_name"));
            assertEquals(1100, rs.getInt("total_spend"));
            assertEquals(Date.valueOf("2023-01-05"), rs.getDate("last_order_date"));

            assertFalse(rs.next(), "Should strictly filter > 1000 (Bob and Charlie should not appear).");
        }
    }

the solution MUST separate the big query with redundant subqueries into multiple queries with sepration of concerns (i.e. one for the math, one for the filtering, and one for the display), this makes the code mre efficient (less redundancy), more readable, and more maintainable (easier to debug). The unit test includes structural checks (as well as functional checks) to ensure refactoring.


Refactor this code use a CTE, keep the same functionality.

Herstructureer deze code met behulp van een CTE, behoud dezelfde functionaliteit.

SELECT
    patient_name,
    weight_kg,
    height_m,
    CASE
        WHEN (weight_kg / (height_m * height_m)) < 18.5 THEN 'Underweight'
        WHEN (weight_kg / (height_m * height_m)) >= 18.5 AND (weight_kg / (height_m * height_m)) < 25 THEN 'Healthy'
        WHEN (weight_kg / (height_m * height_m)) >= 25 AND (weight_kg / (height_m * height_m)) < 30 THEN 'Overweight'
        WHEN (weight_kg / (height_m * height_m)) >= 30 THEN 'Obese'
    END AS bmi_category
FROM patients;

WITH PatientBMI AS (
SELECT
patient_name,
(weight_kg / (height_m * height_m)) as bmi_score
FROM patients
)
SELECT
patient_name,
bmi_score,
CASE
WHEN bmi_score < 18.5 THEN 'Underweight'
WHEN bmi_score < 25   THEN 'Healthy'    -- Implicitly means ">= 18.5 AND < 25"
WHEN bmi_score < 30   THEN 'Overweight' -- Implicitly means ">= 25 AND < 30"
ELSE 'Obese'
END as bmi_category
FROM PatientBMI;

CREATE TABLE patients (
    patient_name VARCHAR(50),
    weight_kg DECIMAL(10, 2),
    height_m DECIMAL(10, 2)
);

INSERT INTO patients VALUES ('Alice', 50.0, 1.80);

INSERT INTO patients VALUES ('Bob', 70.0, 1.75);

INSERT INTO patients VALUES ('Charlie', 85.0, 1.75);

INSERT INTO patients VALUES ('Diana', 100.0, 1.70);

    @Test
    public void testBMIRefactoring(Connection conn) throws SQLException {
           String sql = generatedSqlQuery.toUpperCase();
        assertTrue(sql.contains("WITH "), "Refactoring failed: You must use a Common Table Expression (WITH clause).");

        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {

            int count = 0;
            while(rs.next()) {
                count++;
                String name = rs.getString("patient_name");
                String category = rs.getString("bmi_category");

                if (name.equals("Alice")) assertEquals("Underweight", category);
                else if (name.equals("Bob")) assertEquals("Healthy", category);
                else if (name.equals("Charlie")) assertEquals("Overweight", category);
                else if (name.equals("Diana")) assertEquals("Obese", category);
            }
            assertEquals(4, count, "Should return all 4 patients");
        }
    }

the solution MUST use a CTE to calculate BMI just once, then reference that in the main query to assign a category. The unit test includes structural checks (as well as functional checks) to ensure refactoring and specific use of CTE as the prompt requires. The unit test includes structural checks (as well as functional checks) to ensure refactoring.


These are two queries that have similar calculations, one returns the gpa of all students, the other returns the gpa of cum laude students. Make a view called student_gpa_view to refactor this code to reduce redundancy.

Dit zijn twee query's met vergelijkbare berekeningen: de ene retourneert het gemiddelde cijfer van alle studenten, de andere retourneert het gemiddelde cijfer van cum laude-studenten. Maak een weergave met de naam student_gpa_view om deze code te herstructureren en redundantie te verminderen.

SELECT
    s.student_name,
    SUM(g.score * c.credits) * 1.0 / SUM(c.credits) AS gpa
FROM students s
JOIN grades g ON s.id = g.student_id
JOIN courses c ON g.course_id = c.id
GROUP BY s.student_name;

SELECT
    s.student_name,
    SUM(g.score * c.credits) * 1.0 / SUM(c.credits) AS gpa
FROM students s
JOIN grades g ON s.id = g.student_id
JOIN courses c ON g.course_id = c.id
GROUP BY s.student_name
HAVING SUM(g.score * c.credits) * 1.0 / SUM(c.credits) > 8.0;

CREATE VIEW student_gpa_view AS
SELECT
    s.id AS student_id,
    s.student_name,
    COUNT(g.course_id) AS total_classes,
    CAST(SUM(g.score * c.credits) * 1.0 / SUM(c.credits) AS DECIMAL(10,2)) AS gpa
FROM students s
JOIN grades g ON s.id = g.student_id
JOIN courses c ON g.course_id = c.id
GROUP BY s.id, s.student_name;

CREATE TABLE students (id INT PRIMARY KEY, student_name VARCHAR(50));
CREATE TABLE courses (id INT PRIMARY KEY, credits INT);
CREATE TABLE grades (student_id INT, course_id INT, score INT);

INSERT INTO students VALUES (1, 'Felipe');
INSERT INTO courses VALUES (101, 5), (102, 5);
INSERT INTO grades VALUES (1, 101, 9), (1, 102, 8);

INSERT INTO students VALUES (2, 'Bob');
INSERT INTO grades VALUES (2, 101, 6), (2, 102, 7);

    @Test
    public void testViewCreation(Connection conn) throws SQLException {
       try (Statement stmt = conn.createStatement()) {
            stmt.execute(generatedSqlQuery);
        }

        String verifySql = "SELECT student_name, gpa FROM student_gpa_view ORDER BY student_name DESC";

        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(verifySql)) {

         assertTrue(rs.next(), "The view should return rows.");
            assertEquals("Felipe", rs.getString("student_name"));
            assertEquals(8.5, rs.getDouble("gpa"), 0.01, "Felipe's GPA should be 8.5");

      assertTrue(rs.next());
            assertEquals("Bob", rs.getString("student_name"));
            assertEquals(6.5, rs.getDouble("gpa"), 0.01, "Bob's GPA should be 6.5");
        }
    }

the solution MUST create a view called student_gpa_view that encapsulates the GPA calculation logic, so that both original queries can be simplified to select from this view with appropriate filtering (by student_id for the first, and by gpa for the second). This reduces redundancy and improves maintainability. The unit test includes structural checks (as well as functional checks) to ensure refactoring.


This query retrieves the name, last order date and last product ordered for all customers, but it has repeated subqueries. Refactor the query using a lateral join to make it more efficient and readable without changing functionality.

Deze query haalt de naam, laatste besteldatum en laatst bestelde producten voor alle klanten op, maar bevat herhaalde subquery's. Herstructureer de query met behulp van een lateral join om deze efficiënter en leesbaarder te maken zonder de functionaliteit te wijzigen.

SELECT
    c.name,
    (SELECT order_date FROM orders o WHERE o.customer_id = c.id ORDER BY order_date DESC LIMIT 1) as order_date,
    (SELECT product_name FROM orders o WHERE o.customer_id = c.id ORDER BY order_date DESC LIMIT 1) as product_name,
    (SELECT amount FROM orders o WHERE o.customer_id = c.id ORDER BY order_date DESC LIMIT 1) as amount
FROM customers c;

SELECT
    c.name,
    last_o.order_date,
    last_o.product_name,
    last_o.amount
FROM customers c
LEFT JOIN LATERAL (
    SELECT order_date, product_name, amount
    FROM orders o
    WHERE o.customer_id = c.id
    ORDER BY order_date DESC
    LIMIT 1
) last_o ON TRUE;

CREATE TABLE customers (
    id INT PRIMARY KEY,
    name VARCHAR(50)
);

CREATE TABLE orders (
    id INT,
    customer_id INT,
    product_name VARCHAR(50),
    amount INT,
    order_date DATE
);

INSERT INTO customers VALUES (1, 'Alice');
INSERT INTO orders VALUES (101, 1, 'Phone', 500, '2023-01-01');
INSERT INTO orders VALUES (102, 1, 'Laptop', 1000, '2023-01-02');
INSERT INTO orders VALUES (103, 1, 'Tablet', 300, '2023-01-03');
INSERT INTO customers VALUES (2, 'Bob');

    @Test
    public void testLateralJoin(Connection conn) throws SQLException {
       String sql = generatedSqlQuery.toUpperCase();
        assertTrue(sql.contains("LATERAL"), "Refactoring failed: The model ignored the instruction to use LATERAL JOIN.");

       try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(generatedSqlQuery)) {

          assertTrue(rs.next());
            assertEquals("Alice", rs.getString("name"));
            assertEquals("Tablet", rs.getString("product_name"));

       assertTrue(rs.next());
            assertEquals("Bob", rs.getString("name"));
            assertNull(rs.getString("product_name"), "Bob was filtered out or data is wrong. Did you use LEFT JOIN LATERAL?");
        }
    }

the solution MUST use a LATERAL JOIN to fetch the last order details in a single subquery per customer. The unit test includes structural checks (as well as functional checks) to ensure refactoring.