{"instance_id": 0, "selected_database": "financial", "query": "In the financial database, we have a table named 'order' that records details about orders given to clients. Each order is associated with an order_id and has attributes such as account_id, bank_to, account_to, and amount. We need to find all accounts that have placed at least two orders such that the difference between the highest and lowest amount for those orders exceeds 12000. This query aims to find such accounts, but the initial attempt produced incorrect results.", "error_sql": ["SELECT account_id, MAX(payments) AS max_payment, MIN(payments) AS min_payment FROM loan GROUP BY account_id HAVING COUNT(account_id) > 1 AND (MAX(payments) - MIN(payments)) > 2;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 1, "selected_database": "codebase_community", "query": "I have a table named 'comments' in the 'codebase_community' database with a column 'CreationDate' of type 'datetime'. I want to extract only the 'hh:mm:ss' part from this column. My desired result should look like this:\n\n\n0:00:00\n10:00:00\n04:00:00\n\n\nHowever, when I tried to use the following SQL query, it didn't give me the expected result:\n\nsql\nSELECT CreationDate::time FROM comments;\n\n\nThis query returns the time part but includes leading zeros, which I don't want. How can I modify my query to achieve the desired result?", "error_sql": ["SELECT CreationDate::time FROM comments;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 2, "selected_database": "financial", "query": "I'm exploring triggers and want to create one that fires after an Update event on a `status` column in the `loan` table. The column contains text values representing loan statuses, so the user may update the loan status. I want the trigger function to calculate the number of loans with a specific status 'A' for a certain account. Then update `total_loan_count` in a `loan_summary` table. Here is my trigger (which is not working and I want to figure out why):", "error_sql": ["CREATE OR REPLACE FUNCTION total_loans()\n RETURNS TRIGGER \n AS $$ \n BEGIN \n UPDATE loan_summary \n SET total_loan_count = (SELECT COUNT(CASE WHEN status = 'A' THEN 1 END) FROM loan WHERE loan_summary.account_id = loan.account_id) WHERE account_id = NEW.account_id; RETURN NEW; \n END; \n $$ LANGUAGE plpgsql;", "\n CREATE TRIGGER tr_total_loans AFTER UPDATE OF status FOR EACH ROW EXECUTE PROCEDURE total_loans();\n "], "sol_sql": [], "preprocess_sql": ["DROP TABLE IF EXISTS loan_summary;", "CREATE TABLE loan_summary (account_id INT PRIMARY KEY, total_loan_count INT);", "INSERT INTO loan_summary (account_id, total_loan_count) SELECT l.account_id, COUNT(*) FROM loan l WHERE l.status = 'A' GROUP BY l.account_id;"], "clean_up_sql": [], "test_cases": []} {"instance_id": 3, "selected_database": "european_football_2", "query": "In the context of managing team attributes in the European Football database, a user attempted to add a new value 'Very Fast' to an existing ENUM type for 'buildupplayspeedclass' in the 'team_attributes' table. The user tried an approach: renaming the existing ENUM and creating a new one with the additional value, and switch the data type in place. The approach resulted in locks that caused application downtime, especially considering the table's size in the millions of rows. The user is seeking a solution that avoids such downtime, possibly by considering a different approach than using ENUMs.", "error_sql": ["ALTER TYPE buildupplayspeedclass RENAME TO buildupplayspeedclass_old;", "CREATE TYPE buildupplayspeedclass AS ENUM ('Slow', 'Balanced', 'Fast', 'Very Fast');", "ALTER TABLE Team_Attributes ALTER COLUMN buildupplayspeedclass SET DATA TYPE buildupplayspeedclass USING buildupplayspeedclass::text::buildupplayspeedclass;", "DROP TYPE buildupplayspeedclass;"], "sol_sql": [], "preprocess_sql": ["CREATE TYPE buildupplayspeedclass_enum AS ENUM ('Balanced', 'Fast', 'Slow');", "\n ALTER TABLE team_attributes\n ALTER COLUMN buildupplayspeedclass\n TYPE buildupplayspeedclass_enum\n USING buildupplayspeedclass::buildupplayspeedclass_enum;"], "clean_up_sql": [], "test_cases": []} {"instance_id": 4, "selected_database": "student_club", "query": "In the student_club database, I created a unique index on the `event` table using the following queries 'CREATE UNIQUE INDEX unique_name ON event(event_name, event_date) where event_name is not null; CREATE UNIQUE INDEX unique_location ON event(location, event_date) where location is not null;'. However, when I attempt to insert a new record using an UPSERT operation using the query 'insert into event (event_id, event_name, location, event_date) values('test1', 'test_name', 'test_location', 'test_date')on conflict (event_name, location, event_date) do update set event_id = 'test1', event_name = 'test_name', location = 'test_location', event_date = 'test_date'', I encounter an error stating that there is no unique or exclusion constraint matching the ON CONFLICT specification.", "error_sql": ["CREATE UNIQUE INDEX unique_name ON event(event_name, event_date) where event_name is not null;CREATE UNIQUE INDEX unique_location ON event(location, event_date) where location is not null;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 5, "selected_database": "debit_card_specializing", "query": "In the following SQL, how could I make the `RETURNING` clause join to something else and return the joined row(s)? Here it only returns the row from `transactions_1k` that was updated, but I'd like it to return that row joined to something in another table, e.g. joined to `customers` tables and get both `transactions_1k.transactionid` and `customers.Segment` columns.", "error_sql": ["\n UPDATE transactions_1k \n SET Amount = 100 \n FROM ( SELECT TransactionID FROM transactions_1k WHERE Amount = 50 ORDER BY Date LIMIT 100 FOR UPDATE ) sub \n WHERE transactions_1k.TransactionID = sub.TransactionID RETURNING *;\n "], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 6, "selected_database": "codebase_community", "query": "I have a query that calculates the number of referrals each user has made. However, I want to count a referral only if the referred user has activated their premium account. How can I achieve this?", "error_sql": ["SELECT users.Id, COUNT(posts.Id) as answered FROM users LEFT JOIN posts ON users.Id = posts.OwnerUserId GROUP BY users.Id ORDER BY answered DESC;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 7, "selected_database": "codebase_community", "query": "I want to drop the 'users' table from the 'codebase_community' database. However, when I attempt to drop the table using the SQL command `DROP TABLE IF EXISTS users;`, I encounter an error message stating: 'cannot drop table users because other objects depend on it'. This issue arises because the 'users' table is referenced by foreign keys in other tables such as 'badges', 'comments', 'postHistory', 'posts', and 'votes'. I am seeking a solution to drop the 'users' table without having to remove all dependent tables or data.", "error_sql": ["DROP TABLE IF EXISTS users;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 8, "selected_database": "student_club", "query": "In database student_club, there is a set of users. A student can have multiple users, but ref1 and ref2 might be alike and can therefore link users together. ref1 and ref2 does not overlap, one value in ref1 does not exist in ref2. A user can own multiple assets. I want to \"merge\" users that has one or more refs alike and then count how many assets they own together. There could be missing entries in the user table, in that case I just want to propagate the owner into ref2 and set the asset_count and asset_ids.", "error_sql": ["SELECT ARRAY_AGG(DISTINCT u.id) AS ids, ARRAY_AGG(DISTINCT u.username) AS usernames, ARRAY_AGG(DISTINCT u.ref1) AS refs1, ARRAY_AGG(DISTINCT u.ref2) AS refs2, COUNT(DISTINCT a.id) AS asset_count FROM assets a JOIN users u ON a.owner = u.ref1 OR a.owner = u.ref2 GROUP BY a.owner ORDER BY MIN(a.id);"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE assets (id serial, name text, owner text, PRIMARY KEY(id));", "CREATE TABLE users (id serial, username text, ref1 text, ref2 text, PRIMARY KEY(id));", "INSERT INTO assets (name, owner) VALUES ('#1', 'a'), ('#2', 'b'), ('#3', 'c'), ('#4', 'a'), ('#5', 'c'), ('#6', 'd'), ('#7', 'e'), ('#8', 'd'), ('#9', 'a'), ('#10', 'a'), ('#11', 'z');", "INSERT INTO users (username, ref1, ref2) VALUES ('bobo', 'a', 'd'), ('toto', 'b', 'e'), ('momo', 'c', 'd'), ('lolo', 'a', 'f'), ('popo', 'c', 'f');"], "clean_up_sql": ["drop table if exists users;", "drop table if exists assets;"], "test_cases": []} {"instance_id": 9, "selected_database": "student_club", "query": "I am trying to compare the number of attendees for each event between two different tables: 'attendance' and 'budget'. I want to find events where the number of attendees in the 'attendance' table does not match the number of attendees recorded in the 'budget' table. My query follows this structure:", "error_sql": ["WITH CTE AS ( SELECT link_to_event, COUNT(link_to_member) AS count FROM attendance GROUP BY link_to_event ) SELECT CTE.link_to_event, CTE.count AS newCount, budget.count AS oldCount FROM budget JOIN CTE ON budget.link_to_event = CTE.link_to_event WHERE budget.count != CTE.count;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 10, "selected_database": "student_club", "query": "In the student_club database, we have a scenario where a member can attend multiple events, and an event can have multiple attendees. However, a member can only attend an event once. If a member attempts to attend the same event again, the system should update the attendance record with new information, such as status attend. The current approach is to use an INSERT statement, but it fails when the member already has an attendance record for the event. We need to implement an insert statement that updates the existing record if a conflict occurs based on the combination of member_id and event_id.", "error_sql": ["INSERT INTO attendance VALUES ('recEVTik3MlqbvLFi', 'rec280Sk7o31iG0Tx', 1)"], "sol_sql": [], "preprocess_sql": ["ALTER TABLE attendance ADD COLUMN attend INTEGER DEFAULT 0;"], "clean_up_sql": ["ALTER TABLE attendance DROP COLUMN attend;"], "test_cases": []} {"instance_id": 11, "selected_database": "financial", "query": "In the financial database, there is a need to convert the data from a `BIGINT` column to a `TIMESTAMP` column. The `date` column in the `account` table is currently stored as a `BIGINT` representing the date in the format YYMMDD. The goal is to update this column to a `TIMESTAMP` type to store the date and time information.", "error_sql": ["\n UPDATE account\n SET date__timestamp = date__bigint::timestamp;\n "], "sol_sql": [], "preprocess_sql": ["\n ALTER TABLE account\n ALTER COLUMN date\n TYPE BIGINT\n USING to_char(date, 'YYYYMMDD')::bigint;\n "], "clean_up_sql": [], "test_cases": []} {"instance_id": 12, "selected_database": "card_games", "query": "In the card_games database, there is a table named 'cards'. Each card is uniquely identified by a id and includes details about artists and bordercolors. The user wants to group the cards by their 'artist' attribute to get a distinct result for each group. However, when the user tries to use the following SQL query to achieve this, it results in an error or incorrect output: sql SELECT * FROM cards GROUP BY artist; The user understands that this query is incorrect because it does not group by all the columns that need to be shown. The user is seeking a solution to this problem.", "error_sql": ["\n SELECT * FROM cards GROUP BY artist;\n "], "sol_sql": [], "preprocess_sql": ["\n DELETE FROM cards\n WHERE artist NOT IN ('Ralph Horsley', 'Daarken');\n ", "\n DELETE FROM cards\n WHERE artist IS NULL;\n ", "\n CREATE TABLE cards_new AS\n SELECT id, artist, bordercolor\n FROM cards;\n DROP TABLE cards;\n ALTER TABLE cards_new\n RENAME TO cards;\n "], "clean_up_sql": [], "test_cases": []} {"instance_id": 13, "selected_database": "debit_card_specializing", "query": "I'm trying to create an SQL query that checks if a SELECT query on the 'transactions_1k' table returns no rows based on a specific criteria involving 'CustomerID' and 'Date'. If no rows are returned, it should then execute another SELECT query with a different criteria. Here's what I mean:\n\nsql\nIF SELECT * FROM transactions_1k WHERE CustomerID = 3 AND Date = '2012-08-24' RETURNS NO ROWS\nTHEN SELECT * FROM transactions_1k WHERE CustomerID = 7626 AND Date = '2012-08-24'\n\n\nIs this possible? I'm not sure if an empty result set counts as 'null', which is causing me some trouble.", "error_sql": ["IF SELECT * FROM transactions_1k WHERE CustomerID = 3 AND Date = '2012-08-24' RETURNS NO ROWS\nTHEN SELECT * FROM transactions_1k WHERE CustomerID = 7626 AND Date = '2012-08-24'"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 14, "selected_database": "financial", "query": "I need to compare the 'account' table with another table, but there are some columns in the 'account' table that I don't need to compare. Specifically, I want to exclude the 'account_id' and 'date' columns from the comparison. I tried to dynamically generate a SQL query to select all columns except these two, but the output SQL was incorrect. Here's the problematic SQL I used:", "error_sql": ["SELECT 'SELECT ' || array_to_string(ARRAY(SELECT 'o' || '.' || c.column_name\n FROM information_schema.columns As c\n WHERE table_name = 'account' \n AND c.column_name NOT IN('account_id', 'date')\n), ',') || ' FROM accountAs o' As sqlstmt"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 15, "selected_database": "financial", "query": "I have two tables: `account` and `loan`. I need to display the first 6 accounts from a specific district that has loans in the last 48 hours then the rest of the accounts. This works great but I get duplicates from the second query where I repeat these accounts again. I want to make sure `account.account_id` is unique.", "error_sql": ["(\n SELECT\n account.account_id,\n account.frequency,\n l.loan_id,\n l.date AS loan_date,\n 0 AS priority\n FROM account\n LEFT JOIN loan l\n ON account.account_id = l.account_id\n WHERE account.district_id = '18'\n AND l.date >= (NOW() - INTERVAL '48 hours')\n ORDER BY l.date DESC NULLS LAST\n LIMIT 6\n)\nUNION\n(\n SELECT\n account.account_id,\n account.frequency,\n l.loan_id,\n l.date AS loan_date,\n 1 AS priority\n FROM account\n LEFT JOIN loan l\n ON account.account_id = l.account_id\n WHERE account.district_id = '18'\n ORDER BY account.date DESC\n);"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 16, "selected_database": "student_club", "query": "In the student_club database, there is a table named 'attendance' that records the attendance of members to various events. Each record in this table contains a 'link_to_event' which is a unique identifier for the event, and a 'link_to_member' which is a unique identifier for the member. The goal is to generate a output that aggregates the attendance records by event, where each event's attendance is represented as an array of member objects. Each member object should contain the member's unique identifier ('link_to_member') and the event's unique identifier ('link_to_event'). The desired output should be an array of these event-based arrays. However, the user encountered an issue where the output was interpreted as text, introducing undesired escape characters, and the outer array was missing. The user's query was adapted from a suggestion on another post, but it did not produce the desired result.", "error_sql": ["SELECT Array_agg(rw) FROM (SELECT link_to_event, (SELECT To_(Array_agg(Row_to_(t))) FROM (SELECT link_to_member FROM public.attendance WHERE link_to_event = b.link_to_event) t) rw FROM attendance b GROUP BY link_to_event);"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 17, "selected_database": "financial", "query": "In the financial database, we need to generate a list of all years between two given dates from the 'loan' table. The dates are extracted from the 'date' column, which represents the approval date of loans. The goal is to generate all years between the earliest and latest loan approval dates, regardless of the interval between them. For instance, if the earliest loan was approved on '1994-01-05' and the latest on '1997-12-08', we should get a list of years including '1994', '1995', '1996', and '1997'. However, the initial query only returns the starting year if the interval between the dates is less than a year, which is not the desired outcome.", "error_sql": ["SELECT to_char(generate_series, 'YYYY') FROM generate_series(MIN(date)::timestamptz, MAX(date)::timestamptz, '1 year') FROM loan;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 18, "selected_database": "financial", "query": "In the financial database, there is a table named 'loan' that records details of loans given to clients. Each loan is associated with an account, and the table contains columns such as 'loan_id', 'account_id', 'date', 'amount', 'duration', 'payments', and 'status'. The 'amount' column represents the loan amount in USD. The task is to retrieve all rows from the 'loan' table, along with an additional column that shows the maximum loan amount per account. This will help in understanding the highest loan amount each account has taken. However, the user attempted to use the ROW_NUMBER() window function to achieve this, which resulted in incorrect results.", "error_sql": ["SELECT account_id, amount FROM (SELECT account_id, amount, ROW_NUMBER() OVER(PARTITION BY account_id ORDER BY amount DESC) AS rn FROM loan) AS a WHERE rn = 1;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 19, "selected_database": "financial", "query": "In the financial database, we need to create a table to store detailed information about clients, including their first name, last name, and a full name that is automatically generated from the first and last names. The full name should be stored as a generated column. However, when attempting to create the table with a generated column using the CONCAT function, an error occurs indicating that the generation expression is not immutable.", "error_sql": ["CREATE TABLE client_information ( client_id smallserial NOT NULL, first_name character varying(50), last_name character varying(50), full_name character varying(100) GENERATED ALWAYS AS (concat(first_name, ' ', last_name)) STORED, PRIMARY KEY (client_id) );"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": ["DROP TABLE IF EXISTS client_information;"], "test_cases": []} {"instance_id": 20, "selected_database": "card_games", "query": "In the context of the card_games database, I frequently need to get a card's row based on its unique UUID, and if it does not exist, I want to create it and return its ID. For example, my table might be the 'cards' table. Suppose I want to insert a card with a specific UUID and name, and if the UUID already exists, I want to return the existing card's ID without modifying the row. However, using the following SQL statement, I encounter issues as it does not return the ID when the row already exists:\\nsql \\\\nINSERT INTO cards(uuid, name) VALUES ('5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 'Ancestor''s Chosen') \\\\nON CONFLICT DO NOTHING RETURNING id; \\\\n\\nThis statement does not return the ID of the existing row. I need a solution that returns the ID whether the row is inserted or already exists.", "error_sql": ["INSERT INTO cards(uuid, name) VALUES ('5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 'Ancestor''s Chosen') ON CONFLICT DO NOTHING RETURNING id;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 21, "selected_database": "financial", "query": "In the financial database, I have a table `account` where I need to insert new records or update existing ones based on the `account_id`. The `date` column should be updated to the current date if the record already exists. I want to know whether an `INSERT` or an `UPDATE` operation was performed. I attempted to use an `ON CONFLICT..DO UPDATE` clause but encountered issues with determining the type of operation. I considered adding an `is_update` column to track this, but it feels unnecessary as it is not related to the data itself.", "error_sql": ["INSERT INTO account (account_id, district_id, frequency, date) VALUES (1, 18, 'POPLATEK MESICNE', CURRENT_DATE) ON CONFLICT (account_id) DO UPDATE SET date = CURRENT_DATE"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": ["UPDATE account SET date = '1995-03-24'", "DELETE FROM account WHERE account_id = 22222"], "test_cases": []} {"instance_id": 22, "selected_database": "card_games", "query": "I am analyzing the release dates of Magic: The Gathering card sets to identify periods of consecutive releases. The data includes multiple entries for the same release date due to different printings or variations. I want to find the longest consecutive release periods along with their start and end dates. Here is the structure of the relevant table:\\n- id SERIAL, releaseDate DATE, setCode VARCHAR(50)\\nThe data could have equal release date entries:\\n- id 1, releaseDate 2019-12-28, setCode '10E'\\n- id 2, releaseDate 2019-12-28, setCode '10E'\\n- id 3, releaseDate 2019-12-29, setCode '10E'\\n- id 4, releaseDate 2019-12-29, setCode '10E'\\n- id 5, releaseDate 2019-12-31, setCode '10E'\\n- id 6, releaseDate 2019-12-31, setCode '10E'\\n- id 7, releaseDate 2020-01-01, setCode '10E'\\n- id 8, releaseDate 2020-01-01, setCode '10E'\\n- id 9, releaseDate 2020-01-02, setCode '10E'\\n- id 10, releaseDate 2020-01-03, setCode '10E'\\n- id 11, releaseDate 2020-01-04, setCode '10E'\\n- id 12, releaseDate 2020-01-04, setCode '10E'\\n- id 13, releaseDate 2020-01-05, setCode '10E'\\n- id 14, releaseDate 2020-01-22, setCode '10E'\\n- id 15, releaseDate 2020-01-29, setCode '10E'\\n- id 16, releaseDate 2020-01-30, setCode '10E'\\nI am interested in getting the consecutive release periods with the start and end dates. An output like this:\\n- count | date MIN | date MAX \\\\(6, 2019-12-31, 2020-01-05)\\\\(2, 2019-12-28, 2019-12-29)\\\\(2, 2020-01-29, 2020-01-30)\\nI tried the following SQL query, but it gives incorrect counts and mismatched start/end dates:\\", "error_sql": ["SELECT COUNT(*) -1 AS count, MAX(releaseDate), MIN(releaseDate) FROM (SELECT *, date(releaseDate) - row_number() OVER (PARTITION BY releaseDate ORDER BY date(releaseDate)) * INTERVAL '1 day' AS filter FROM sets_releaseInfo ) t1 GROUP BY filter HAVING COUNT(*) -1 > 0 ORDER BY count DESC"], "sol_sql": [], "preprocess_sql": ["CREATE TEMP TABLE sets_releaseInfo (id SERIAL, releaseDate DATE, setCode VARCHAR(50));", "INSERT INTO sets_releaseInfo (releaseDate, setCode) VALUES ('2019-12-28', '10E'), ('2019-12-28', '10E'), ('2019-12-29', '10E'), ('2019-12-29', '10E'), ('2019-12-31', '10E'), ('2019-12-31', '10E'), ('2020-01-01', '10E'), ('2020-01-01', '10E'), ('2020-01-02', '10E'), ('2020-01-03', '10E'), ('2020-01-04', '10E'), ('2020-01-04', '10E'), ('2020-01-05', '10E'), ('2020-01-22', '10E'), ('2020-01-29', '10E'), ('2020-01-30', '10E');"], "clean_up_sql": ["DROP TABLE IF EXISTS sets_releaseInfo;"], "test_cases": []} {"instance_id": 23, "selected_database": "card_games", "query": "In the card_games database, we have a table named 'collection' where each card can have a reference to another card through the 'nextCardId' column. This column represents the ID of the next card in a sequence. We want to generate a sequence path for each card starting from the card that has no previous card (i.e., no card points to it) and ending at the card that has no next card (i.e., its 'nextCardId' is NULL). The path should be represented as a string of card IDs separated by ' --> '.\\nFor example, if we have the following data:\\n| id | nextCardId |\\n|-----|------------|\\n| 1 | 5 |\\n| 2 | NULL |\\n| 3 | 6 |\\n| 4 | 7 |\\n| 5 | 8 |\\n| 6 | 9 |\\n| 7 | NULL |\\n| 8 | NULL |\\n| 9 | 10 |\\n| 10 | NULL |\\nWe want to get the following paths:\\n1 --> 5 --> 8;\\n2;\\n3 --> 6 --> 9 --> 10;\\n4 --> 7;\\nHowever, when we run the following SQL query, we get incorrect results that include incomplete paths:\\nsql;\\nWITH RECURSIVE path_cte AS (\\n SELECT id, nextCardId, id::TEXT AS Path;\\n FROM collection\\n WHERE nextCardId IS NULL\\n UNION ALL\\n SELECT collection.id, collection.nextCardId, collection.id || ' --> ' || cte.Path\\n FROM collection\\n JOIN path_cte cte ON collection.nextCardId = cte.id\\n)\\nSELECT Path\\nFROM path_cte\\nORDER BY id;\\n\\nWe need to correct this query to get only the complete paths starting from the cards that have no previous card and ending at the cards that have no next card.", "error_sql": ["WITH RECURSIVE path_cte AS (SELECT id, nextCardId, id::TEXT AS Path FROM collection WHERE nextCardId IS NULL UNION ALL SELECT collection.id, collection.nextCardId, collection.id || ' --> ' || cte.Path FROM collection JOIN path_cte cte ON collection.nextCardId = cte.id) SELECT Path FROM path_cte ORDER BY id;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE collection (id INTEGER NOT NULL PRIMARY KEY, nextCardId INTEGER)", "INSERT INTO collection (id, nextCardId) VALUES (1, 5), (2, NULL), (3, 6), (4, 7), (5, 8), (6, 9), (7, NULL), (8, NULL), (9, 10), (10, NULL);"], "clean_up_sql": ["DROP TABLE IF EXISTS collection"], "test_cases": []} {"instance_id": 24, "selected_database": "financial", "query": "In the financial database, I need to classify transactions by quarter, but I want the quarters to start at a configurable month. If I set the quarter to start in April, then April, May, and June should be the first quarter. I think I need a function what_quarter_is(date_in, start_month). For example, what_quarter_is('1995-07-23', 4) = 2. The default EXTRACT(QUARTER FROM date) function in PostgreSQL starts quarters in January, which does not meet my requirements.", "error_sql": ["SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": ["DROP FUNCTION what_quarter_is(date, integer);"], "test_cases": []} {"instance_id": 25, "selected_database": "codebase_community", "query": "In the codebase_community database, I have a table named 'users' with a primary key of 'id'. I need to find all tables, columns, and constraints that reference the 'users' table regardless of which column in 'users' is referenced. For example, if there is a table named 'posts' with a foreign key constraint as follows:\\nCREATE TABLE posts (\\n id bigint NOT NULL,\\n owneruserid bigint NULL,\\n lasteditoruserid bigint NULL,\\n PRIMARY KEY (id),\\n FOREIGN KEY (owneruserid) REFERENCES users(id),\\n FOREIGN KEY (lasteditoruserid) REFERENCES users(id)\\n);\\nI should get back rows like the following:\\nbase_table base_col referencing_table referencing_col constraint_sql\\nusers id posts owneruserid CONSTRAINT posts_owneruserid_fkey FOREIGN KEY (owneruserid) REFERENCES users(id)\\nusers id posts lasteditoruserid CONSTRAINT posts_lasteditoruserid_fkey FOREIGN KEY (lasteditoruserid) REFERENCES users(id)\\nNon-primary key references should also be listed and it should handle compound keys.", "error_sql": ["SELECT (select r.relname from pg_class r where r.oid = c.confrelid) as base_table,\\n a.attname as base_col,\\n (select r.relname from pg_class r where r.oid = c.conrelid) as referencing_table,\\n UNNEST((select array_agg(attname) from pg_attribute where attrelid = c.conrelid and array[attnum] <@ c.conkey)) as referencing_col,\\n pg_get_constraintdef(c.oid) contraint_sql FROM pg_constraint c join pg_attribute a on c.confrelid=a.attrelid and a.attnum = ANY(confkey)\\n WHERE c.confrelid = (select oid from pg_class where relname = 'users')\\n AND c.confrelid!=c.conrelid;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 26, "selected_database": "financial", "query": "We have a table 'trans' that records all transactions made by clients in various accounts. Each transaction has a 'trans_id', 'account_id', 'date', 'type', 'operation', 'amount', 'balance', 'k_symbol', 'bank', and 'account'. We need to add a new column 'next_bank' to the 'trans' table that indicates the next non-null 'bank' value for each transaction, ordered by 'date' within each 'account_id'. For example, if a transaction has a null 'bank', the 'next_bank' should be the 'bank' of the next transaction in the same account that has a non-null 'bank'. The user attempted to use the following SQL query, which fails in PostgreSQL due to the lack of support for the 'ignore nulls' clause in the window function. The query is as follows:", "error_sql": ["SELECT first_value(bank ignore nulls) over (partition by account_id order by date rows unbounded following) as next_bank FROM trans;"], "sol_sql": [], "preprocess_sql": ["ALTER TABLE trans ADD COLUMN next_amount int;"], "clean_up_sql": ["ALTER TABLE trans DROP COLUMN next_amount;"], "test_cases": []} {"instance_id": 27, "selected_database": "european_football_2", "query": "I have two separate queries that I want to combine. The first query retrieves the team_api_id and short names of teams from the Team table. The second query retrieves the buildUpPlaySpeed from the Team_Attributes table, based on the team_api_id. I want to combine these two queries into a single query that outputs theteam_api_id, team long name, and the corresponding buildUpPlaySpeed. I have tried the following sql: \\nsql \\\\\\\\nSELECT team_api_id, team_short_name FROM Team as data FULL OUTER JOIN ( SELECT buildUpPlaySpeed, team_api_id FROM Team_Attributes ta WHERE team_api_id = data.team_api_id ) AS subquery_alias ON data.team_api_id = subquery_alias.team_api_id; \\\\\\\\n\\n However, when I ran this query, I encountered an error: There is an entry for table 'data' but it cannot be referenced from this part of the query. How can I modify my query so that it properly combines the results of the two queries?", "error_sql": ["SELECT team_api_id, team_short_name FROM Team as data FULL OUTER JOIN (SELECT buildUpPlaySpeed, team_api_id FROM Team_Attributes ta WHERE team_api_id = data.team_api_id) AS subquery_alias ON data.team_api_id = subquery_alias.team_api_id;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 28, "selected_database": "financial", "query": "We have two tables in our financial database: `trans` and `loan`. The `trans` table records all transactions made by clients, while the `loan` table records all loans issued to clients. Each transaction and loan has a timestamp indicating when it occurred. We want to combine these two tables into a single dataset, without worrying about clashing IDs, and then count the number of actions (transactions and loans) per year. The goal is to produce a result set that shows the total number of actions in each year (order by year). I attempted to write a query but encountered an error related to the GROUP BY clause.", "error_sql": ["WITH one AS ( SELECT date_trunc('year', date) as timeOne, COUNT(*) as trans_count FROM trans ORDER BY timeOne ), two AS ( SELECT date_trunc('year', date) as timeTwo, COUNT(*) as loan_count FROM loan ORDER BY timeTwo ) SELECT timeOne as year, SUM(trans_count, loan_count) as count FROM one, two ORDER BY 1;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 29, "selected_database": "debit_card_specializing", "query": "In the context of the debit_card_specializing database, we need to draw the first place to fifth place winners from a pool of customers based on their transaction amounts. A customer can't win multiple places. If a customer hasn't placed, then all of their transaction amounts must be considered in the draw. The goal is to draw all five place winners efficiently without repeating the query multiple times. The transactions_1k table contains the necessary data with columns such as CustomerID and Amount. The user initially attempted to draw one winner but couldn't extend the logic to draw all five winners without eliminating previous winners in each subsequent draw.", "error_sql": ["WITH gen_transactions AS (SELECT CustomerID, Amount FROM transactions_1k CROSS JOIN LATERAL generate_series(1, CAST(Amount AS INTEGER))), shuffle AS (SELECT CustomerID, Amount, row_number() OVER (ORDER BY random()) AS rn FROM gen_transactions) SELECT * FROM shuffle ORDER BY RANDOM() LIMIT 1;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 30, "selected_database": "card_games", "query": "The data in the table \"card_infomation\" includes one column named \"price\". I am using postgres and I have multiple entries of jsonb inside an array in a single column called price. They're input as the card names and corresponding prices. There are multiple rows, with multiple json elements inside of each one of them. I would like to combine them into one big entry in one row, so that I will just have one row of one column as a result.", "error_sql": ["\nINSERT INTO card_information(price) SELECT jsonb_agg(price) FROM (SELECT price FROM card_information) AS subquery; SELECT * FROM card_information;\n"], "sol_sql": [], "preprocess_sql": ["\nCREATE TABLE card_information (price JSONB); \nINSERT INTO card_information (price) VALUES \n('[{\"a\": 1}, {\"b\": 2}, {\"c\": 0.5}]'::jsonb), \n('[{\"d\": 2.2}, {\"e\": 2.4}, {\"f\": 3.5}]'::jsonb), \n('[{\"g\": 1.7}, {\"h\": 5.4}, {\"i\": 8.9}]'::jsonb);\nSELECT * FROM card_information;\n"], "clean_up_sql": ["DROP TABLE card_information;"], "test_cases": [], "external_data": "{\"a\": 1}, {\"b\": 2}, {\"c\": 0.5},{\"d\": 2.2}, {\"e\": 2.4}, {\"f\": 3.5},{\"g\": 1.7}, {\"h\": 5.4}, {\"i\": 8.9}"} {"instance_id": 31, "selected_database": "financial", "query": "In the financial database, I have two tables: `trans` and `account`. The `trans` table contains transaction details including the `account_id`, `date`, `type`, `operation`, `amount`, `balance`, `k_symbol`, `bank`, and `account`. The `account` table contains account details including `account_id`, `district_id`, `frequency`, and `date`. For each transaction in the `trans` table that matches a specific `account_id` and `type`, I want to join the corresponding record in the `account` table with the minimum transaction date. I want to group the results by `k_symbol` and extract the `k_symbol`, `operation`, `amount`, `balance`, and `frequency` from the selected transaction record.", "error_sql": ["SELECT t.k_symbol, t.operation, t.amount, t.balance, a.frequency FROM trans t INNER JOIN account a ON t.account_id = a.account_id WHERE t.account_id = 1 AND t.type = 'PRIJEM' GROUP BY t.k_symbol -- and t.date is the minimum for each group;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 32, "selected_database": "card_games", "query": "I am trying to analyze the purchasing behavior of users in our card_games database to find out the count of sequential monthly purchases and their lengths for each user. I want to identify the longest streaks of consecutive monthly purchases for each user and then count how many users have each longest streak length. For example, if a user made purchases in March, April, May, and June, that would be a streak of 4 months. If another user made purchases in January, February, and March, that would be a streak of 3 months. I need to find the longest streak for each user and then count how many users have the longest streak of a certain length. The expected result should show the streak length and the number of users who have that longest streak length.", "error_sql": ["\nSELECT user_id, COUNT(*) AS num_consecutive_months FROM (SELECT user_id, purchase_date, DATE_TRUNC('month', TO_DATE(purchase_date || '-01', 'YYYY-MM-DD')) AS month_date, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY DATE_TRUNC('month', TO_DATE(purchase_date || '-01', 'YYYY-MM-DD'))) - ROW_NUMBER() OVER(PARTITION BY user_id, DATE_TRUNC('month', TO_DATE(purchase_date || '-01', 'YYYY-MM-DD')) - INTERVAL '1 month' * ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY DATE_TRUNC('month', TO_DATE(purchase_date || '-01', 'YYYY-MM-DD')))) AS grp FROM purchase) sub GROUP BY user_id, grp ORDER BY COUNT(*) DESC LIMIT 1;\n"], "sol_sql": [], "preprocess_sql": ["\nCREATE TABLE purchase ( purchase_date VARCHAR(255), user_id VARCHAR(255) ); INSERT INTO purchase(purchase_date, user_id) VALUES('2020-03', 'alex01'), ('2020-04', 'alex01'), ('2020-05', 'alex01'), ('2020-06', 'alex01'), ('2020-12', 'alex01'), ('2021-01', 'alex01'), ('2021-02', 'alex01'), ('2021-03', 'alex01'), ('2020-04', 'jon03'), ('2020-05', 'jon03'), ('2020-06', 'jon03'), ('2020-09', 'jon03'), ('2021-11', 'jon03'), ('2021-12', 'jon03'), ('2022-01', 'jon03'), ('2022-02', 'jon03'), ('2020-05', 'mark05'), ('2020-06', 'mark05'), ('2020-07', 'mark05'), ('2020-08', 'mark05'), ('2020-09', 'mark05');\n"], "clean_up_sql": ["DROP TABLE purchase;"], "test_cases": []} {"instance_id": 33, "selected_database": "financial", "query": "I am working with a table (card_info) containing card IDs, company names, and types. My task is to extract the pure card id without company information, \"pure_cardid\", from the cardid field by removing the substring between the first and second hyphens. Afterward, I need to retrieve the minimum value of type for each unique \"pure_cardid\", considering that multiple records may exist for the same \\pure_cardid\". My main challenge is how to correctly perform both the string manipulation and the aggregation in a single query.", "error_sql": ["\nWITH tab_with_cardid AS (\n select split(cardid, '-', 3)ivm_arr,\n\n type,\n last_refresh_date\n FROM db.scema.table\n), ranked_visits AS (\n SELECT *, ROW_NUMBER() OVER(PARTITION BY CONCAT(ivm_arr[2],item) as temp ORDER BY type) AS rn\n FROM tab_with_cardid\n)\nSELECT cardid, pure_cardid\nFROM ranked_visits\nWHERE rn = 1\n"], "sol_sql": [], "preprocess_sql": ["\nCREATE TABLE card_info (\n cardid VARCHAR(50),\n company VARCHAR(10),\n type CHAR(1)\n);\n\nINSERT INTO card_info (cardid, company, type) VALUES\n('1234-5678-HIJK', '1234', 'A'),\n('1234-9012-HIJK', '1234', 'B'),\n('56457-12456-DF-GH-TC', '56457', 'D');\n"], "clean_up_sql": ["DROP TABLE card_info;"], "test_cases": []} {"instance_id": 34, "selected_database": "european_football_2", "query": "Suppose we have the following table in the 'european_football_2' database that records the overall rating of players over time:\\n|player_api_id|date|overall_rating|\\n|-------------|----|--------------|\\n|505942 |2016-02-18|67 |\\n|505942 |2015-11-19|67 |\\n|505942 |2015-09-21|62 |\\n|155782 |2016-03-15|75 |\\n|155782 |2015-12-10|74 |\\n|162549 |2016-01-20|70 |\\n|162549 |2015-10-25|68 |\\nFor each player, we want the latest overall rating based on the date. The final table would be:\\n|player_api_id|date|overall_rating|\\n|-------------|----|--------------|\\n|505942 |2016-02-18|67 |\\n|155782 |2016-03-15|75 |\\n|162549 |2016-01-20|70 |\\nI attempted to group by player_api_id while ordering by date and then getting the first value:\\nsql \\\\nSELECT player_api_id, MAX(date), FIRST(overall_rating) \\\\nFROM Player_Attributes \\\\nGROUP BY player_api_id \\\\nORDER BY date desc \\\\n\\nBut this doesn't work.", "error_sql": ["SELECT player_api_id, MAX(date), FIRST(overall_rating) FROM Player_Attributes GROUP BY player_api_id ORDER BY date desc;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 35, "selected_database": "codebase_community", "query": "I am using a tool that allows querying user data in our local database using the PostgreSQL interface. I am running a simple query to print all ages of the users on our platform. However, I am getting an error message that says 'ERROR: invalid input syntax for type numeric: \"text\"'. I am not sure why I am getting this error. Can you help me understand why this error is occurring and how I can fix it?", "error_sql": ["SELECT Age::numeric FROM users;"], "sol_sql": [], "preprocess_sql": ["ALTER TABLE users ALTER COLUMN Age SET DATA TYPE text; INSERT INTO users VALUES (1212121,3150,'2010-07-19 19:09:39','JMS','2014-09-13 04:03:25',NULL,NULL,NULL,257,138,7,134002,'Invalid Age',NULL);"], "clean_up_sql": ["DELETE FROM users WHERE id = 1212121; ALTER TABLE users ALTER COLUMN age SET DATA TYPE integer USING age::integer;"], "test_cases": []} {"instance_id": 36, "selected_database": "codebase_community", "query": "In our local database, we have two tables `users` and `profiles`. When a new user is added to the `users` table, we want to automatically create a corresponding profile in the `profiles` table. The `profiles` table has three columns: `id`, `CreationDate`, and `WebsiteUrl`. The `WebsiteUrl` should be derived from the user's WebsiteUrl by taking the part before the '.com' and after the 'http://'. For example, 'http://stackoverflow.com' should become 'stackoverflow'. To achieve this, I created a trigger on the `users` table with the following function: sql begin insert into profiles (Id, CreationDate, WebsiteUrl) select new.id, new.WebsiteUrl, left(replace(new.WebsiteUrl, '.', '-'), charindex('@', replace(new.WebsiteUrl, '.', '-')) - 1); return new; end; However, when a new user is added, I encounter the error: ERROR: function charindex(unknown, text) does not exist (SQLSTATE 42883)", "error_sql": ["begin insert into profiles (Id, CreationDate, WebsiteUrl) select new.Id, new.CreationDate, left(replace(new.WebsiteUrl, '.', '-'), charindex('@', replace(new.WebsiteUrl, '.', '-')) - 1); return new; end;"], "sol_sql": [], "preprocess_sql": ["DROP TABLE IF EXISTS profiles; CREATE TABLE profiles (id varchar(256) NOT NULL, CreationDate text, WebsiteUrl text, PRIMARY KEY (id));"], "clean_up_sql": [], "test_cases": []} {"instance_id": 37, "selected_database": "financial", "query": "We have a large transaction table in our financial database with over 180 million rows and 20 GB in size. The table is structured to store detailed transaction records for various accounts. We are running a query to retrieve specific transactions based on a list of account IDs, a specific bank, and a range of transaction types. The query is taking an unexpectedly long time to execute when the shared buffers are cold, around 9 seconds, but only 25 ms when the data is cached. We suspect that the query planner is not choosing the most optimal execution plan. We have tried adding a covering index and forcing a Bitmap Heap Scan, but we would like to understand why the planner is not making the best choice and find a more permanent solution to improve performance to around 1-2 seconds.", "error_sql": ["SELECT t.trans_id, t.account_id, t.date, t.type, t.amount FROM trans t JOIN account a ON t.account_id = a.account_id WHERE a.district_id = 18 AND t.bank = 'AB' AND t.type IN ('PRIJEM', 'VYDAJ')"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": [], "efficiency": true} {"instance_id": 38, "selected_database": "card_games", "query": "A user is working with a table named `cards` in the `card_games` database. They want to find card records that match specific criteria: `availability` is 'paper', `bordercolor` is 'black', `rarity` is 'uncommon', and `type` is 'Creature'. They can write a query to get rows that match all these conditions. However, they also want to find cards that meet 3 out of these 4 criteria. Can this be done in a single SQL query?", "error_sql": ["SELECT * FROM cards WHERE availability = 'paper' AND bordercolor = 'black' AND rarity = 'uncommon' AND types = 'Creature';"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 39, "selected_database": "student_club", "query": "I want to insert a new event into the 'event' table and, in case of a duplicate event ID (which is unique), log the failure in the 'failure' table with specific event ID and member ID indicating the error. For example, I want to insert an event with the ID 'recAlAwtBZ0Fqbr5K' and name 'Annual Gala'. If it fails due to a duplicate name, log the failure with the member ID 'rec280Sk7o31iG0Tx'. My current SQL statement is producing an error: syntax error at or near 'insert'.", "error_sql": ["insert into event (event_id, event_name, event_date, type, notes, location, status) values ('recAlAwtBZ0Fqbr5K', 'Annual Gala', '2023-12-15T19:00:00', 'Social', 'Annual Gala for club members', 'Grand Ballroom', 'Open') on conflict (event_id) do insert into failure (event, member) values ('recAlAwtBZ0Fqbr5K', 'rec280Sk7o31iG0Tx');"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE failure (event VARCHAR(255) NOT NULL, member VARCHAR(255) NOT NULL, PRIMARY KEY (event, member));"], "clean_up_sql": ["DROP TABLE IF EXISTS failure;"], "test_cases": []} {"instance_id": 40, "selected_database": "european_football_2", "query": "I am new to functions and triggers in PostgreSQL. I am trying to create a trigger function to log changes in the player's name in the Player table. I followed a tutorial but encountered an error. The code block and the error are provided below. The Player table contains detailed information about players. The player_audits table is intended to keep track of any changes to the player's name along with the timestamp of the change.", "error_sql": ["CREATE OR REPLACE FUNCTION log_player_name_changes() RETURNS trigger AS $BODY$ BEGIN IF NEW.player_name <> OLD.player_name THEN INSERT INTO player_audits(player_id, old_player_name, changed_on) VALUES(OLD.id, OLD.player_name, now()); END IF; RETURN NEW; END; $BODY$ CREATE TRIGGER tr_change_playername AFTER UPDATE OF player_name ON player FOR EACH ROW EXECUTE PROCEDURE log_player_name_changes();"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE player_audits (player_id int, old_player_name text, changed_on timestamp );"], "clean_up_sql": ["DROP TABLE IF EXISTS player_audits;"], "test_cases": []} {"instance_id": 41, "selected_database": "student_club", "query": "\nI have an event_attendance table and what I am trying to build should be one row for each member.\\nColumn definitions of the expected output:\\nGame_AttendanceDate : Latest attendance date based on date where EventType = 'Game'\\nGame_Attendances: Total number of Game events attended by each member.\\nWorkshop_AttendanceDate: Latest attendance date based on date where EventType = 'Workshop'\\nWorkshop_Attendances: Total number of Workshop events attended by each member.\\nTotal_Attendances: Total events attended by each member. I tried on one categories but I have to do this calculation for another 2 categories then that will add up another 2 sub queries. Is there anyway to optimize the SQL code?\n", "error_sql": ["\nSELECT\n COALESCE(a.MemberID, b.MemberID) AS MemberID,\n a.AttendanceDate AS Latest_Game_Date,\n a.Game_Attendance AS Total_Game_Attendance,\n b.AttendanceDate AS Latest_Workshop_Date,\n b.Workshop_Attendance AS Total_Workshop_Attendance,\n a.Game_Attendance + b.Workshop_Attendance AS Total_Attendance\nFROM \n(\n SELECT \n MemberID, \n EventType,\n AttendanceDate,\n COUNT(EventID) OVER(PARTITION BY MemberID, EventType) AS Game_Attendance,\n ROW_NUMBER() OVER(PARTITION BY MemberID, EventType ORDER BY AttendanceDate DESC) AS RNUM\n FROM event_attendance\n WHERE EventType = 'Game'\n) a\nFULL JOIN \n(\n SELECT \n MemberID, \n EventType,\n AttendanceDate,\n COUNT(EventID) OVER(PARTITION BY MemberID, EventType) AS Workshop_Attendance,\n ROW_NUMBER() OVER(PARTITION BY MemberID, EventType ORDER BY AttendanceDate DESC) AS RNUM\n FROM event_attendance\n WHERE EventType = 'Workshop'\n) b\nON a.MemberID = b.MemberID\nWHERE (a.RNUM = 1 OR a.RNUM IS NULL) AND (b.RNUM = 1 OR b.RNUM IS NULL);\n"], "sol_sql": [], "preprocess_sql": ["\nCREATE TABLE event_attendance (MemberID int, EventID int, EventType text, AttendanceDate date); INSERT INTO event_attendance (MemberID, EventID, EventType, AttendanceDate) VALUES (1, 101, 'Game', '2023-01-01'), (1, 102, 'Game', '2023-01-10'), (1, 103, 'Game', '2023-02-15'), (1, 104, 'Game', '2023-02-20'), (1, 105, 'Workshop', '2023-03-01'), (1, 106, 'Workshop', '2023-03-20'), (2, 107, 'Game', '2023-01-15'), (2, 108, 'Workshop', '2023-02-06');\n"], "clean_up_sql": ["DROP TABLE event_attendance;"], "test_cases": [], "efficiency": true} {"instance_id": 42, "selected_database": "codebase_community", "query": "\nI'm working with a table called `preference_tag`, which contains a `userid` and an array of tags in the `tag` column. \nI need to find rows in the user's tag preference table where the array contains the corresponding tags. \nFor example, when querying with `ARRAY['friend', 'cat']`, it works as expected, returning the rows where the array contains both 'friend' and 'cat'. \nHowever, when I try to use wildcard symbols (e.g., `ARRAY['%friend%', '%cat%']`), it doesn't return the expected results. \nThe issue seems to be related to the `%` symbols, as I want to match any values that contain substrings like 'friend' or 'cat', but I don't need an exact match.\n", "error_sql": ["\nSELECT DISTINCT userid, tag\nFROM preference_tag\nWHERE tag @> (ARRAY['friend', 'cat']::VARCHAR[]);\n"], "sol_sql": [], "preprocess_sql": ["\nCREATE TABLE preference_tag (\n userid INT PRIMARY KEY,\n tag TEXT[]\n);\n\nINSERT INTO preference_tag (userid, tag) VALUES\n(1, ARRAY['friend', 'apple', 'cat']),\n(2, ARRAY['cat', 'friend', 'dog']),\n(3, ARRAY['pasta', 'best-friend', 'lizard']),\n(4, ARRAY['wildcat', 'potato', 'alices-friend']);\n\n"], "clean_up_sql": ["DROP TABLE preference_tag;"], "test_cases": []} {"instance_id": 43, "selected_database": "financial", "query": "In the financial database, there is a table named 'account_info' that stores the detailed information of accounts. Each row in the table includes an array in the 'condition' column, which contains various conditions related to the account. We need to find all qualifying accounts where the 'condition' column contains a condition with a specific 'rootcompanyid' value of 5. The current query is only returning the last row that matches the condition, but we need all rows that have this 'rootcompanyid' value in any part of the array.", "error_sql": ["SELECT * FROM account_info WHERE ((condition->0->>'conditions')::json->>'rootcompanyid')::json->>'$in' = '[5]';"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE IF NOT EXISTS account_info (account_id INTEGER, condition JSONB);", "INSERT INTO account_info (account_id, condition) VALUES (1, '[{\"action\":\"read\",\"subject\":\"rootcompany\",\"conditions\":{\"rootcompanyid\":{\"$in\":[35,20,5,6]}}}]'::jsonb), (2, '[{\"action\":\"read\",\"subject\":\"rootcompany\",\"conditions\":{\"rootcompanyid\":{\"$in\":[1,4,2,3,6]}}}]'::jsonb), (3, '[{\"action\":\"read\",\"subject\":\"rootcompany\",\"conditions\":{\"rootcompanyid\":{\"$in\":[5]}}}]'::jsonb);"], "clean_up_sql": ["DROP TABLE IF EXISTS account_info;"], "test_cases": [], "external_data": "{\"action\":\"read\",\"subject\":\"rootcompany\",\"conditions\":{\"rootcompanyid\":{\"$in\":[35,20,5,6]}}}, {\"action\":\"read\",\"subject\":\"rootcompany\",\"conditions\":{\"rootcompanyid\":{\"$in\":[1,4,2,3,6]}}}, {\"action\":\"read\",\"subject\":\"rootcompany\",\"conditions\":{\"rootcompanyid\":{\"$in\":[5]}}}"} {"instance_id": 44, "selected_database": "superhero", "query": "I am working on a superhero database and have a table called 'hero_power' that records the powers of each superhero. Currently, the combination of 'hero_id' and 'power_id' is supposed to be unique, meaning that a superhero cannot have the same power listed more than once. However, this is not quite what I want. Instead, I would want the combination 'hero_id' and 'power_id' to be unique only in cases where the power is currently active. In other words, a superhero should be able to have multiple instances of the same power listed if the power is inactive, but should not be allowed to have duplicates that are active. Is there a way to enforce this in this table?", "error_sql": ["ALTER TABLE hero_power ADD CONSTRAINT unique_active_hero_power UNIQUE (hero_id, power_id);"], "sol_sql": [], "preprocess_sql": ["ALTER TABLE hero_power ADD COLUMN active BOOLEAN DEFAULT TRUE;"], "clean_up_sql": ["ALTER TABLE hero_power DROP COLUMN IF EXISTS active;", "DROP INDEX IF EXISTS idx_hero_power_active;"], "test_cases": []} {"instance_id": 45, "selected_database": "toxicology", "query": "In the toxicology database, we have a table named `orders` that records the purchases made by users. Each record includes the `user_id`, `email`, `segment` (type of purchase), `destination` (location of purchase), and `revenue` (amount spent). We need to identify users who meet specific criteria based on their purchase history:\\n1) Users who have made a purchase in the `luxury` segment with a `destination` of `New York`.\\n2) Users who have made a purchase in the `luxury` segment with a `destination` of `London`.\\n3) Users who have made purchases in the `basic` segment with a `destination` of `New York` and the total revenue from these purchases exceeds $2,000.\\n4) Users who have never made a purchase with a `destination` of `Miami`.\\nGiven the sample data, we expect to retrieve the following users:\\nuser_id email \\\\(3 mike@me.com \\\\(4 sally@you.com \\\\(5 bob@gmail.com \\\\)The user attempted to use the following SQL query to get part of the required results, but it did not account for conditions 3 and 4:\\nsql \\\\(SELECT DISTINCT(user_id), email FROM orders o WHERE (o.segment = 'luxury' AND o.destination = 'New York') OR (o.segment = 'luxury' AND o.destination = 'London') \\\\)", "error_sql": ["SELECT DISTINCT(user_id), email FROM orders o WHERE (o.segment = 'luxury' AND o.destination = 'New York') OR (o.segment = 'luxury' AND o.destination = 'London')"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE orders (user_id INT, email TEXT, segment TEXT, destination TEXT, revenue NUMERIC); INSERT INTO orders (user_id, email, segment, destination, revenue) VALUES (1, 'joe@smith.com', 'basic', 'New York', 500), (1, 'joe@smith.com', 'luxury', 'London', 750), (1, 'joe@smith.com', 'luxury', 'London', 500), (1, 'joe@smith.com', 'basic', 'New York', 625), (1, 'joe@smith.com', 'basic', 'Miami', 925), (1, 'joe@smith.com', 'basic', 'Los Angeles', 218), (1, 'joe@smith.com', 'basic', 'Sydney', 200), (2, 'mary@jones.com', 'basic', 'Chicago', 375), (2, 'mary@jones.com', 'luxury', 'New York', 1500), (2, 'mary@jones.com', 'basic', 'Toronto', 2800), (2, 'mary@jones.com', 'basic', 'Miami', 750), (2, 'mary@jones.com', 'basic', 'New York', 500), (2, 'mary@jones.com', 'basic', 'New York', 625), (3, 'mike@me.com', 'luxury', 'New York', 650), (3, 'mike@me.com', 'basic', 'New York', 875), (4, 'sally@you.com', 'luxury', 'Chicago', 1300), (4, 'sally@you.com', 'basic', 'New York', 1200), (4, 'sally@you.com', 'basic', 'New York', 1000), (4, 'sally@you.com', 'luxury', 'Sydney', 725), (5, 'bob@gmail.com', 'basic', 'London', 500), (5, 'bob@gmail.com', 'luxury', 'London', 750);"], "clean_up_sql": ["DROP TABLE orders;"], "test_cases": []} {"instance_id": 46, "selected_database": "formula_1", "query": "In the Formula 1 database, there is a table named 'cars' which contains the information of cars. Each entry includes a 'version' column that records the version of the car used by the driver in the race. The version numbers are in a format similar to '3.0.5-1-test-dev' and need to be sorted correctly to determine the latest version used in a race. However, the current sorting method does not handle multi-digit numbers correctly and fails when the version includes additional string information after the numeric version. The task is to write a query that correctly sorts the versions. If the table is sorted, I can get the latest version by select the first one.", "error_sql": ["SELECT version FROM cars ORDER BY SUBSTRING(version, '^[0-9]+') DESC, SUBSTRING(version, '[0-9]+\\.[0-9]+\\.([0-9]+)-') DESC, CAST(SUBSTRING(version, '[0-9]+\\.[0-9]+\\.[0-9]+-([0-9]+)') AS INTEGER) DESC, SUBSTRING(version, '[0-9]+\\.[0-9]+\\.[0-9]+-[0-9]+\\.([0-9]+)') DESC"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE cars (version varchar(100))", "INSERT INTO cars (version) VALUES ('3.0.5-1-test-dev'), ('3.0.6-1'), ('3.0.7-1-test'), ('3.0.8-1-test-dev-test23'), ('3.0.9-1'), ('3.0.13-2'), ('3.0.4-1-1'), ('3.0.10-1'), ('3.0.11-2'), ('3.0.11-1')"], "clean_up_sql": ["DROP TABLE cars;"], "test_cases": []} {"instance_id": 47, "selected_database": "thrombosis_prediction", "query": "In the thrombosis_prediction database, we have a set of normalized tables representing patients, medications, and their prescriptions. Each patient can be prescribed multiple medications, and each medication can be prescribed to multiple patients. For reporting purposes, we need a highly denormalized view that shows each patient's name and a list of all medications they are prescribed. However, when we filter the list to show only patients who are prescribed a specific medication (e.g., Aspirin), we lose the information about other medications those patients are prescribed. We want to filter by a specific medication but still get a list of all medications that a patient is prescribed in one row.", "error_sql": ["SELECT prescriptions.patient_id, array_agg(DISTINCT prescriptions.medication_id ORDER BY prescriptions.medication_id) AS medications FROM prescriptions INNER JOIN prescriptions AS Aspirin_filter ON prescriptions.patient_id = Aspirin_filter.patient_id AND Aspirin_filter.medication_id = 1 GROUP BY prescriptions.patient_id;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE patients ( patient_id SERIAL PRIMARY KEY, patient_name TEXT NOT NULL );", "CREATE TABLE medications ( medication_id SERIAL PRIMARY KEY, medication_name TEXT NOT NULL );", "CREATE TABLE prescriptions ( patient_id INT REFERENCES patients (patient_id), medication_id INT REFERENCES medications (medication_id), PRIMARY KEY (patient_id, medication_id) );", "INSERT INTO patients (patient_name) VALUES ('Alice'), ('Bob'), ('Charlie');", "INSERT INTO medications (medication_name) VALUES ('Aspirin'), ('Ibuprofen'), ('Paracetamol'), ('Warfarin');", "INSERT INTO prescriptions (patient_id, medication_id) VALUES (1, 1), (1, 2), (1, 3);", "INSERT INTO prescriptions (patient_id, medication_id) VALUES (2, 2);", "INSERT INTO prescriptions (patient_id, medication_id) VALUES (3, 2), (3, 1), (3, 3), (3, 4);"], "clean_up_sql": [], "test_cases": [], "efficiency": true} {"instance_id": 48, "selected_database": "formula_1", "query": "In the context of Formula 1 racing data, I have two tables: `races` and `results`. The `races` table contains information about each race, including the `raceId` which uniquely identifies each race. The `results` table contains detailed information about the results of each race, including the `raceId` to link back to the `races` table, `driverId` to identify the driver, and `points` which represent the points scored by the driver in that race. I need to calculate the total points scored by each driver across all races, but only for races where the driver has participated. If a driver has not participated in any races, their total points should be `0`. I attempted to write a query to achieve this but encountered issues with grouping and ensuring that drivers who haven't participated in any races are included with a total of `0` points.", "error_sql": ["SELECT r.driverId, ((SELECT COALESCE(SUM(r.points), 0) FROM results r WHERE r.raceId = races.raceId) - (SELECT COALESCE(SUM(r.points), 0) FROM results r WHERE r.raceId = races.raceId)) AS total_points FROM results r GROUP BY r.driverId"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 49, "selected_database": "superhero", "query": "In the context of the superhero database, I need to calculate the total count of superheroes by their alignment and also display the count of superheroes for each specific alignment and race combination. I attempted to write a query to achieve this but it doesn't provide the total count by alignment as I expected. Here's what I tried:", "error_sql": ["select count(S.id), A.alignment, count(R.race), R.race from superhero S, alignment A, race R where S.alignment_id=A.id and S.race_id=R.id group by A.alignment, R.race;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 50, "selected_database": "formula_1", "query": "In the context of analyzing Formula 1 race results, I'm trying to understand the behavior of window functions in PostgreSQL. Specifically, I'm looking at the `array_agg` function with and without an `ORDER BY` clause within a window function. I expect both to return the same result since no filtering is applied, but they don't. Here's the scenario: I have a table of race results, and I want to aggregate the driver IDs in two ways: one with an order by the points they scored in the race, and another without any order. The results seem to suggest that ordering the partition affects the aggregation, which is confusing. Here's the SQL I used:", "error_sql": ["select driverId, points, lead(driverId) over (order by points asc) as \"lead(driverId) with order\", array_agg(driverId) over (order by points asc) as \"array_agg(driverId) with order\", lead(driverId) over () as \"lead(driverId) without order\", array_agg(driverId) over () as \"array_agg(driverId) without order\" from results where raceId = 19 order by driverId asc"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 51, "selected_database": "formula_1", "query": "In the context of Formula 1 racing data analysis, a user is attempting to calculate the total duration of pit stops for each race day based on the difference between consecutive pit stop times recorded in the same column. The user has a table that records pit stop details including race ID, driver ID, stop number, lap number, pit stop time, and duration. The user's initial approach was to calculate the maximum and minimum pit stop times for each race day and then find the difference between these times to estimate the total pit stop duration. However, this approach misses the intermediate pit stops, leading to an inaccurate total duration calculation. The user is seeking a method to accurately calculate the total pit stop duration by considering all consecutive pit stop times for each race day.", "error_sql": ["SELECT \n raceId,\n MAX(time::time) AS end_time,\n MIN(time::time) AS start_time,\n (MAX(time::time) - MIN(time::time)) AS total_duration\nFROM pitStops\nWHERE raceId = 842\nGROUP BY raceId;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 52, "selected_database": "toxicology", "query": "In the toxicology database, I'm attempting to retrieve a specific data structure from a query. My data is structured in a way that each molecule has atoms connected by bonds, and each molecule is labeled as either carcinogenic (+) or not carcinogenic (-). I want to return a object that groups molecules by their label and lists the atoms and bonds for each molecule. The desired output format is a object where each key is a label, and the value is an array of objects, each representing a molecule with its atoms and bonds. Here's the SQL query I have so far, but it doesn't produce the desired output structure:", "error_sql": ["select label, JSON_AGG(JSON_BUILD_OBJECT(atom.molecule_id, atom.atom_id)) AS groupedMolecules FROM molecule JOIN atom ON molecule.molecule_id = atom.molecule_id GROUP BY label"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 53, "selected_database": "toxicology", "query": "In the context of a toxicology database, I have a `molecule` table that tracks molecules and their carcinogenic status, and an `atom` table that records atoms within these molecules. Each atom is identified by a unique `atom_id` and belongs to a molecule identified by `molecule_id`. The `element` column in the `atom` table specifies the chemical element of the atom. I need to count the number of sodium (`na`) and carbon (`c`) or chlorine (`cl`) atoms for each molecule. However, if both carbon (`c`) and chlorine (`cl`) elements within the same molecule, they should be counted as one. Here's the SQL query I attempted, but it counts each atom individually, even if they are of the same element within the same molecule:", "error_sql": ["SELECT molecule_id, COALESCE(SUM(CASE WHEN element = 'na' THEN 1 ELSE 0 END), 0) na_atoms, COALESCE(SUM(CASE WHEN element = 'c' OR element = 'cl' THEN 1 ELSE 0 END), 0) c_atoms FROM atom GROUP BY molecule_id;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 54, "selected_database": "european_football_2", "query": "In the context of analyzing football match data, I'm attempting to calculate the average number of goals scored by each team, grouped by the hour of the match. The goal is to understand the performance trends of teams at different times of the day without resorting to external scripting. Here's the initial approach I took, which unfortunately resulted in an error due to incorrect handling of the timestamp data.", "error_sql": ["SELECT home_team_api_id, AVG(home_team_goal) as avg_home_goals, AVG(away_team_goal) as avg_away_goals, SUM(home_team_goal) as total_home_goals, SUM(away_team_goal) as total_away_goals, MAX(home_team_goal) as max_home_goals, MIN(home_team_goal) as min_home_goals, COUNT(home_team_api_id) as count FROM Match GROUP BY home_team_api_id, date_part('hour', date);"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 55, "selected_database": "debit_card_specializing", "query": "In the table clients_to_groups, we need to identify clients who have made transactions at gas stations that belong to specific groups. Specifically, we want to find clients who have made transactions at gas stations that are either in the group 1 or 3 AND also in group 5 or 6. For example, a client who has made transactions at a gas station in the group 5 and another transaction at a gas station in the group 1 should be included in the results, but a client who has only made transactions at gas stations in the group 5 should not be included.", "error_sql": ["SELECT DISTINCT c.id FROM clients c INNER JOIN clients_to_groups at1 ON c.id = at1.client_id INNER JOIN clients_to_groups at2 ON c.id = at2.client_id WHERE at1.group_id IN (5, 6) AND at2.group_id IN (1, 3);"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE clients (id INT NOT NULL);", "CREATE TABLE groups (id INT NOT NULL);", "CREATE TABLE clients_to_groups (id serial, group_id INT, client_id INT);", "INSERT INTO clients(id) VALUES (0), (1), (2), (3);", "INSERT INTO groups(id) VALUES (1), (3), (5), (6);", "INSERT INTO clients_to_groups(client_id, group_id) VALUES (0, 1), (0, 5), (1, 1), (1, 90), (2, 1), (3, 3), (3, 5), (3, 90);", "INSERT INTO clients (id) SELECT random() from generate_series(1,2000);", "INSERT INTO clients_to_groups(client_id, group_id) SELECT random(), random() from generate_series(1,2000);"], "clean_up_sql": ["DROP TABLE clients;", "DROP TABLE groups;", "DROP TABLE clients_to_groups;"], "test_cases": [], "efficiency": true} {"instance_id": 56, "selected_database": "european_football_2", "query": "In the context of the 'european_football_2' database, consider a table that records daily financial transactions for football clubs. Each transaction includes the date, the club name, and the amount of money involved, which can be positive (income) or negative (expense). The goal is to group these transactions by club and sign (positive or negative) and sum the amounts for consecutive transactions of the same sign for each club. For example, if a club has consecutive positive transactions, they should be summed up into a single transaction. The user attempted to use window functions but encountered issues with their query, which did not produce the desired output.", "error_sql": ["SELECT transaction_date AS date, club_name, sum(amount) over (partition by club_name, sign(amount) order by transaction_date) from club_transactions"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE club_transactions (transaction_date DATE, club_name VARCHAR(50), amount INTEGER);", "INSERT INTO club_transactions (transaction_date, club_name, amount) VALUES ('2023-01-01', 'Manchester United', 3), ('2023-01-02', 'Manchester United', 2), ('2023-01-03', 'Manchester United', 1), ('2023-01-04', 'Manchester United', -5), ('2023-01-05', 'Manchester United', 1), ('2023-01-01', 'Liverpool', 2), ('2023-01-02', 'Liverpool', -1), ('2023-01-03', 'Liverpool', -6);"], "clean_up_sql": ["DROP TABLE club_transactions;"], "test_cases": []} {"instance_id": 57, "selected_database": "california_schools", "query": "I have a table in Postgres that returns flat data. But I would like it to be returned to me in a Json ordered with its children as follows, and I have not been able to solve it.Is there a way in postgresql to order the parent modules with their child modules, I attach an example \"[{\"children\":[{\"id_module\":4,\"desc_module\":\"asdf\",\"module_code\":\"asdf\",\"name_module\":\"asdf\",\"id_parent_module\":1},{\"id_module\":3,\"desc_module\":\"C\",\"module_code\":\"232\",\"name_module\":\"C\",\"id_parent_module\":1},{\"id_module\":2,\"desc_module\":\"B\",\"module_code\":\"011.002\",\"name_module\":\"B\",\"id_parent_module\":1}],\"id_module\":1,\"desc_module\":\"A\",\"module_code\":\"001\",\"name_module\":\"A\",\"id_parent_module\":null},{\"children\":[{\"id_module\":14,\"desc_module\":\"asdf\",\"module_code\":\"asdf\",\"name_module\":\"asdf\",\"id_parent_module\":5}],\"id_module\":5,\"desc_module\":\"asdf\",\"module_code\":\"asdf\",\"name_module\":\"asdf\",\"id_parent_module\":null},{\"children\":[{\"id_module\":22,\"desc_module\":\"asdf\",\"module_code\":\"asdf\",\"name_module\":\"asdf\",\"id_parent_module\":6},{\"id_module\":8,\"desc_module\":\"asdf\",\"module_code\":\"asdf\",\"name_module\":\"asdf\",\"id_parent_module\":6},{\"id_module\":7,\"desc_module\":\"asdf\",\"module_code\":\"asdf\",\"name_module\":\"asdf\",\"id_parent_module\":6}],\"id_module\":6,\"desc_module\":\"qw\",\"module_code\":\"23\",\"name_module\":\"asdf\",\"id_parent_module\":null},{\"children\":[{\"id_module\":21,\"desc_module\":\"asdf\",\"module_code\":\"asdf\",\"name_module\":\"asdf\",\"id_parent_module\":9},{\"id_module\":20,\"desc_module\":\"asdf\",\"module_code\":\"asdf\",\"name_module\":\"asdf\",\"id_parent_module\":9}],\"id_module\":9,\"desc_module\":\"asdfsad\",\"module_code\":\"asdf\",\"name_module\":\"asdf\",\"id_parent_module\":null},{\"children\":[{\"id_module\":13,\"desc_module\":\"asdf\",\"module_code\":\"asdf\",\"name_module\":\"asdf\",\"id_parent_module\":10},{\"id_module\":12,\"desc_module\":\"asdfsf\",\"module_code\":\"asdf\",\"name_module\":\"asdf\",\"id_parent_module\":10},{\"id_module\":11,\"desc_module\":\"asdf\",\"module_code\":\"sadf\",\"name_module\":\"asdf\",\"id_parent_module\":10}],\"id_module\":10,\"desc_module\":\"asdf\",\"module_code\":\"asdf\",\"name_module\":\"asdf\",\"id_parent_module\":null}]\"", "error_sql": ["SELECT array_to_json(array_agg(row_to_json(alias))) FROM (select * from modules ) alias"], "sol_sql": [], "preprocess_sql": ["create table modules (id_module int, id_parent_module int, module_code text, name_module text, desc_module text);", "insert into modules values (1, null, '001', 'A', 'A'), (2, 1, '011.002', 'B', 'B'), (3, 1, '232', 'C', 'C'), (4, 1, 'asdf', 'asdf', 'asdf'), (5, null, 'asdf', 'asdf', 'asdf'), (14, 5, 'asdf', 'asdf', 'asdf'), (6, null, '23', 'asdf', 'qw'), (7, 6, 'asdf', 'asdf', 'asdf'), (8, 6, 'asdf', 'asdf', 'asdf'), (22, 6, 'asdf', 'asdf', 'asdf'), (9, null, 'asdf', 'asdf', 'asdfsad'), (20, 9, 'asdf', 'asdf', 'asdf'), (21, 9, 'asdf', 'asdf', 'asdf'), (10, null, 'asdf', 'asdf', 'asdf'), (11, 10, 'sadf', 'asdf', 'asdf'), (12, 10, 'asdf', 'asdf', 'asdfsf'), (13, 10, 'asdf', 'asdf', 'asdf');"], "clean_up_sql": ["DROP TABLE modules;"], "test_cases": []} {"instance_id": 58, "selected_database": "toxicology", "query": "In the toxicology database, we have a table named 'atom_edits' that records updates to the 'atom' table. Users can update the 'element' or 'molecule_id' of an atom. If a field is not updated, it retains a NULL value. Here's an example of four edits touching two separate atoms. Atom with ID 'TR000_1' received two updates: the first one is updating the 'element' field, the second one touches the 'molecule_id'. Atom with ID 'TR000_2' received one update that changes the 'element'. We need to merge this table such that in the resulting table there's one row per atom, giving the cumulative edits.", "error_sql": ["SELECT atom_id, (ARRAY_REMOVE(ARRAY_AGG(element ORDER BY edit_id DESC), NULL))[1] AS element, (ARRAY_REMOVE(ARRAY_AGG(molecule_id ORDER BY edit_id DESC), NULL))[1] AS molecule_id FROM atom_edits GROUP BY atom_id;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE atom_edits (edit_id SERIAL PRIMARY KEY, atom_id TEXT, element TEXT, molecule_id TEXT); INSERT INTO atom_edits (atom_id, element, molecule_id) VALUES ('TR000_1', 'cl', NULL), ('TR000_1', NULL, 'TR001'), ('TR000_2', 'c', NULL);"], "clean_up_sql": ["DROP TABLE atom_edits;"], "test_cases": [], "efficiency": true} {"instance_id": 59, "selected_database": "debit_card_specializing", "query": "We are trying to bulk insert a large number of customer records into the `customers` table using an `INSERT` statement with an `ON CONFLICT` clause. The goal is to get the `CustomerID` back for all rows, whether they are already existing or not. The `customers` table has a composite unique constraint on `Segment` and `Currency`. We are encountering an error when trying to run the SQL through Django's cursor. The error message indicates that the `ON CONFLICT DO UPDATE` command cannot affect a row a second time due to duplicate constrained values in the `VALUES` list. We need to handle this situation to ensure that we can insert new records and retrieve the IDs of both new and existing records.", "error_sql": ["INSERT INTO customers (customerid, segment, currency) VALUES (3, 'SME', 'EUR'), (1, 'KAM', 'CZK'), (3, 'SME', 'EUR') ON CONFLICT (customerid, segment, currency) DO UPDATE SET Currency = customers.Currency RETURNING CustomerID;"], "sol_sql": [], "preprocess_sql": ["ALTER TABLE customers\nADD CONSTRAINT customers_customerid_segment_currency_uk\nUNIQUE (customerid, segment, currency);"], "clean_up_sql": ["DROP TABLE customers;"], "test_cases": []} {"instance_id": 60, "selected_database": "financial", "query": "In the financial database, there are two tables: 'client' and 'disp'. The 'disp' table contains a B column named 'addresses' which stores address information for each client. I attempted to join the 'client' and 'disp' tables on the 'client_id' field and then use b_array_elements to extract address details. However, I encountered an error 'cannot extract elements from a scalar' because some entries in the 'addresses' column are not arrays. I need to handle these cases properly to extract the 'PostCode' from the addresses B column for a specific client with client_id = 12345.", "error_sql": ["SELECT \n client.client_id, \n client.gender, \n disp.disp_id, \n address ->> 'PostCode' AS PostCode\nFROM client\nFULL JOIN disp ON (client.client_id = disp.client_id),\njsonb_array_elements(disp.addresses) AS address\nWHERE disp.client_id = 12345;"], "sol_sql": [], "preprocess_sql": ["ALTER TABLE disp \nADD COLUMN addresses jsonb;", "INSERT INTO disp (disp_id, client_id, account_id, addresses) VALUES\n (324124, 32323432, 4342443141, '[{\"PostCode\":\"12345\"}]'),\n (43244241, 3455566, 645634, '[null]'),\n (42342436, 12345, 5346574, 'null');"], "clean_up_sql": ["\n DELETE FROM disp \n WHERE disp_id IN (324124, 43244241, 42342436);\n ", "\n ALTER TABLE disp \n DROP COLUMN addresses;\n "], "test_cases": []} {"instance_id": 61, "selected_database": "financial", "query": "In the financial database, I want to update the 'amount' in the 'loan' table for a specific 'account_id' and 'date' if it exists, or insert a new record if it does not. However, I do not want the 'loan_id' to increment if an update occurs because it is an auto-incrementing SERIAL column. The 'loan_id' should only increment when a new record is inserted to maintain a sequential order without gaps.", "error_sql": ["\nINSERT INTO loan (\n loan_id, \n account_id, \n date, \n amount, \n duration, \n payments, \n status\n)\nVALUES (\n DEFAULT, \n 2, \n '1996-04-29', \n 30276, \n 12, \n 2523.0, \n 'B'\n)\nON CONFLICT (loan_id, account_id, date)\nDO UPDATE\n SET amount = loan.amount + 1000;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE IF NOT EXISTS loan (loan_id SERIAL PRIMARY KEY, account_id int NOT NULL, date date NOT NULL, amount int NOT NULL, duration int NOT NULL, payments double NOT NULL, status text NOT NULL, UNIQUE(account_id, date)); INSERT INTO loan (loan_id, account_id, date, amount, duration, payments, status) VALUES (134411, 2, '1994-01-05', 80952, 24, 3373.0, 'A');", "\n DELETE FROM loan t1\n USING loan t2\n WHERE t1.account_id = t2.account_id\n AND t1.date = t2.date\n AND t1.loan_id > t2.loan_id;\n ", "ALTER TABLE loan\n ADD CONSTRAINT loan_accountid_date_uk\n UNIQUE (account_id, date);"], "clean_up_sql": ["DROP TABLE IF EXISTS loan;"], "test_cases": []} {"instance_id": 62, "selected_database": "card_games", "query": "In our card_games database, we have a large table named cards which contains detailed information about each card. We also have two smaller tables, norm1 and norm2, which contain a subset of the cards based on certain criteria. The goal is to delete rows from the cards table where the combination of (uuid, setCode, rarity, manaCost) does not exist in either norm1 or norm2. The current query uses two separate NOT IN clauses, which is both verbose and potentially inefficient. We need to rewrite this query to make it more concise and performant.", "error_sql": ["DELETE FROM cards WHERE (uuid, setCode, rarity, manaCost) NOT IN (SELECT uuid, setCode, rarity, manaCost FROM norm1 WHERE uuid IS NOT NULL AND setCode IS NOT NULL AND rarity IS NOT NULL AND manaCost IS NOT NULL) AND (uuid, setCode, rarity, manaCost) NOT IN (SELECT uuid, setCode, rarity, manaCost FROM norm2 WHERE uuid IS NOT NULL AND setCode IS NOT NULL AND rarity IS NOT NULL AND manaCost IS NOT NULL);"], "sol_sql": [], "preprocess_sql": ["\nCREATE TABLE norm1 AS SELECT uuid, setCode, rarity, manaCost FROM cards WHERE id % 2 = 0; CREATE TABLE norm2 AS SELECT uuid, setCode, rarity, manaCost FROM cards WHERE id % 3 = 0;\n"], "clean_up_sql": ["\nDROP TABLE norm1; DROP TABLE norm2;\n"], "test_cases": [], "efficiency": true} {"instance_id": 63, "selected_database": "financial", "query": "In the financial database, I want to apply a forward fill function to all nullable columns of a table. The forward fill function should be applied to each column dynamically, given the table name, an ID column, and a row number column. For example, using the 'trans' table, I want to apply the forward fill to all nullable columns, partitioned by 'account_id' and ordered by 'date'. The function should handle any table with nullable columns and apply the forward fill accordingly. However, my initial attempt at writing the function resulted in a syntax error. I need a corrected version of the function that works for any table with nullable columns.", "error_sql": ["CREATE OR REPLACE FUNCTION f_gap_fill_update(tbl text, id text, row_num text) RETURNS void LANGUAGE plpgsql AS $func$ DECLARE tmp text[]; col text; BEGIN select array ( select column_name from information_schema.columns c where table_name = tbl ) into tmp; foreach col in array tmp loop execute 'update '||tbl||' set '||col||' = gapfill('||col||') OVER w AS '||col||' where '||tbl||'.row_num = '||col||'.row_num window w as (PARTITION BY '||id||' ORDER BY '||row_num||') returning *;'; end loop; end $func$;"], "sol_sql": [], "preprocess_sql": ["CREATE OR REPLACE FUNCTION gap_fill_internal(s anyelement, v anyelement) RETURNS anyelement LANGUAGE plpgsql AS $func$ BEGIN RETURN COALESCE(v, s); END $func$; CREATE AGGREGATE gap_fill(anyelement) ( SFUNC = gap_fill_internal, STYPE = anyelement );"], "clean_up_sql": [""], "test_cases": []} {"instance_id": 64, "selected_database": "financial", "query": "In the financial database, there is a table named 'card' that records details of issued cards. Each card is identified by a 'card_id' and is associated with a 'disp_id', along with other details like 'type' and 'issued'. Let's say we want to change the order of a specific 'disp_id' within the same 'type'. For instance, we want to set the 'disp_id' of a card with 'disp_id' = 41 to 1. This change should reorder the 'disp_id' values of all affected cards within the same 'type'. The expected result is that the card with 'disp_id' = 41 should now have 'disp_id' = 1, and the other cards' 'disp_id' values should be incremented accordingly.", "error_sql": ["UPDATE card SET disp_id = 1 WHERE disp_id = 41;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 65, "selected_database": "financial", "query": "I have created the following custom SQL function on a PostgreSQL 16.1 server to generate a series of monthly dates between two given dates for analyzing transaction trends over time:\\nCREATE OR REPLACE FUNCTION public.generate_series_monthly(a date, b date)\\nRETURNS SETOF date LANGUAGE SQL IMMUTABLE PARALLEL SAFE ROWS 12 AS $function$\\nselect generate_series(date_trunc('month', a), date_trunc('month', b), '1 month')\\n$function$;\\nSpecifically, I have added the row estimate parameter, and as expected, I am seeing this estimate in some simple queries:\\nexplain select generate_series_monthly('2023-01-01', '2023-12-01');\\nHowever, in some uses in queries, I see it falling back to the default of 1000:\\nexplain select * from generate_series_monthly('2023-01-01', '2023-12-01');\\nI would expect this second query to also use the 12 row estimate. Why is it resorting to 1000?", "error_sql": ["CREATE OR REPLACE FUNCTION public.generate_series_monthly(a date, b date) RETURNS SETOF date LANGUAGE SQL IMMUTABLE PARALLEL SAFE ROWS 10 AS $function$ select generate_series(date_trunc('month', a), date_trunc('month', b), '1 month') $function$; EXPLAIN SELECT generate_series_monthly('2024-01-01', '2024-05-01'); EXPLAIN SELECT * FROM generate_series_monthly('2024-01-01', '2024-05-01');"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 66, "selected_database": "european_football_2", "query": "In the context of european_football_2 database whose match table contains columns such as season, date, home_team_goal, away_team_goal, etc. Now, suppose you want to treat any match ending in a draw (home_team_goal = away_team_goal) as if an invoice were being issued (similar to setting Invoiced = 1). Between two such draws, you might have several other matches that do not end in a draw (equivalent to Invoiced = 0), and for each of those matches, you want to treat the total goals scored (i.e., home_team_goal + away_team_goal) like a running amount you accumulate. Finally, you only want to keep the draw rows, and each of those rows should carry the sum of total goals scored since the last draw.", "error_sql": ["SELECT \n m.id,\n m.date,\n CASE WHEN m.home_team_goal = m.away_team_goal THEN 1 ELSE 0 END AS invoiced,\n SUM(m.home_team_goal + m.away_team_goal)\n OVER (PARTITION BY (CASE WHEN m.home_team_goal = m.away_team_goal THEN 1 ELSE 0 END)\n ORDER BY m.id, m.date) AS amount\nFROM match AS m\nORDER BY m.id, m.date;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 67, "selected_database": "debit_card_specializing", "query": "We have a table called transactions_1k that contains transaction details for multiple customers across different gas stations. Each row in this table has:\n1. transaction date\n2. ransaction time\n3. customerid (the ID of the customer)\n4. gasstationid (the ID of the gas station)\n5. productid (the product involved)\n6. amount (the quantity, e.g., liters purchased)\n7. price (the cost)\n\nWe want to filter these transactions under the following rules, per customer:\n1. Only the last transaction at each gas station should be considered.\n2. If the customer has any transaction where amount < 10 (which indicates a potential issue), display the first gas station on which that issue occurred.\n3. If the customer has no transactions with amount < 10, then display the last gas station on which the customer had a transaction with amount >= 10.\n\nGiven some sample data, we expect the final output to show only:\n1. The last transaction for each gas station where amount >= 10.\n2. The first transaction for each gas station where amount < 10.\n\nWe attempted the following SQL query in PostgreSQL to achieve this, but it does not return the desired results. Instead, it only picks the gas station with the maximum gasstationid for each customer and does not correctly determine the earliest occurrence of amount < 10 chronologically. In other words, this query fails to implement “the last transaction per gas station” and “the first station where amount < 10” correctly.", "error_sql": ["WITH DataSource AS (\n SELECT\n *,\n MIN(CASE WHEN amount < 10 THEN gasstationid END) \n OVER (PARTITION BY customerid) AS first_issue_gasstation,\n ROW_NUMBER() OVER (PARTITION BY customerid ORDER BY gasstationid DESC) AS gasstation_id\n FROM transactions_1k\n WHERE gasstationid = (\n SELECT MAX(gasstationid)\n FROM transactions_1k\n WHERE customerid = transactions_1k.customerid\n )\n)\nSELECT \n customerid,\n transactionid,\n gasstationid,\n amount\nFROM DataSource\nWHERE\n (first_issue_gasstation IS NULL AND gasstation_id = 1)\n OR (first_issue_gasstation = gasstationid);"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 68, "selected_database": "superhero", "query": "In the superhero database, we have a directed acyclic graph representing the lineage of superheroes. Each superhero has a unique identifier and a parent identifier, which points to their predecessor in the lineage. Given two superheroes, 'Superhero A' and 'Superhero B', we need to find their common ancestor in the lineage. The provided query is inefficient as it traverses the entire lineage until it finds the root, which is not optimal when the common segment of the lineage is large. We need to find an efficient way to determine the common ancestor with a complexity of O(A+B) where A and B are the number of nodes in the lineages of 'Superhero A' and 'Superhero B', respectively.", "error_sql": ["WITH RECURSIVE linked_list(id, parent_id) AS (SELECT id, parent_id FROM lineage WHERE id = 1001 OR id = 1201 UNION ALL SELECT g.id, g.parent_id FROM lineage g INNER JOIN linked_list ll ON ll.parent_id = g.id) SELECT string_agg(id::TEXT, ',') AS ids, parent_id FROM linked_list GROUP BY parent_id HAVING COUNT(DISTINCT id) > 1;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE lineage (id INT PRIMARY KEY, parent_id INT);", "INSERT INTO lineage (id, parent_id) SELECT i, CASE WHEN i = 1 THEN NULL ELSE i - 1 END FROM generate_series(1, 1000) AS i;", "INSERT INTO lineage (id, parent_id) SELECT 1000 + i, 1000 + i - 1 FROM generate_series(1, 200) AS i;", "INSERT INTO lineage (id, parent_id) SELECT 1200 + i, 1000 + i - 1 FROM generate_series(1, 200) AS i;"], "clean_up_sql": ["DROP TABLE lineage;"], "test_cases": [], "efficiency": true} {"instance_id": 69, "selected_database": "card_games", "query": "In a digital card trading platform, users perform various actions such as `LOGIN`, `SEARCH`, and `BUY`. An abandoned `SEARCH` action is defined as when a user `LOGIN`s, performs one or more `SEARCH` actions, and does not perform a `BUY` action before the next `LOGIN`. Given a table `user_actions` that records `user_id`, `action`, and `action_time`, determine all abandoned `SEARCH` actions.", "error_sql": ["SELECT c1.user_id, COUNT(*) FROM user_actions c1 LEFT JOIN (SELECT user_id, action, action_time FROM user_actions WHERE action = 'LOGIN') c2 ON c1.user_id = c2.user_id AND c2.action_time > c1.action_time LEFT JOIN (SELECT user_id, action, action_time FROM user_actions WHERE action = 'BUY') c3 ON c1.user_id = c3.user_id AND c3.action_time > c1.action_time AND c3.action_time < c2.action_time WHERE c1.action = 'SEARCH' AND c2.user_id IS NOT NULL AND c3.user_id IS NULL GROUP BY 1"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE user_actions(user_id VARCHAR(1) NOT NULL, action VARCHAR(6) NOT NULL, action_time DATE NOT NULL);", "INSERT INTO user_actions(user_id, action, action_time) VALUES ('A', 'LOGIN', '2023-05-01'), ('A', 'SEARCH', '2023-05-02'), ('A', 'SEARCH', '2023-05-03'), ('A', 'BUY', '2023-05-04'), ('B', 'LOGIN', '2023-05-01'), ('B', 'SEARCH', '2023-05-02'), ('B', 'SEARCH', '2023-05-03'), ('B', 'LOGIN', '2023-05-04'), ('B', 'SEARCH', '2023-05-05')"], "clean_up_sql": ["DROP TABLE user_actions"], "test_cases": []} {"instance_id": 70, "selected_database": "card_games", "query": "In the card_games database, there is a table named 'cards' which contains various details about each card, including a unique identifier 'id' and the card's name 'name'. Another table named 'decks' stores information about different decks, where each deck has a unique identifier 'id' and an array 'card_order' that lists the 'id's of the cards in the deck in the order they should be played. When a user selects a deck, they want to see the cards in the order they are listed in the 'card_order' array. However, the current SQL query does not preserve the order of the cards as specified in the 'card_order' array. The user's current SQL query is provided below and it does not maintain the order of the cards.", "error_sql": ["SELECT c.id, c.name FROM cards c WHERE c.id IN (SELECT unnest(card_order) FROM decks WHERE id = 1);"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE decks (id bigint PRIMARY KEY, card_order bigint[]);", "INSERT INTO decks (id, card_order) VALUES (1, ARRAY[3, 6, 1]), (2, ARRAY[5, 2, 4]);"], "clean_up_sql": ["DROP TABLE decks;"], "test_cases": []} {"instance_id": 71, "selected_database": "card_games", "query": "In the context of the card_games database, we have two tables: 'card_prices' and 'order_cards'. The 'card_prices' table records the price of each card at different start dates, and the 'order_cards' table records the cards ordered by customers on specific dates. We need to join these two tables to get the price of each card at the time it was ordered. However, the initial attempt to join the tables resulted in duplicate records for some orders. Here are the tables and the problematic query:\\n\\Table 'card_prices':\\n| start_date | card_id | price |\\n|------------|---------|-------|\\n| 2023-04-01 | 1 | 10.0 |\\n| 2023-04-15 | 1 | 20.0 |\\n| 2023-04-01 | 2 | 20.0 |\\n\\Table 'order_cards':\\n| order_date | order_id | card_id |\\n|------------|----------|---------|\\n| 2023-04-01 | 10001 | 1 |\\n| 2023-04-01 | 10001 | 2 |\\n| 2023-04-02 | 10002 | 1 |\\n| 2023-04-02 | 10002 | 2 |\\n| 2023-04-16 | 10003 | 1 |\\n| 2023-04-16 | 10003 | 2 |\\n\\nThe desired result is:\\n| order_date | order_id | card_id | price |\\n|------------|----------|---------|-------|\\n| 2023-04-01 | 10001 | 1 | 10.0 |\\n| 2023-04-01 | 10001 | 2 | 20.0 |\\n| 2023-04-02 | 10002 | 1 | 10.0 |\\n| 2023-04-02 | 10002 | 2 | 20.0 |\\n| 2023-04-16 | 10003 | 1 | 20.0 |\\n| 2023-04-16 | 10003 | 2 | 20.0 |\\nHowever, the initial attempt resulted in duplicate records for some orders.\\n", "error_sql": ["SELECT ord.order_date, ord.order_id, ord.card_id, prd.price FROM order_cards ord LEFT JOIN (SELECT * FROM card_prices ORDER BY start_date ASC) AS prd ON ord.card_id = prd.card_id AND ord.order_date >= prd.start_date"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE card_prices (start_date DATE, card_id BIGINT, price NUMERIC);", "INSERT INTO card_prices (start_date, card_id, price) VALUES ('2023-04-01', 1, 10.0), ('2023-04-15', 1, 20.0), ('2023-04-01', 2, 20.0);", "CREATE TABLE order_cards (order_date DATE, order_id BIGINT, card_id BIGINT);", "INSERT INTO order_cards (order_date, order_id, card_id) VALUES ('2023-04-01', 10001, 1), ('2023-04-01', 10001, 2), ('2023-04-02', 10002, 1), ('2023-04-02', 10002, 2), ('2023-04-16', 10003, 1), ('2023-04-16', 10003, 2);"], "clean_up_sql": ["DROP TABLE card_prices;", "DROP TABLE order_cards;"], "test_cases": []} {"instance_id": 72, "selected_database": "european_football_2", "query": "In the database 'european_football_2', there is a table named 'player_stats' that records the performance statistics of football players across different matches. Each row in the table represents a player's performance in a specific match. The table has two columns, 'stats_keys' and 'stats_values', which store the performance metrics and their corresponding values as comma-separated strings. For example, 'stats_keys' might contain 'goals,assists,yellow_cards' and 'stats_values' might contain '2,1,0'. The task is to transform this table into a format where each performance metric is a separate column, with the corresponding values filled in for each player's match performance.", "error_sql": ["select player_id, stats_keys, stats_values from player_stats"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE player_stats (player_id INT, stats_keys TEXT, stats_values TEXT);", "INSERT INTO player_stats (player_id, stats_keys, stats_values) VALUES (1, 'goals,assists,yellow_cards', '2,1,0'), (2, 'assists,yellow_cards', '0,1'), (3, 'goals,yellow_cards', '1,0'), (4, 'assists,yellow_cards,red_cards', '2,1,0');"], "clean_up_sql": ["DROP TABLE player_stats;"], "test_cases": []} {"instance_id": 73, "selected_database": "european_football_2", "query": "In the 'european_football_2' database, there is a table named 'teams_config' which holds information about various football teams. Each team has a 'configurations' column of type jsonb that stores an array of objects representing different team settings. Each object in the array has an 'id', 'name', and 'settings'. For example, one row in the 'teams_config' table might have the following 'configurations':\n[\n {\n \"id\": 100, \n \"name\": \"testOne\", \n \"settings\": \"settingOne\" \n },\n {\n \"id\": 101,\n \"name\": \"testTwo\",\n \"settings\": \"settingTwo\"\n },\n]", "error_sql": ["UPDATE teams_config SET configurations = jsonb_set(configurations, '{settings}', (configurations->'id') - (SELECT DISTINCT position - 1 FROM teams_config, jsonb_array_elements(configurations) WITH ORDINALITY arr(elem, position) WHERE elem->>'id' = '101')::int);"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE teams_config (configurations jsonb);", "INSERT INTO teams_config VALUES ('[{\"id\": 100, \"name\": \"testOne\", \"settings\": \"settingOne\"}, {\"id\": 101, \"name\": \"testTwo\", \"settings\": \"settingTwo\"}]');"], "clean_up_sql": ["DROP TABLE teams_config"], "test_cases": []} {"instance_id": 74, "selected_database": "formula_1", "query": "I have a table race_dates which stores the begin_date and end_date of races, e.g. '2022-01-03' and '2022-03-04', is there any neat way to calculate ONLY the completed full calendar months between these dates? Some examples with their requested outputs: '2022-01-03' and '2022-03-04' full calendar months = 1 since only February was a full calendar month between this timespan. '2022-01-01' and '2022-05-30' full calendar months = 4 since May has 31 days total. '2022-01-31' and '2022-05-31' full calendar months = 3 since the month of May is not completed. I tried subtracting the dates but it gives me the days difference between these dates. I also tried the function AGE() but it is based also in the days difference, since it is using days to calculate years months etc.", "error_sql": ["SELECT begin_date, end_date, age(CASE WHEN end_date = date_trunc('month', end_date) + interval '1 month - 1 day' THEN end_date + interval '1 day' ELSE date_trunc('month', end_date) END::date, CASE WHEN begin_date = date_trunc('month', begin_date) THEN begin_date ELSE date_trunc('month', begin_date) + interval '1 month' END::date) AS calculated_months FROM race_dates;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE race_dates (begin_date DATE NOT NULL, end_date DATE NOT NULL)", "INSERT INTO race_dates (begin_date, end_date) VALUES ('2022-01-03', '2022-03-04'), ('2022-01-01', '2022-05-30'), ('2022-01-31', '2022-05-31'), ('2021-11-15', '2022-02-10'), ('2021-12-01', '2022-05-31');"], "clean_up_sql": ["DROP TABLE race_dates"], "test_cases": []} {"instance_id": 75, "selected_database": "student_club", "query": "In the student_club database, I am trying to insert an attendance record that tracks when a member attends an event. The goal is to ensure there are no duplicate entries for the same member (link_to_member) attending the same event (link_to_event). If an attendance record for the member and event already exists, the date column should be updated to reflect the most recent attendance timestamp. If no such record exists, a new record should be created. I have tried using the ON CONFLICT clause with a WHERE condition to achieve this, but it doesn't seem to work.\nHere is one of the many permutations I've tried:\n\nsql\nINSERT INTO new_attendance (link_to_event, link_to_member, date) \nVALUES ('reciRZdAqNIKuMC96', 'recL94zpn6Xh6kQii', NOW()) \nON CONFLICT \n WHERE link_to_member='recL94zpn6Xh6kQii' DO NOTHING\n\n\nThe link_to_member column does not have any constraints, so the simpler syntax:\n\nsql\nON CONFLICT (link_to_member) DO NOTHING\n\n\nthrows database errors. My hope is this is a simple syntax issue.", "error_sql": ["\n INSERT INTO new_attendance (link_to_event, link_to_member, date)\n VALUES ('reciRZdAqNIKuMC96', 'recL94zpn6Xh6kQii', NOW())\n ON CONFLICT\n WHERE link_to_member='recL94zpn6Xh6kQii' DO NOTHING;\n "], "sol_sql": [], "preprocess_sql": ["\n DROP TABLE IF EXISTS new_attendance;\n ", "\n CREATE TABLE new_attendance AS\n SELECT DISTINCT link_to_event, link_to_member, NOW() AS date\n FROM attendance;\n ", "\n ALTER TABLE new_attendance\n ADD CONSTRAINT unique_event_member UNIQUE (link_to_event, link_to_member);\n "], "clean_up_sql": [], "test_cases": []} {"instance_id": 76, "selected_database": "financial", "query": "I'm migrating from Oracle to PostgreSQL. In Oracle, I used the following call to acquire a lock with a timeout: `lkstat := DBMS_LOCK.REQUEST(lkhndl, DBMS_LOCK.X_MODE, lktimeout, true);`. This function tries to acquire the lock `lkhndl` and returns 1 if it fails to get it after `lktimeout` seconds. In PostgreSQL, I tried using `pg_advisory_xact_lock(lkhndl);`, but it seems to wait indefinitely for the lock. I need a way to implement a timeout version of lock acquiring in PostgreSQL named pg_try_advisory_lock_with_timeout. The function pg_try_advisory_lock_with_timeout(key bigint) is designed to attempt to acquire a PostgreSQL advisory lock with a timeout of 1 second. If the lock is unavailable due to contention or deadlock detection, it will return false instead of waiting indefinitely.", "error_sql": ["\n pg_advisory_xact_lock(lkhndl);\n "], "sol_sql": [], "preprocess_sql": ["\n DROP FUNCTION IF EXISTS pg_try_advisory_lock_with_timeout(bigint);\n "], "clean_up_sql": [], "test_cases": []} {"instance_id": 77, "selected_database": "student_club", "query": "I'm trying to rank club members based on the hours they have attented for events, rounded to the nearest 10. I need to produce a descending ranking of members by total hours attened, including a column with the rank using the `RANK()` window function, and sort the result by the rank. However, my rounding logic seems to be incorrect, as it produces different results compared to the expected output.", "error_sql": ["\n SELECT\n link_to_member,\n CASE\n WHEN (SUBSTRING(ROUND(SUM(hours)::NUMERIC, 0)::TEXT FROM '.{1}$') IN ('5', '6', '7', '8', '9', '0')) \n THEN CEIL(SUM(hours) / 10) * 10\n ELSE FLOOR(SUM(hours) / 10) * 10\n END AS rounded_hours,\n RANK() OVER (ORDER BY \n CASE\n WHEN (SUBSTRING(ROUND(SUM(hours)::NUMERIC, 0)::TEXT FROM '.{1}$') IN ('5', '6', '7', '8', '9', '0')) \n THEN CEIL(SUM(hours) / 10) * 10\n ELSE FLOOR(SUM(hours) / 10) * 10\n END DESC\n ) AS rank\n FROM attendance\n GROUP BY link_to_member\n ORDER BY rank, link_to_member; \n "], "sol_sql": [], "preprocess_sql": ["\n ALTER TABLE attendance\n ADD COLUMN hours NUMERIC;\n ", "\n TRUNCATE TABLE attendance;\n ", "\n INSERT INTO attendance (link_to_event, link_to_member, hours)\n VALUES \n ('event_1', 'member_1', 64.5),\n ('event_2', 'member_1', 60.0),\n ('event_2', 'member_2', 210.5),\n ('event_3', 'member_3', 237.6);\n "], "clean_up_sql": [], "test_cases": []} {"instance_id": 78, "selected_database": "financial", "query": "I need to create an index named ix_account on the 'account' table for the columns 'district_id', 'frequency', and 'date'. I want to ensure that the index does not already exist before attempting to create it. How can I check for the existence of this index? Return True if the index exists. Otherwise return False.", "error_sql": ["\n CREATE INDEX ix_account ON account USING btree (district_id, frequency, date); \n "], "sol_sql": [], "preprocess_sql": ["\n CREATE INDEX ix_account ON account USING btree (district_id, frequency, date); \n "], "clean_up_sql": [], "test_cases": []} {"instance_id": 79, "selected_database": "european_football_2", "query": "I am trying to create a view that counts the records where home team goal is 2 in a specific season. I have a function `findteam(text)` that returns a float representing the count for a given season. However, when I try to use this function in my view, I encounter an error stating 'cannot change data type of view column `team_count` from integer to double precision'. I am new to SQL and do not understand why this is happening or how to fix it.", "error_sql": ["\n create or replace view findcount(season, team_count) as\n select\n season,\n findteam(season) as team_count\n from (\n select distinct season\n from match\n where season >= '2008/2009' \n ) seasons;\n "], "sol_sql": [], "preprocess_sql": ["\n DROP VIEW IF EXISTS findcount;\n DROP FUNCTION IF EXISTS findteam;\n ", "\n create or replace function findteam(text) returns float as $$\n select cast(count(*) as float)\n from match m\n where m.home_team_goal = 2 and m.season = $1;\n $$ language sql;\n ", "\n CREATE VIEW findcount AS\n SELECT season, CAST(10 AS INTEGER) AS team_count\n from (\n select distinct season\n from match\n where season >= '2008/2009' \n ) seasons;\n "], "clean_up_sql": [], "test_cases": []} {"instance_id": 80, "selected_database": "codebase_community", "query": "In the context of the 'codebase_community' database, a user has a table named 'posts' containing various posts made by users. Each post has a 'tags' column that lists the tags associated with the post. Specifically, the user is interested in identifying the number of posts that include the keywords 'bayesian' or 'distributions' for each post type. The user attempted to implement this in PostgreSQL but encountered errors in his SQL query.", "error_sql": ["\n select posttypeid\n case when tags like ('%bayesian%','%distributions%') \n then 1 else 0 end as keyword_count\n from posts\n "], "sol_sql": [], "preprocess_sql": ["\n ALTER TABLE posts RENAME TO posts_backup;\n ", "\n CREATE TABLE posts (\n id INT PRIMARY KEY,\n posttypeid INT,\n tags TEXT\n );\n ", "\n INSERT INTO posts (id, posttypeid, tags)\n VALUES \n (1, 1, ''),\n (2, 1, ''),\n (3, 1, ''),\n (4, 2, ''),\n (5, 2, '');\n ", "\n DROP TABLE IF EXISTS posts_backup;\n "], "clean_up_sql": [], "test_cases": []} {"instance_id": 81, "selected_database": "debit_card_specializing", "query": "I have a table of transactions for multiple customers, where each transaction has a unique transaction id, along with amount, type, and transaction record. Some transactions for a single customerid share the same combination of these attributes. I want to update a first_transaction column with the transaction of the earliest transaction for each unique combination of attributes within each customer. My current method uses a LATERAL JOIN but is extremely slow on my small server. I process one customer at a time and commit after each iteration, but the query remains inefficient. How can I optimize this process?", "error_sql": ["SELECT a.customerid, a.transaction, (SELECT b.transaction FROM transaction_info b WHERE b.customerid = a.customerid AND b.amount = a.amount AND b.type = a.type ORDER BY b.transaction LIMIT 1) AS first_transaction, a.amount, a.type, a.transactionid FROM transaction_info a ORDER BY a.customerid, a.transaction"], "sol_sql": [], "preprocess_sql": ["\nCREATE TABLE transaction_info (\n customerid int,\n transaction int,\n first_transaction varchar(10),\n amount numeric,\n type numeric,\n transactionid text\n);\nINSERT INTO transaction_info (customerid, transaction, first_transaction, amount, type, transactionid) VALUES\n(1, 1, 'na', 65250.78, 700000.52, '01010000206A0000000000F0C02E458A4400000000F03F'),\n(1, 2, 'na', 65250.78, 700000.52, '01010000206A0000000000F0C02E458A4400000000F03F'),\n(1, 3, 'na', 65250.78, 700000.52, '01010000206A0000000000F0C02E458A4400000000F03F'),\n(1, 4, 'na', 65999.00, 700555.00, '01010000455A000000000010C03F478A4400000010F03F'),\n(1, 5, 'na', 65999.00, 700555.00, '01010000455A000000000010C03F478A4400000010F03F'),\n(1, 6, 'na', 65999.00, 700555.00, '01010000455A000000000010C03F478A4400000010F03F'); \n"], "clean_up_sql": ["\nDROP TABLE test;\n"], "test_cases": [], "efficiency": true} {"instance_id": 82, "selected_database": "toxicology", "query": "In the toxicology database, I have two tables, 'bond' and 'molecule'. The 'bond' table contains information about bonds within molecules, including a foreign key 'molecule_id' that references the 'molecule' table. I need to construct a query that select count(*), molecule_id, most recent update timestamp grouping the bonds by 'molecule_id' and sorts the results based on molecule_id and the most recent bond entry (assuming we have a timestamp column added to the 'bond' table for this purpose). However, I've tried the following query and it doesn't work as expected:", "error_sql": ["SELECT count(bond_id), molecule_id FROM bond GROUP BY molecule_id ORDER BY molecule_id last_update DESC;"], "sol_sql": [], "preprocess_sql": ["ALTER TABLE bond ADD COLUMN last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP;"], "clean_up_sql": ["ALTER TABLE bond DROP COLUMN last_update;"], "test_cases": []} {"instance_id": 83, "selected_database": "european_football_2", "query": "In the context of the 'european_football_2' database, we have a table that logs changes to player statistics over time. Each row in the 'player_stats_changes' table represents a change to a specific player's attribute (such as height or weight) at a particular timestamp. We want to generate a cumulative view of these changes, where each row shows the player's current height and weight at each timestamp, filling in any missing values with the most recent known value.", "error_sql": ["SELECT entity_id, coalesce(change->'height', lag(change->'height', 1, null) over (partition by entity_id order by updated_at)) as height, coalesce(change->'weight', lag(change->'weight', 1, null) over (partition by entity_id order by updated_at)) as weight, updated_at FROM ( SELECT entity_id, json_object_agg(column_id, value) as change, updated_at FROM player_stats_changes GROUP BY entity_id, updated_at) as changes;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE IF NOT EXISTS player_stats_changes ( entity_id TEXT NOT NULL, column_id TEXT NOT NULL, value JSONB NOT NULL, updated_at TIMESTAMP NOT NULL );", "INSERT INTO player_stats_changes VALUES ('1', 'height', to_jsonb(140), '01-01-2021 00:00:00'::TIMESTAMP), ('1', 'weight', to_jsonb(30), '01-01-2021 00:00:00'::TIMESTAMP), ('1', 'height', to_jsonb(145), '01-02-2021 00:00:00'::TIMESTAMP), ('1', 'weight', to_jsonb(34), '01-03-2021 00:00:00'::TIMESTAMP);"], "clean_up_sql": ["DROP TABLE IF EXISTS player_stats_changes;"], "test_cases": []} {"instance_id": 84, "selected_database": "superhero", "query": "In the superhero database, I have two separate queries (q1, q2) joining across multiple tables assigning the same superheroes to different groups (I call these subgroups) based on different criteria. I get query result 1 and 2 (qr1, qr2). An item might appear in one or both, but within a result it is unique. I want to assign a new group id based on both subgroups and assigning the same group id if the subgroups share one or more items.", "error_sql": ["with qr1(item, subgroup) AS (SELECT id, subgroup1 FROM superhero_group WHERE subgroup1 IS NOT NULL), qr2(item, subgroup) AS (SELECT id, subgroup2 FROM superhero_group WHERE subgroup2 IS NOT NULL) select item, subgroup1, subgroup2, dense_rank() over (order by item) as group from (select qr1.item, qr1.subgroup as subgroup1, qr2.subgroup as subgroup2 from qr1 full outer join qr2 on qr1.item = qr2.item) as combined"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE superhero_group (id INTEGER PRIMARY KEY, subgroup1 INTEGER, subgroup2 INTEGER)", "INSERT INTO superhero_group VALUES (1,1,5), (2,1,null), (3,2,null), (4,3,null), (5,3,6), (6,4,6), (7,null,7), (8,null,5), (10,null,5)"], "clean_up_sql": [], "test_cases": []} {"instance_id": 85, "selected_database": "superhero", "query": "In the superhero database, a user is allowed to view details of a superhero if their user_id matches the superhero's publisher_id or if there is an entry in the 'hero_access' table where their user_id is in the 'read_acl' column (array using gin index). Both tables have about 2 million rows. The query is slow, especially when using an OR clause. Is there a way that improves the performance significantly?", "error_sql": ["select * from superhero where publisher_id = 1 or exists (select * from hero_access f where superhero.id = f.superhero_id and '{1}' && read_acl) order by superhero.id limit 10;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE hero_access (superhero_id bigint, read_acl text[]);", "CREATE INDEX idx_hero_access_read_acl ON hero_access USING gin (read_acl);", "INSERT INTO hero_access (superhero_id, read_acl) SELECT id, ARRAY['1'] FROM superhero ORDER BY random() LIMIT 10;"], "clean_up_sql": ["DROP TABLE hero_access;"], "test_cases": [], "efficiency": true} {"instance_id": 86, "selected_database": "superhero", "query": "I have two tables and I want to merge them. Table utm is a source-main table and table report contains data for utm rows. What I need: Take id and utm_ from utm table and add stats from table report with proper granulation. In table utm I've a row: (24611609, 'myTarget', 'Media', 'Social', NULL, NULL) and in table report I've 2 rows: \n(24611609, '2022-08-01', 200, 150, 15, 'myTarget', 'Media', 'Social', 'premium', 'subcribe'),\n(24611609, '2022-08-01', 25, 10, 1, 'myTarget', 'Media', 'Social', 'free', 'subcribe')\n Common is: 'myTarget', 'Media', 'Social'.\nProper granularity level is id, utm_campaign, utm_source, utm_medium, so I need to SUM and GROUP two rows by these keys. I don't know how to deal with all possible granularity combinations. My idea was just use diffrent JOINS variations and merge results with UNION. But it's really stupid, I should create > 1000 unions and joins. Any tips?", "error_sql": ["WITH r AS (SELECT id, date_of_visit, SUM(sessions) AS sessions, SUM(pageviews) AS pageviews, SUM(bounces) AS bounce, COALESCE(utm_campaign, '') AS utm_campaign, COALESCE(utm_source, '') AS utm_source, COALESCE(utm_medium, '') AS utm_medium, COALESCE(utm_content, '') AS utm_content, COALESCE(utm_term, '') AS utm_term FROM report GROUP BY id, date_of_visit, utm_campaign, utm_source, utm_medium, utm_content, utm_term UNION SELECT id, date_of_visit, SUM(sessions), SUM(pageviews), SUM(bounces), COALESCE(utm_campaign, ''), COALESCE(utm_source, ''), '' AS utm_medium, '' AS utm_content, '' AS utm_term FROM report GROUP BY id, date_of_visit, utm_campaign, utm_source UNION SELECT id, date_of_visit, SUM(sessions), SUM(pageviews), SUM(bounces), COALESCE(utm_campaign, ''), '' AS utm_source, COALESCE(utm_medium, ''), '' AS utm_content, '' AS utm_term FROM report GROUP BY id, date_of_visit, utm_campaign, utm_medium UNION SELECT id, date_of_visit, SUM(sessions), SUM(pageviews), SUM(bounces), COALESCE(utm_campaign, ''), '' AS utm_source, '' AS utm_medium, COALESCE(utm_content, ''), '' AS utm_term FROM report GROUP BY id, date_of_visit, utm_campaign, utm_content UNION SELECT id, date_of_visit, SUM(sessions), SUM(pageviews), SUM(bounces), COALESCE(utm_campaign, ''), '' AS utm_source, '' AS utm_medium, '' AS utm_content, COALESCE(utm_term, '') FROM report GROUP BY id, date_of_visit, utm_campaign, utm_term UNION SELECT id, date_of_visit, SUM(sessions), SUM(pageviews), SUM(bounces), '' AS utm_campaign, COALESCE(utm_source, ''), COALESCE(utm_medium, ''), '' AS utm_content, '' AS utm_term FROM report GROUP BY id, date_of_visit, utm_source, utm_medium UNION SELECT id, date_of_visit, SUM(sessions), SUM(pageviews), SUM(bounces), '' AS utm_campaign, COALESCE(utm_source, ''), '' AS utm_medium, COALESCE(utm_content, ''), '' AS utm_term FROM report GROUP BY id, date_of_visit, utm_source, utm_content UNION SELECT id, date_of_visit, SUM(sessions), SUM(pageviews), SUM(bounces), '' AS utm_campaign, COALESCE(utm_source, ''), '' AS utm_medium, '' AS utm_content, COALESCE(utm_term, '') FROM report GROUP BY id, date_of_visit, utm_source, utm_term UNION SELECT id, date_of_visit, SUM(sessions), SUM(pageviews), SUM(bounces), '' AS utm_campaign, '' AS utm_source, COALESCE(utm_medium, ''), COALESCE(utm_content, ''), '' AS utm_term FROM report GROUP BY id, date_of_visit, utm_medium, utm_content UNION SELECT id, date_of_visit, SUM(sessions), SUM(pageviews), SUM(bounces), '' AS utm_campaign, '' AS utm_source, COALESCE(utm_medium, ''), '' AS utm_content, COALESCE(utm_term, '') FROM report GROUP BY id, date_of_visit, utm_medium, utm_term UNION SELECT id, date_of_visit, SUM(sessions), SUM(pageviews), SUM(bounces), '' AS utm_campaign, '' AS utm_source, '' AS utm_medium, COALESCE(utm_content, ''), COALESCE(utm_term, '') FROM report GROUP BY id, date_of_visit, utm_content, utm_term UNION SELECT id, date_of_visit, SUM(sessions), SUM(pageviews), SUM(bounces), '' AS utm_campaign, '' AS utm_source, '' AS utm_medium, '' AS utm_content, '' AS utm_term FROM report GROUP BY id, date_of_visit) SELECT r.* FROM r JOIN utm AS u ON r.id = u.row_id AND (r.utm_campaign = u.utm_campaign OR (r.utm_campaign = '' AND u.utm_campaign IS NULL)) AND (r.utm_source = u.utm_source OR (r.utm_source = '' AND u.utm_source IS NULL)) AND (r.utm_medium = u.utm_medium OR (r.utm_medium = '' AND u.utm_medium IS NULL)) AND (r.utm_content = u.utm_content OR (r.utm_content = '' AND u.utm_content IS NULL)) AND (r.utm_term = u.utm_term OR (r.utm_term = '' AND u.utm_term IS NULL)) WHERE 'NA' NOT IN (r.utm_campaign, r.utm_source, r.utm_medium, r.utm_content, r.utm_term);"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE utm (row_id int8 NOT NULL, utm_campaign text NULL, utm_source text NULL, utm_medium text NULL, utm_content text NULL, utm_term text NULL);", "INSERT INTO utm (row_id, utm_campaign, utm_source, utm_medium, utm_content, utm_term) VALUES (24611609, 'myTarget', 'Media', 'Social', NULL, NULL), (28573041, 'shop_ smartfony', 'my_beeline', 'banner', NULL, NULL), (28573041, 'Beeline_uppers_2022', NULL, NULL, NULL, NULL), (24611609, 'campaign', 'source', 'medium', 'content', 'term');", "CREATE TABLE report (id int8 NOT NULL, date_of_visit date NOT NULL, sessions numeric NULL, pageviews numeric NULL, bounces numeric NULL, utm_campaign text NULL, utm_source text NULL, utm_medium text NULL, utm_content text NULL, utm_term text NULL);", "INSERT INTO report (id, date_of_visit, sessions, pageviews, bounces, utm_campaign, utm_source, utm_medium, utm_content, utm_term) VALUES (24611609, '2022-08-01', 200, 150, 15, 'myTarget', 'Media', 'Social', 'premium', 'subcribe'), (24611609, '2022-08-01', 25, 10, 1, 'myTarget', 'Media', 'Social', 'free', 'subcribe'), (28573041, '2022-08-01', 900, 885, 34, 'shop_ smartfony', 'my_beeline', 'banner', NULL, NULL), (28573041, '2022-08-01', 1000, 900, 10, 'Beeline_uppers_2022', NULL, NULL, NULL, NULL), (21781121, '2022-08-01', 500, 50, 5, 'vodafone', 'google', NULL, NULL, NULL), (21781121, '2022-08-01', 55, 50, 3, 'vodafone', 'google', 'youtube', NULL, NULL), (24611609, '2022-08-01', 1, 1, 0, 'campaign', 'source', 'medium', 'content', 'term');"], "clean_up_sql": ["DROP TABLE utm;", "DROP TABLE report"], "test_cases": []} {"instance_id": 87, "selected_database": "card_games", "query": "I have a local PostgreSQL database named card_games, with a table called cards that contains many columns. One of these columns is named text, which stores details about each card's abilities or effects. Sometimes, the text field contains one or more curly-brace expressions indicating costs or actions. For example:\n\"{{T}}: Target creature gains haste until end of turn.\"\n\"{{1}}{{W}}: Prevent the next 2 damage that would be dealt to any target.\"\n\"{{2}}{{U}}{{U}}: Draw two cards, then discard a card.\"\n\"Flying (This creature can't be blocked except by creatures with flying or reach) {{G}}{{1}}\"\n\nI want to extract all the bracketed tokens (i.e., everything in {{...}}) from the text field, potentially returning them in a separate column or combining them into a list. Additionally, some rows may contain multiple occurrences of these curly-brace expressions, separated by normal text.\n\nHow can I write a SQL query (using PostgreSQL features like regexp_matches, substring, or similar) to:\n\t1.\tFind all bracketed tokens within each row's text column,\n\t2.\tReturn them in a format where I can see each token (e.g., {{T}}, {{1}}{{W}}, etc.) separately or as an array,\n\t3.\tHandle rows that have multiple bracketed tokens or none at all,\n\t4.\tOptionally count how many curly-brace expressions appear per row?\n\nI'm specifically looking for a solution that runs purely in SQL (e.g. using regexp_replace, regexp_matches, or other built-in PostgreSQL string functions). How should I structure my query to achieve this? Are there any caveats with capturing multiple matches from the same row in PostgreSQL?", "error_sql": ["SELECT\n id,\n text,\n REGEXP_MATCHES(\n text,\n '\\{.*?\\}',\n 'g'\n ) AS bracketed_tokens\nFROM cards;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 88, "selected_database": "superhero", "query": "I am porting the queries from InfluxDB to TimescaleDB (PostgreSQL). I am currently stuck with the equivalent of InfluxDB's TOP and BOTTOM functions. Specifically, I need to find the top 5 and bottom 5 races within each gender_id group, ranked by the number of superheroes. If multiple races have the same count, they should share the same rank. In InfluxDB, I would use TOP(count(race_id), 5) in each group with the same gender_id. How can I achieve this in PostgreSQL?", "error_sql": ["SELECT race_id, top(count(*), 5) as cnt FROM superhero group by gender_id"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 89, "selected_database": "card_games", "query": "I have this SQL query to get the top 3 rulings for each uuid in the given list: 6d268c95-c176-5766-9a46-c14f739aba1c, 56f4935b-f6c5-59b9-88bf-9bcce20247ce, 8dfc67e9-8323-5d1f-9e25-9f9394abd5a0, 5ac794d2-4c66-5332-afb1-54b24bc11823, 60f49caf-3583-5f85-b4b3-08dca73a8628, ranked by the number of rulings. However, my current query is not working correctly and is not returning the expected results.", "error_sql": ["SELECT rulings.id, rulings.date, rulings.text, rulings.uuid FROM rulings WHERE rulings.uuid IN ('6d268c95-c176-5766-9a46-c14f739aba1c', '56f4935b-f6c5-59b9-88bf-9bcce20247ce', '8dfc67e9-8323-5d1f-9e25-9f9394abd5a0', '5ac794d2-4c66-5332-afb1-54b24bc11823', '60f49caf-3583-5f85-b4b3-08dca73a8628') GROUP BY rulings.id ORDER BY rulings.id LIMIT 3"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 90, "selected_database": "formula_1", "query": "I am analyzing Formula 1 race data to rank drivers based on their total points across multiple races. Each driver earns points for their position in each race. I want to retain the discrete race scoring while also ranking the drivers in the series. For example, considering a sub-query that returns this:\\n| Driver ID | Driver Name | Total Points | Race Points | Race ID |\\n| --------- | ----------- | ------------ | ----------- | ------- |\\n| 1 | Lewis | 50 | 10 | 101 |\\n| 1 | Lewis | 50 | 20 | 102 |\\n| 1 | Lewis | 50 | 20 | 103 |\\n| 2 | Nico | 40 | 20 | 101 |\\n| 2 | Nico | 40 | 20 | 102 |\\nYou can see Lewis has 50 points, as he won 10, 20, and 20 points in three races. Nico has 40 points, as he won 20 and 20 points in two races.\\nNow for the ranking, what I'd like is:\\n| Place | Driver ID | Driver Name | Total Points | Race Points | Race ID |\\n| --------- | --------- | ----------- | ------------ | ----------- | ------- |\\n| 1 | 1 | Lewis | 50 | 10 | 101 |\\n| 1 | 1 | Lewis | 50 | 20 | 102 |\\n| 1 | 1 | Lewis | 50 | 20 | 103 |\\n| 2 | 2 | Nico | 40 | 20 | 101 |\\n| 2 | 2 | Nico | 40 | 20 | 102 |\\nBut if I use `rank()` and `order by Total Points`, I get:\\n| Place | Driver ID | Driver Name | Total Points | Race Points | Race ID |\\n| --------- | --------- | ----------- | ------------ | ----------- | ------- |\\n| 1 | 1 | Lewis | 50 | 10 | 101 |\\n| 1 | 1 | Lewis | 50 | 20 | 102 |\\n| 1 | 1 | Lewis | 50 | 20 | 103 |\\n| 4 | 2 | Nico | 40 | 20 | 101 |\\n| 4 | 2 | Nico | 40 | 20 | 102 |\\nWhich makes sense, since there are three 'ties' at 50 points.\\n`dense_rank()` solves this problem, but if there are legitimate ties across different drivers, I want there to be gaps in the rank (e.g if Lewis and Nico both had 50 points, they are both the first place and the next driver would be in third place, no second).\\nThe easiest way to solve this I think would be to issue two queries, one with the 'duplicate' drivers eliminated, and then a second one where I can retain the individual race data, which I need for the points break down display.\\nI can also probably, given enough effort, think of a way to do this in a single query, but I'm wondering if I'm not just missing something really obvious that could accomplish this in a single, relatively simple query.\\nAny suggestions?", "error_sql": ["select rank() over (order by total_points desc) as place, id, name, total_points, race_points, raceId from racers"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE racers (id integer, name text, total_points integer, race_points integer, raceId integer);", "INSERT INTO racers (id, name, total_points, race_points, raceId) VALUES (1, 'Lewis', 50, 10, 123), (1, 'Lewis', 50, 20, 234), (1, 'Lewis', 50, 20, 345), (2, 'Nico', 40, 20, 123), (2, 'Nico', 40, 20, 234), (3, 'Dave', 50, 30, 123), (3, 'Dave', 50, 20, 234);"], "clean_up_sql": ["DROP TABLE racers;"], "test_cases": []} {"instance_id": 91, "selected_database": "california_schools", "query": "In the context of the 'california_schools' database, we have three tables: 'schools', 'satscores', and 'frpm'. The 'schools' table contains detailed information about each school, the 'satscores' table contains SAT scores for each school, and the 'frpm' table contains information about the free and reduced-price meal eligibility for each school. We want to determine for each school in the 'satscores' table, whether there is any corresponding entry in the 'frpm' table for the same school. The user has written a query that checks for the existence of such entries but believes it is inefficient as it traverses the 'frpm' table twice. Is there a better way?", "error_sql": ["SELECT s.cds, true FROM satscores s WHERE EXISTS (SELECT 1 FROM frpm f WHERE s.cds = f.cdscode) UNION SELECT s.cds, false FROM satscores s WHERE NOT EXISTS (SELECT 1 FROM frpm f WHERE s.cds = f.cdscode) ORDER BY cds"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": [], "efficiency": true} {"instance_id": 92, "selected_database": "card_games", "query": "In the card_games database, we have a table named 'orders' that records the purchase history of customers. Each entry in the 'orders' table includes the month and year of the purchase, the order ID, and the customer ID. We want to analyze the purchase behavior of our customers to identify repeat customers. A repeat customer is defined as a customer who has made at least one purchase in the past and makes another purchase in a subsequent month. We aim to count the number of repeat customers per month. For example, if a customer made their first purchase in January 2022, then any purchase they make in February 2022 or later should be counted as a repeat purchase in that respective month. The user attempted to write a query to count repeat customers but encountered issues with the query logic, which only counted customers who made more than one purchase in the same month rather than those who made a purchase in a subsequent month after their first purchase.", "error_sql": ["SELECT month_year, COUNT(DISTINCT customer_id) FROM orders GROUP BY month_year HAVING COUNT(order_id) > 1"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE orders (month_year text, order_id text, customer_id bigint);", "INSERT INTO orders (month_year, order_id, customer_id) VALUES ('2016-04', '0001', 24662), ('2016-05', '0002', 24662), ('2016-05', '0002', 24662), ('2016-07', '0003', 24662), ('2016-07', '0003', 24662), ('2016-07', '0004', 24662), ('2016-07', '0004', 24662), ('2016-08', '0005', 24662), ('2016-08', '0006', 24662), ('2016-08', '0007', 24662), ('2016-08', '0008', 24662), ('2016-08', '0009', 24662), ('2016-08', '0010', 11372), ('2016-08', '0011', 11372), ('2016-09', '0012', 24662), ('2016-10', '0013', 24662), ('2016-10', '0014', 11372), ('2016-11', '0015', 24662), ('2016-11', '0016', 11372), ('2016-12', '0017', 11372), ('2017-01', '0018', 11372), ('2017-01', '0019', 11372);"], "clean_up_sql": ["DROP TABLE orders;"], "test_cases": []} {"instance_id": 93, "selected_database": "european_football_2", "query": "In the database european_football_2, there is a table named player_movements that records the movements of football players joining and leaving teams. Each row in the table includes the player's name, the event (either 'Join' or 'Leave'), and the timestamp of the event. The goal is to transform this data into a format that shows the periods during which each player was part of a team. Specifically, we want to create a table that lists each player, the date they joined a team, and the date they left the team. This will allow us to easily query the data to determine if a player was part of a team on a specific date. For example, we should be able to find out if Player A was on Team X on a given date by using a query like: SELECT * FROM transformed_table WHERE player_name = 'Player A' AND '2022-01-01' BETWEEN joined_date AND left_date. However, the user attempted to write a query that did not produce the desired results.", "error_sql": ["SELECT player_name, event_date as join_date, (SELECT event_date FROM player_movements pm1 WHERE pm1.player_name = pm.player_name AND pm1.event = 'Leave' AND pm1.event_date > pm.event_date) as leave_date FROM player_movements pm WHERE event = 'Join'"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE player_movements (player_name VARCHAR(100), event VARCHAR(10), event_date DATE);", "INSERT INTO player_movements (player_name, event, event_date) VALUES ('Player A', 'Join', '2022-01-01'), ('Player A', 'Leave', '2022-01-02'), ('Player A', 'Join', '2022-01-31'), ('Player A', 'Leave', '2022-02-01'), ('Player B', 'Join', '2022-01-31'), ('Player B', 'Leave', '2022-02-01');"], "clean_up_sql": ["DROP TABLE player_movements;"], "test_cases": []} {"instance_id": 94, "selected_database": "european_football_2", "query": "We have a table named 'player_attributes' that records various performance metrics for players. Each record includes the following metrics: gk_diving, gk_handling, gk_kicking, gk_positioning, gk_reflexes. For example, if a player has gk_diving = 6, gk_handling = 10, gk_kicking = 11, gk_positioning = 8, gk_reflexes = 8, the average after removing the highest (11) and lowest (6) amounts would be (8 + 8 + 10) / 3 = 8.6667. The following is the method I use. It is very bloated and the execution time is too long. Is there a neat way to achieve my needs?", "error_sql": ["SELECT id, (SUM(gk) - MAX(gk) - MIN(gk)) / (COUNT(gk) - 2) AS adjusted_average FROM (SELECT id, gk_diving AS gk FROM player_attributes UNION ALL SELECT id, gk_handling AS gk FROM player_attributes UNION ALL SELECT id, gk_kicking AS gk FROM player_attributes UNION ALL SELECT id, gk_positioning AS gk FROM player_attributes UNION ALL SELECT id, gk_reflexes AS gk FROM player_attributes) subquery GROUP BY id ORDER BY id;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": [], "efficiency": true} {"instance_id": 95, "selected_database": "financial", "query": "In the financial database, there is a table named 'trans' which records all transactions made by clients. Each transaction has a unique transaction ID, the account ID associated with the transaction, the date of the transaction, the type of transaction (credit or debit), the operation performed, the amount involved, the balance after the transaction, and additional details such as the bank and account of the partner. The table has more than 1000000 rows and is growing rapidly. I need to extract the most recent transaction (based on the transaction date) for each account ID. I also tried to avoid using a subquery but did not notice a significant difference. Any idea how I could optimize this query?", "error_sql": ["DROP INDEX IF EXISTS idx_a;", "SELECT DISTINCT ON (t.account_id) t.trans_id, t.account_id, t.date, t.type, t.amount, t.balance FROM trans t ORDER BY t.account_id, t.date DESC, trans_id;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": ["DROP INDEX IF EXISTS idx_a;"], "test_cases": [], "efficiency": true} {"instance_id": 96, "selected_database": "financial", "query": "A financial analyst is tasked with analyzing transaction data to summarize daily financial activities for each client. They need to calculate the total amount of transactions, total balance changes, and the number of transactions for each client, partitioned by date. The analyst writes a query using the same window function with the same partition definition for multiple result columns but encounters redundancy. The use wants to use one PARTITION definition for multiple window function calls.", "error_sql": ["\n select account_id, date, \n sum(amount) OVER (PARTITION BY account_id, date) as total_amount, \n sum(balance) OVER (PARTITION BY account_id, date) as total_balance, \n count(trans_id) OVER (PARTITION BY account_id, date) as total_transactions\n from trans \n "], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 97, "selected_database": "debit_card_specializing", "query": "I need to retrieve transactions from the `transactions_1k` table based on a lexicographic ordering on multiple columns, where the direction of the sort on some columns is reversed. Specifically, I want to find transactions that occurred before a certain date, or on the same date but after a certain time, or on the same date and time but with a transaction amount less than a specified value. For example, I want to find transactions that occurred before '2012-08-24', or on '2012-08-24' but after '10:00:00', or on '2012-08-24' at '10:00:00' but with an amount less than 20. Is there a straightforward way to do this using tuples or a similar approach in PostgreSQL? Note that I cannot rely on tricks that apply only to integers, as some columns are of type date and text.", "error_sql": ["\n SELECT * FROM transactions_1k WHERE (Date, Time, Amount) < ('2012-08-24', '10:00:00', 20);\n "], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 98, "selected_database": "financial", "query": "A financial analyst is trying to generate a report that includes the client's name, the loan details, and the account details for loans that were issued in the year 1996. The analyst has written a query to join the `client`, `disp`, `account`, and `loan` tables. However, the query is failing with an error related to a missing FROM-clause entry. The analyst needs to retrieve the client's name, loan amount, loan duration, and account creation date for loans issued in 1996.", "error_sql": ["\n SELECT client.gender, loan.amount, loan.duration, account.date FROM loan JOIN account ON loan.account_id = account.account_id JOIN client ON disp.client_id = client.client_id JOIN disp ON account.account_id = disp.account_id WHERE loan.date BETWEEN '1996-01-01' AND '1996-12-31';\n "], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 99, "selected_database": "codebase_community", "query": "We are analyzing user engagement with posts on a community forum. Specifically, we want to determine if a user's view of a post had a significant impact based on the duration of the view and the percentage of the post viewed. The 'has_impact' field should be set to true if the difference between the view end time and the view start time is greater than 3 seconds and the view percentage is greater than 0.8, otherwise it should be false. We have a table 'view_logs' that logs each view event with the session_id, post_id, timestamp (ts), event_name (either 'view_start' or 'view_end'), and view percentage (view_perc). We need to populate the 'has_impact' field based on these criteria.", "error_sql": ["with cte as (select pv1.session_id, pv1.post_id, pv2.view_perc, pv1.ts as start_time, min(pv2.ts) as end_time from view_logs pv1 join view_logs pv2 on pv1.session_id = pv2.session_id and pv1.post_id = pv2.post_id and pv1.event_name <> pv2.event_name and pv1.ts < pv2.ts group by pv1.session_id, pv1.post_id, pv2.view_perc, pv1.ts) select session_id, post_id, start_time, end_time, case when (end_time - start_time > 3 and view_perc > 0.8 )then 'yes' else 'no' end as has_meaningful_view from cte;"], "sol_sql": [], "preprocess_sql": ["create table view_logs (session_id varchar(10), post_id int, ts int, event_name varchar(50), view_perc float);", "insert into view_logs(session_id, post_id, ts, event_name, view_perc) values ('m1', 1000, 1524600, 'view_start', null), ('m1', 1000, 1524602, 'view_end', 0.85), ('m1', 1000, 1524650, 'view_start', null), ('m1', 1000, 1524654, 'view_end', 0.9), ('m1', 2000, 1524700, 'view_start', null), ('m1', 2000, 1524707, 'view_end', 0.3), ('m1', 2000, 1524710, 'view_start', null), ('m1', 2000, 1524713, 'view_end', 0.9);"], "clean_up_sql": ["DROP TABLE IF EXISTS view_logs;"], "test_cases": []} {"instance_id": 100, "selected_database": "superhero", "query": "In the superhero database, is it possible to return a value from a DELETE statement in PostgreSQL when no rows were deleted? For example, if we attempt to delete a superhero with an ID that does not exist, we want to return a default value indicating that no rows were deleted. We tried using the RETURNING clause with a constant value, but it returned NULL instead of the desired default value.", "error_sql": ["delete from superhero where id = 999 returning 1"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 101, "selected_database": "superhero", "query": "A data analyst is working with the superhero database and needs to perform a forward fill operation on the 'height_cm' and 'weight_kg' columns of the 'superhero' table. The analyst wants to create a PL/pgSQL function that mimics the behavior of the pandas 'ffill' function, which fills missing values with the last known non-null value. Here we use a table example(row_num int, id int, str text, val int) to test the functionality. We need to get the result of ffill(column val). The analyst has attempted to create a function but encountered syntax errors and incorrect results. The analyst needs a function that can handle forward filling for any specified column in the 'superhero' table, ordered by the 'id' column and partitioned by the 'publisher_id'.", "error_sql": ["CREATE OR REPLACE FUNCTION GapFillInternal(s anyelement, v anyelement) RETURNS anyelement AS $$ DECLARE temp alias for $0; BEGIN RAISE NOTICE 's= %, v= %', s, v; IF v IS NULL AND s NOTNULL THEN temp := s; ELSIF s IS NULL AND v NOTNULL THEN temp := v; ELSIF s NOTNULL AND v NOTNULL THEN temp := v; ELSE temp := NULL; END IF; RAISE NOTICE 'temp= %', temp; RETURN temp; END; $$ LANGUAGE PLPGSQL;", "CREATE AGGREGATE GapFill(anyelement) (SFUNC=GapFillInternal, STYPE=anyelement);", "SELECT id, str, val, GapFill(val) OVER (ORDER BY id) AS valx FROM example;"], "sol_sql": [], "preprocess_sql": ["CREATE TEMPORARY TABLE example(id int, str text, val integer);", "INSERT INTO example VALUES (1, 'a', NULL), (1, NULL, 1), (2, 'b', 2), (2, NULL, NULL)"], "clean_up_sql": ["DROP TABLE IF EXISTS example;", "DROP FUNCTION IF EXISTS GapFillInternal(anyelement, anyelement);", "DROP AGGREGATE IF EXISTS GapFill(anyelement);"], "test_cases": []} {"instance_id": 102, "selected_database": "california_schools", "query": "In the context of the 'california_schools' database, we need to update the 'table_A' table to deactivate certain items based on their associated records in table 'table_B'. Specifically, we want to find all items in table_A whose associated record in table_B has the 'deleted' set to 'true'. From this set of results, we need to get the 'parent_id' of these items. Then, for any item in the 'table_A' table whose 'id' is part of the 'parent_id' column from the previous result set, we need to check if their 'is_active' is 'true' and if so, make it 'false'. This operation is intended to deactivate items that are part of deleted status but the query gets stuck loading endlessly.", "error_sql": ["UPDATE table_A A SET is_active = false FROM table_A WHERE A.parent_id IS NULL AND A.is_active = true AND A.id = ANY (SELECT (B.parent_id) FROM table_A B INNER JOIN table_B ON table_A.foreign_id = table_B.id WHERE table_B.deleted = true) RETURNING *;"], "sol_sql": [], "preprocess_sql": ["create table table_B (id int primary key, deleted boolean);", "create table table_A (id serial primary key, parent_id int, is_active boolean default true, foreign_id int, foreign key (foreign_id) references table_B(id));", "insert into table_B (id, deleted) values (1, false), (2, true), (5, true), (3, false), (4, false)", "insert into table_A (parent_id, foreign_id) values (null, 1), (1, 2), (1, 5), (null, 3), (3, 4)"], "clean_up_sql": ["DROP TABLE table_A;", "DROP TABLE table_B;"], "test_cases": [], "efficiency": true} {"instance_id": 103, "selected_database": "toxicology", "query": "We are analyzing the sales data of a chemical supply company stored in the 'transactions' table. The columns are id (customer id), amount (amount spent by customer), and timestamp (time of purchase). Assume that today is '2022-01-27'. We need to query:\\n- Yesterday's revenue: sum of amount.\\n- Percent difference from 8 days ago's revenue to yesterday's revenue.\\n- Month-to-date (MTD) revenue.\\n- Percent difference from last month's MTD to this month's MTD.\\nWhen calculating the percentage, round the result to two decimal places.\nGiven the sample data:\\n| id | amount | timestamp |\\n| -- | ------ | -------- |\\n| 1 | 50 | 2021-12-01|\\n| 2 | 60 | 2021-12-02|\\n| 3 | 70 | 2021-11-05|\\n| 4 | 80 | 2022-01-26|\\n| 5 | 90 | 2022-01-25|\\n| 6 | 20 | 2022-01-26|\\n| 7 | 80 | 2022-01-19|\\nThe expected output is:\\n| yesterday_revenue | pct_change_week_ago | mtd | pct_change_month_prior|\\n| -------- | -------------- | --- | --- |\\n| 100 | 0.25 | 270 | 0.50|\\nHowever, the user's query resulted in incorrect percent change columns. Here is the problematic SQL statement:", "error_sql": ["SELECT SUM(CASE WHEN timestamp::date = '2022-01-27'::date - 1 THEN amount ELSE NULL END) AS yesterday_revenue, ROUND((SUM(CASE WHEN timestamp::date > '2022-01-27'::date - 1 THEN amount ELSE NULL END) - SUM(CASE WHEN timestamp::date = '2022-01-27'::date - 8 THEN amount ELSE NULL END)) / SUM(CASE WHEN timestamp::date = '2022-01-27'::date - 8 THEN amount ELSE NULL END), 2) AS pct_change_week_ago, SUM(CASE WHEN date_trunc('month', timestamp) = date_trunc('month', '2022-01-27'::date - 1) THEN amount ELSE NULL END) AS mtd, ROUND((SUM(CASE WHEN date_trunc('month', timestamp) = date_trunc('month', '2022-01-27'::date - 1) THEN amount ELSE NULL END) - SUM(CASE WHEN date_trunc('month', timestamp) = date_trunc('month', '2022-01-27'::date - 1) - interval '1 month' AND date_part('day', timestamp) <= date_part('day', '2022-01-27'::date - 1) THEN amount ELSE NULL END)) / SUM(CASE WHEN date_trunc('month', timestamp) = date_trunc('month', '2022-01-27'::date - 1) - interval '1 month' AND date_part('day', timestamp) <= date_part('day', '2022-01-27'::date - 1) THEN amount ELSE NULL END), 2) AS pct_change_month_prior FROM transactions;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE transactions (id int, amount numeric, timestamp date);", "INSERT INTO transactions (id, amount, timestamp) VALUES (1, 50, '2021-12-01'), (2, 60, '2021-12-02'), (3, 70, '2021-11-05'), (4, 80, '2022-01-26'), (5, 90, '2022-01-25'), (6, 20, '2022-01-26'), (7, 80, '2022-01-19');"], "clean_up_sql": ["DROP TABLE transactions;"], "test_cases": []} {"instance_id": 104, "selected_database": "card_games", "query": "I am analyzing the average converted mana cost of cards over a rolling window of 8 previous cards for each card in the 'cards' table. I need to round the nine_day_avg to two decimal places. However, I am having trouble placing the ROUND function correctly in the query. The query below does not produce the desired result. Can you help me correct it?", "error_sql": ["SELECT name, convertedManaCost, avg(convertedManaCost) OVER(ORDER BY id ROWS BETWEEN 8 PRECEDING AND CURRENT ROW) AS nine_card_avg FROM cards WHERE name LIKE 'A%' ORDER BY id DESC"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 105, "selected_database": "superhero", "query": "In the superhero database, each superhero has a set of attributes stored in a B column named 'attributes' within the 'hero_attribute' table. Each attribute object contains an 'ss_id' and an 'approved' status indicating whether the attribute is officially recognized by the superhero community. For example, a single record might look like this:\\n{\\", "error_sql": ["SELECT hero_id, attribute_id, jsonb_array_length(a.ss) AS ss_cnt, jsonb_array_length(CASE WHEN a.ss -> 'approved' = 'true' THEN a.ss END) AS approved_cnt FROM hero_attribute a WHERE a.hero_id IN (1, 2);"], "sol_sql": [], "preprocess_sql": ["ALTER TABLE hero_attribute ADD COLUMN ss JSONB;", "UPDATE hero_attribute SET ss = '[{\"ss_id\": 1, \"approved\": true}, {\"ss_id\": 2, \"approved\": false}]' WHERE hero_id = 1;", "UPDATE hero_attribute SET ss = '[{\"ss_id\": 1, \"approved\": true}, {\"ss_id\": 2, \"approved\": true}]' WHERE hero_id = 2;"], "clean_up_sql": ["ALTER TABLE hero_attribute DROP COLUMN ss;"], "test_cases": []} {"instance_id": 106, "selected_database": "financial", "query": "I am trying to speed up a PostgreSQL query to find previous transactions on the same day of the year from the 'trans' table. My current query is as follows:\\nsql \\nselect * from trans \\nwhere date_part('month', date) = date_part('month', now()) \\nand date_part('day', date) = date_part('day', now()) \\norder by date desc; \\n\\nThis query works but is running much slower than desired. Is there a better approach for comparing the current month and day?\\nThe data is time-series in nature, and I am using PostgreSQL as the database.", "error_sql": ["select * from trans where date_part('month', \"date\") = date_part('month', now()) and date_part('day', \"date\") = date_part('day', now()) order by \"date\" desc;"], "sol_sql": [], "preprocess_sql": ["CREATE INDEX ix1 ON trans (EXTRACT(MONTH FROM date), EXTRACT(DAY FROM date));"], "clean_up_sql": ["drop index if exists ix1;"], "test_cases": [], "efficiency": true} {"instance_id": 107, "selected_database": "financial", "query": "Is there an efficient way to aggregate data from a jsonb column in postgresql? Given the table userdata(id STRING, data JSONB) and the data in the table named \"test\".As you notice, I want unique values of keys (for e.g. \"dis\") across all records indexed by the id.I tried getting values using jsonb_agg and jsonb_array_elements. I could not aggregate all keys and distinct values. I couldn't figure out how to use jsonb_each to get all keys. What I tried is something like this to get one key. Any help with the query is appreciated. ", "error_sql": ["\nselect id,\n (select jsonb_agg(t->>'dis') from jsonb_array_elements(data::jsonb) as x(t) where t->>'dis' is not null) as sdata\nfrom test where id='123.abc'\n"], "sol_sql": [], "preprocess_sql": ["\nCREATE TABLE test (\n id TEXT NOT NULL,\n data JSONB NOT NULL\n);\nINSERT INTO test (id, data)\nVALUES\n ('123.abc', '{\"dis\": [\"close\"]}'),\n ('123.abc', '{\"purpose\": {\"score\": 0.1, \"text\": \"hi\"}, \"dis\": [\"hello\", \"close\"]}'),\n ('123.abc', '{\"dis\": [\"bye\"], \"dir\": 1}'),\n ('123.abc', '{}'),\n ('567.bhy', '{\"dis\": [\"close\"]}');\n"], "clean_up_sql": ["DROP TABLE test;"], "test_cases": [], "external_data": "('123.abc', '{\"dis\": [\"close\"]}'), ('123.abc', '{\"purpose\": {\"score\": 0.1, \"text\": \"hi\"}, \"dis\": [\"hello\", \"close\"]}'), ('123.abc', '{\"dis\": [\"bye\"], \"dir\": 1}'), ('123.abc', '{}'), ('567.bhy', '{\"dis\": [\"close\"]}')"} {"instance_id": 108, "selected_database": "european_football_2", "query": "\nIn the context of managing a football database, I am trying to update the 'overall_rating' of players based on their 'player_api_id' and the 'date' of their attributes. I have arrays of 'player_api_id's, 'date's, and 'overall_rating's that I want to use to update the 'Player_Attributes' table. My initial approach was to use a loop to iterate through the arrays and update each player's 'overall_rating' individually, but this method incorrectly updates the 'overall_rating' to the last value in the array for all selected players. To fix this issue, I need to ensure that each 'overall_rating' is correctly matched with the corresponding 'player_api_id' and 'date'. One solution is to use the 'unnest' function in SQL to pair the arrays together and update each player's 'overall_rating' individually. Here's the corrected SQL query I plan to use:\n", "error_sql": ["DO $$ DECLARE i integer; BEGIN \n FOREACH i IN ARRAY[11, 20]::integer[] LOOP \n RAISE NOTICE 'Value: %', i; \n UPDATE Player_Attributes SET overall_rating = i \n WHERE player_api_id = ANY (ARRAY[505942, 155782]::integer[]) \n AND date = ANY (ARRAY['2016-02-18 00:00:00', '2015-10-16 00:00:00']::text[]);\n END LOOP; \n END $$;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 109, "selected_database": "formula_1", "query": "In the context of the Formula 1 database, I am trying to perform a full-text search on a specific B field within the 'results' table. The B field contains race result details, and I am particularly interested in searching within the 'fastestLapTime' attribute. My initial attempt to perform this search using the `to_tsvector` and `to_tsquery` functions did not yield the expected results. Here is the problematic SQL statement I used:", "error_sql": ["\nSELECT resultId FROM results WHERE to_tsvector(results.fastestLapTime) @@ to_tsquery('1:35.405');\n"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 110, "selected_database": "formula_1", "query": "In the context of Formula 1 racing data, I have a table that records the results of races, including the race ID, driver ID, constructor ID, and the position each driver finished in. I want to count the occurrences of each finishing position by race and insert the number of occurrences into another table as a B object. The positions are not limited to a predefined set and can vary widely. Here's an example of what I'm trying to achieve: For each race, I want to count how many drivers finished in each position and store this information in a B column, where the key is the position and the value is the count of drivers who finished in that position.", "error_sql": ["\nSELECT raceId, position, COUNT(*) as cnt FROM results GROUP BY raceId, position\n"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 111, "selected_database": "european_football_2", "query": "In the context of the european_football_2 database, I am trying to understand 'keyset pagination' using the `Match` table which includes `id`, `date`, and `match_api_id` columns. My base query for the first page works perfectly, but I have a few use-cases which I don't understand how does it work if I want to order by `match_api_id DESC`.", "error_sql": ["\nSELECT * FROM Match WHERE (match_api_id, date, id) > (492473, '2008-08-17 00:00:00', 1) ORDER BY date, id ASC LIMIT 3\n"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 112, "selected_database": "california_schools", "query": "In the context of analyzing school data within the 'california_schools' database, I need to identify all schools that are located in both Alameda and Contra Costa counties. This is similar to finding products whose companies include both A and B in the original problem. I attempted to write a query that would return schools located in more than one county, but I'm struggling to refine this query to specifically include only those schools that are present in both Alameda and Contra Costa counties.", "error_sql": ["\nSELECT School FROM schools GROUP BY School HAVING COUNT(*) > 1 ORDER BY COUNT(*) DESC;\n"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 113, "selected_database": "formula_1", "query": "\nI'm new to SQL & I'm trying to get the raceid and name for each name with the latest date.\n", "error_sql": ["SELECT MAX(date), raceid, name FROM races GROUP BY name, raceid HAVING MAX(date) = date;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 114, "selected_database": "european_football_2", "query": "\nI need to generate a report that lists all possible combinations of match outcomes (win, lose, draw) for each team in the 'european_football_2' database. I tried the following query but it does not work as expected; it only returns a limited set of combinations instead of all possible combinations for each team.\n", "error_sql": ["SELECT t.team_name, o.outcome FROM (VALUES('Team A'),('Team B')) AS t(team_name) JOIN (VALUES('win'),('lose'),('draw')) AS o(outcome);"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 115, "selected_database": "california_schools", "query": "\nI am working with the california_schools database and need to analyze the frpm table to find the second highest enrollment (K-12) for each County Code, ignoring rows with NULL values in the County Code and Enrollment (K-12) fields. The goal is: Partition the data by County Code. Within each partition, sort the records by Enrollment (K-12) in descending order, with NULL values appearing last. Select the second highest enrollment record (rn = 2) from each partition. Exclude any counties where there's only one valid record.\n", "error_sql": ["\nSELECT DISTINCT ON (\"County Code\") * FROM frpm ORDER BY \"County Code\", \"Enrollment (K-12)\" DESC;\n"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 116, "selected_database": "formula_1", "query": "In the context of Formula 1 racing data, I have a table that contains information about the results of races, including the points scored by drivers and their finishing positions. I want to find out the maximum number of points that can be accumulated by a driver in races where the total points scored by all drivers in those races is less than or equal to 100. The expected output is the maximum points a single driver can score under this condition, considering the distribution of points across races.", "error_sql": ["SELECT SUM(quantity) FROM race_materials WHERE price_per_unit * quantity <= 100;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE IF NOT EXISTS race_materials (name text, price_per_unit int, quantity int); INSERT INTO race_materials (name, price_per_unit, quantity) VALUES ('A', 3, 30), ('B', 5, 3), ('C', 5, 3), ('D', 6, 20);"], "clean_up_sql": ["DROP TABLE race_materials;"], "test_cases": []} {"instance_id": 117, "selected_database": "formula_1", "query": "In the context of Formula 1 racing data, I have two tables: `drivers` and `results`. The `drivers` table contains information about each driver, including their unique `driverId` and `driverRef`. The `results` table records the outcomes of races, including the `driverId` of the participant, their `position` in the race, and the `points` they scored. I want to filter `drivers` by their `position` and `points` in the `results` table. Typically, I filter between 2-5 `position` and `points` values. There are approximately 6-10 `results` entries per driver. Given the large size of the database, I aim to optimize this query for performance, possibly by eliminating the `HAVING` clause. Here's the query I'm currently using:```sql\nSELECT \n drivers.forename, \n drivers.surname, \n jsonb_agg(jsonb_strip_nulls(jsonb_build_object('laps', results.laps, 'position', results.position))) AS race_results\nFROM \n drivers\nJOIN \n results\nON \n drivers.driverid = results.driverid\nGROUP BY \n drivers.forename, \n drivers.surname\nHAVING \n jsonb_agg(jsonb_build_object('laps', results.laps, 'position', results.position)) @? '$[*] ? (@.laps == 56) ? (@.position == 1)';\n```", "error_sql": ["SELECT \n drivers.forename, \n drivers.surname, \n jsonb_agg(jsonb_strip_nulls(jsonb_build_object('laps', results.laps, 'position', results.position))) AS race_results\nFROM \n drivers\nJOIN \n results\nON \n drivers.driverid = results.driverid\nGROUP BY \n drivers.forename, \n drivers.surname\nHAVING \n jsonb_agg(jsonb_build_object('laps', results.laps, 'position', results.position)) @? '$[*] ? (@.laps == 56) ? (@.position == 1)';"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": [], "efficiency": true} {"instance_id": 118, "selected_database": "european_football_2", "query": "\nHow can I generate a table that groups data from a player_attributes table by player_fifa_api_id and player_api_id and, for each group, concatenates the overall_rating values into a field?\n", "error_sql": ["INSERT INTO historical_rating (player_fifa_api_id, player_api_id, grouped_rating) SELECT player_fifa_api_id, player_api_id AS grouped_rating FROM player_attributes GROUP BY player_fifa_api_id, player_api_id;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE historical_rating (player_fifa_api_id INT, player_api_id INT, grouped_rating TEXT);"], "clean_up_sql": ["DROP TABLE historical_rating"], "test_cases": []} {"instance_id": 119, "selected_database": "codebase_community", "query": "\nIn a database that contains a table named 'posts', each post can reference a parent post through the 'acceptedanswerid' column. The goal is to retrieve posts based on the following conditions: (1) Include the parent post if the parent's 'score' is greater than or equal to 20, and (2) Include the child post if the parent's 'score' is less than 20 but the child's 'score' is greater than or equal to 20. Both parent and child posts should not be included simultaneously if the parent satisfies the condition. How can I write a query to achieve this?\n", "error_sql": ["SELECT DISTINCT id, acceptedanswerid, posttypeid, score FROM posts WHERE score >= 20 OR acceptedanswerid IS NOT NULL AND score >= 20 GROUP BY id, acceptedanswerid;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 120, "selected_database": "superhero", "query": "\nIn the superhero database, we want to identify a list of superheroes who have only the superpowers of 'Flight' and 'Telepathy' and do not possess any other superpowers. The following query seems to work, but I suspect there might be a more efficient way to achieve this result.", "error_sql": ["SELECT DISTINCT s.id \nFROM superhero s \nWHERE EXISTS (\n SELECT 1 \n FROM hero_power hp \n JOIN superpower sp ON hp.power_id = sp.id \n WHERE s.id = hp.hero_id AND sp.power_name = 'Flight'\n) \nAND EXISTS (\n SELECT 1 \n FROM hero_power hp \n JOIN superpower sp ON hp.power_id = sp.id \n WHERE s.id = hp.hero_id AND sp.power_name = 'Telepathy'\n) \nAND NOT EXISTS (\n SELECT 1 \n FROM hero_power hp \n JOIN superpower sp ON hp.power_id = sp.id \n WHERE s.id = hp.hero_id AND sp.power_name NOT IN ('Flight', 'Telepathy')\n);"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": [], "efficiency": true} {"instance_id": 121, "selected_database": "card_games", "query": "We have a table with card collection data which includes the start and end dates of when cards were added to and removed from a collection. Not all cards have an end date as they are still in the collection. We need to calculate the number of new cards added per month, cards removed per month, and existing cards per month. We have already completed counts of new and removed cards per month, but we are facing trouble in calculating the existing cards. The data starts from January 2023.", "error_sql": ["WITH card_activity AS ( SELECT to_date(fe.start_date_key::text, 'YYYYMMDD') AS start_date, to_date(fe.end_date_key::text, 'YYYYMMDD') AS end_date, dp.set_name, dp.set_code FROM fact_collection fe INNER JOIN dim_set dp ON fe.set_key = dp.set_key ) SELECT date_trunc('month', month_series) AS month, COUNT(*) AS existing_cards, sa.set_name FROM ( SELECT generate_series( (SELECT MIN(to_date(start_date_key::text, 'YYYYMMDD')) FROM fact_collection), '2100-12-31', INTERVAL '1 month') AS month_series ) AS months LEFT JOIN card_activity sa ON sa.start_date < month_series AND (sa.end_date IS NULL OR sa.end_date >= month_series) GROUP BY month, sa.set_name;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE dim_set ( set_key int4 GENERATED ALWAYS AS IDENTITY( INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START 1 CACHE 1 NO CYCLE) NOT NULL, set_name varchar NULL, set_code varchar NULL ); CREATE TABLE fact_collection ( card_key int4 NULL, start_date_key int4 NULL, end_date_key int4 NULL, set_key int4 NULL ); INSERT INTO dim_set (set_name, set_code) VALUES ('Core Set', '10E'); INSERT INTO fact_collection (card_key, start_date_key, end_date_key, set_key) VALUES (1, 20230105, 20230130, 1), (2, 20230106, 20230120, 1), (3, 20230405, 20230420, 1); INSERT INTO fact_collection (card_key, start_date_key, set_key) VALUES (4, 20230110, 1), (5, 20230120, 1), (6, 20230220, 1), (7, 20230202, 1), (8, 20230228, 1), (9, 20230206, 1), (10, 20230406, 1);"], "clean_up_sql": ["DROP TABLE IF EXISTS fact_collection; DROP TABLE IF EXISTS dim_set;"], "test_cases": []} {"instance_id": 122, "selected_database": "superhero", "query": "We have a dataset representing time spans during which superheroes have been active in various missions. Each record includes a superhero's ID, the start time, and the end time of their mission. We need to combine multiple rows into a single row where the missions are continuous (i.e., the end time of one mission is the start time of the next mission for the same superhero). The goal is to find the earliest start time and the latest end time for each continuous span of missions for each superhero.", "error_sql": ["WITH mission_spans AS ( SELECT hero_id, mission_start, mission_end FROM superhero_missions ORDER BY hero_id, mission_start, mission_end ) SELECT hero_id, MIN(mission_start) OVER (PARTITION BY hero_id), MAX(mission_end) OVER (PARTITION BY hero_id) FROM mission_spans ORDER BY 1, 2, 3"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE superhero_missions ( hero_id bigint, mission_start timestamp, mission_end timestamp );", "INSERT INTO superhero_missions (hero_id, mission_start, mission_end) VALUES (1, '2023-01-01 09:00:00', '2023-01-01 10:00:00'), (1, '2023-01-01 10:00:00', '2023-01-01 11:00:00'), (1, '2023-01-01 11:00:00', '2023-01-01 12:00:00'), (1, '2023-01-01 13:00:00', '2023-01-01 14:00:00'), (1, '2023-01-01 14:00:00', '2023-01-01 15:00:00'), (1, '2023-01-01 15:00:00', '2023-01-01 16:00:00'), (2, '2023-01-01 10:00:00', '2023-01-01 11:00:00'), (2, '2023-01-01 11:00:00', '2023-01-01 12:00:00'), (2, '2023-01-01 13:00:00', '2023-01-01 14:00:00'), (3, '2023-01-01 10:00:00', '2023-01-01 11:00:00');"], "clean_up_sql": ["DROP TABLE IF EXISTS superhero_missions;"], "test_cases": []} {"instance_id": 123, "selected_database": "card_games", "query": "I am trying to find the median release date of all card sets in the 'sets' table of the card_games database. The goal is to obtain the date that is in the middle of all the release dates. I attempted to use the percentile_cont function directly on the date column, but encountered an error. Here is the SQL statement I used:", "error_sql": ["SELECT percentile_cont(0.5) within group (ORDER by releasedate) FROM sets"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 124, "selected_database": "formula_1", "query": "I am creating a table to track race incidents and I need a check constraint to validate the possible values given a string value. I am creating this table: \\\\", "error_sql": ["CREATE TABLE race_incidents ( incident_type VARCHAR(30) NOT NULL CHECK(incident_type = 'Engine failure' OR incident_type = 'Collision'), incident_description VARCHAR(30) NOT NULL);"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 125, "selected_database": "financial", "query": "In the financial database, we have two tables: `trans` and `account`. The `trans` table tracks all transactions made on each account, with multiple rows per account. The `account` table contains only one row per account, representing the most recent transaction details. We need to update the `account` table with the details of the most recent transaction (highest `trans_id`) for each account. The tables have many columns, so we would like to use a method that includes all fields in the update without explicitly listing them.", "error_sql": ["select * from trans t1 where (account_id, trans_id) in (select account_id, max(trans_id) from trans t1 group by account_id);"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE latest_trans AS SELECT DISTINCT account_id, 0 AS amount, 0 AS trans_id FROM trans;"], "clean_up_sql": ["drop table if exists latest_trans;"], "test_cases": []} {"instance_id": 126, "selected_database": "european_football_2", "query": "I am trying to run a recursive query in PostgreSQL to find all teams that belong under a specific league. The query is the following: I need to find all teams that are part of a league and any sub-leagues they might belong to. However, I am encountering issues with the recursive CTE. The error seems to be related to the structure of the CTE and the use of UNION instead of UNION ALL. Additionally, I am unsure how to properly reference the initial CTE within the recursive part of the query.", "error_sql": ["WITH TAB AS (SELECT id as league_id, name FROM League UNION SELECT id, name FROM League) , RECURSIVE recuree AS ( SELECT league_id, name FROM TAB UNION SELECT E.league_id, E.name FROM TAB E JOIN recuree S ON E.id = S.league_id) SELECT * FROM recuree"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 127, "selected_database": "superhero", "query": "In our superhero database, we have multiple tables that store various attributes and details about superheroes. I need to retrieve all records from the `superhero` table across all column names that end with '_id' in josn. The column names are dynamic, with new ones being added and old ones being removed frequently, so I cannot hardcode the column names in my query. How can I achieve this?", "error_sql": ["SELECT * \nFROM superhero.\"%_id\";"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 128, "selected_database": "card_games", "query": "In the context of managing a database for a card game, I need to ensure that when inserting data into a table, if a null value is provided for certain enum fields, the default value specified during the table creation is used instead. Currently, when I insert data with null values for these enum fields, the null values are being inserted rather than the default values. Here's an example of the issue I'm encountering:\n\nsql\nINSERT INTO cards(availability, borderColor) VALUES (NULL, 'black');\n\n\nThis results in the following data being inserted:\n\n|availability|borderColor|\n|---|---|\n|NULL|black|\n\nHowever, I need the data to be inserted with the default value for 'availability' when NULL is provided, like so:\n\n|availability|borderColor|\n|---|---|\n|mtgo,paper|black|", "error_sql": ["INSERT INTO cards(availability, borderColor) VALUES (NULL, 'black');"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 129, "selected_database": "formula_1", "query": "In the context of Formula 1 racing data, I have a table named `races` with a column `date` of type `date`. I need each of the values in `date` to be unique. Given a `date` input, `input_date`, I need to find the **minimum** `date` value that satisfies the following criteria: the result must be >= `input_date` and the result must not already be in `date`. I cannot merely add one day to the greatest value in `date`, because I need the minimum value that satisfies the above criteria. Is there a concise way to compute this as part of an insert or update to the `races` table?", "error_sql": ["INSERT INTO races (raceid, year, round, circuitid, name, date, time, url)\nVALUES (\n 999,\n 2023,\n 1,\n 1,\n 'Test Grand Prix',\n '2023-04-01',\n '12:00:00',\n 'http://example.com'\n)"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 130, "selected_database": "formula_1", "query": "In the context of Formula 1 racing data, we have a table that records the lap times of drivers across different races. Each driver has multiple lap times recorded for each race they participate in. The goal is to select a specific driver's lap times across all races they've participated in, aggregating these times by race. Given `driverId=1` and `name=Lewis Hamilton`, we want to retrieve his lap times for each race, aggregated by race, to analyze his performance across different circuits. The desired output should list each race with the corresponding aggregated lap times for the specified driver.", "error_sql": ["SELECT\n sub.raceId,\n sub.t[1] AS \"Lap_Time_Race1\",\n sub.t[2] AS \"Lap_Time_Race2\",\n sub.t[3] AS \"Lap_Time_Race3\"\nFROM (\n SELECT\n driverId,\n raceId,\n ARRAY_AGG(milliseconds ORDER BY lap) AS t\n FROM lapTimes\n WHERE driverId = 1\n GROUP BY driverId\n) AS sub\nORDER BY sub.raceId;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 131, "selected_database": "thrombosis_prediction", "query": "In the context of a medical database tracking patient examinations and laboratory tests, I have a table called `Examination` that records various test results for patients, including a `Thrombosis` score indicating the severity of thrombosis. Another table, `Laboratory`, logs detailed laboratory test results over time for each patient. I need to retrieve the last two laboratory test results for each patient's `Thrombosis` score, but instead of getting two rows for each patient, I want to have two new columns with the previous `Thrombosis` scores, labeled as `Thrombosis_1` and `Thrombosis_2`. The desired result should look like this: ID | Thrombosis_1 | Thrombosis_2, where each row represents a patient with their last two `Thrombosis` scores.", "error_sql": ["SELECT * FROM Examination AS e LEFT JOIN LATERAL (SELECT * FROM Laboratory WHERE ID = e.ID ORDER BY Date DESC LIMIT 2) AS lab ON true"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 132, "selected_database": "toxicology", "query": "In the context of a toxicology database, we have a scenario where we need to identify the atoms that are most frequently connected to other atoms within molecules, essentially finding the atoms with the most 'friends' (connections) and the number of these connections. Given the schema and data provided, we aim to find the atom(s) with the highest number of connections and the count of these connections.", "error_sql": ["select a.f as \"id\", count(a.f) as \"num\" from ( select atom_id as f from connected union all select atom_id2 as f from connected ) a group by a.f order by count(a.f) desc limit 1;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 133, "selected_database": "european_football_2", "query": "I'm trying to create a trigger that will add a new row processed entry to a destination table each time a new row is created in the source table. The source table contains detailed information about match events in a football league, including timestamps, match IDs, player IDs, event types, and additional data about the event context. The destination table should store processed information about these events, including the timestamp, match ID, player ID, event type, a simplified URL from the event context, and the user ID who recorded the event. The trigger function is not working as expected, and no new entries are being recorded in the destination table despite new rows being inserted into the source table.", "error_sql": ["CREATE OR REPLACE FUNCTION triger_function() RETURNS TRIGGER AS $BODY$ BEGIN INSERT INTO public.destination_table ( created_at, match_id, player_id, event_type, url, user_id) SELECT created_at, match_id, player_id, event_type, split_part(url::text, '?', 1) AS url, ((((data >> '{}')::jsonb >> '{}')::jsonb -> 'local_storage'::text) -> 'data'::text) >> '{}' -> 'user_id'::varchar FROM source_table; RETURN new; END; $BODY$ language plpgsql;", "CREATE TRIGGER after_insert_source_error\nAFTER INSERT ON public.source_table\nFOR EACH ROW\nEXECUTE PROCEDURE trigger_function_error();", "INSERT INTO public.source_table (\n created_at,\n match_id,\n player_id,\n event_type,\n url,\n data\n)\nVALUES (\n NOW(), -- created_at\n 101, -- match_id\n 202, -- player_id\n 'goal', -- event_type\n 'http://example.com?foo=bar', -- url\n '{\n \"local_storage\": {\n \"data\": {\n \"user_id\": \"u12345\"\n }\n }\n }'::jsonb -- data\n);"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE public.source_table (\n id serial PRIMARY KEY,\n created_at TIMESTAMP NOT NULL,\n match_id INTEGER NOT NULL,\n player_id INTEGER NOT NULL,\n event_type VARCHAR NOT NULL,\n url VARCHAR NOT NULL,\n data JSONB NOT NULL\n);\n\nCREATE TABLE public.destination_table (\n id serial PRIMARY KEY,\n created_at TIMESTAMP NOT NULL,\n match_id INTEGER NOT NULL,\n player_id INTEGER NOT NULL,\n event_type VARCHAR NOT NULL,\n url VARCHAR NOT NULL,\n user_id VARCHAR\n);"], "clean_up_sql": ["DROP TABLE public.source_table; DROP TABLE public.destination_table;"], "test_cases": []} {"instance_id": 134, "selected_database": "superhero", "query": "I am given a task to optimize the following query (not originally written by me). The query calculates the success rate of superheroes requesting new powers, where each request can have up to 5 retries if it fails.\n\nThe query needs to return:\n1. The total number of requests,\n2. The success rate (ratio of successful to total requests),\n3. Grouped by the power requested and the superhero's ID.\n\nHowever, the current query is very slow on a large dataset (millions of rows). Below is the table-creation script, data-insertion script, and the problematic query. How can I optimize this further?\n", "error_sql": ["SELECT\n s.superhero_id AS \"superheroId\",\n p.power_name AS \"power\",\n COUNT(*) AS \"totalRequests\",\n SUM(\n CASE WHEN r.status = 'success' THEN 1 ELSE 0 END\n ) * 100.0 / COUNT(*) AS \"successRate\"\nFROM public.superhero_requests s\nJOIN public.superpower p\n ON s.superpower_id = p.id\nJOIN (\n SELECT\n id,\n superhero_id,\n superpower_id,\n status,\n retry_number,\n main_request_uuid,\n ROW_NUMBER() OVER (\n PARTITION BY main_request_uuid\n ORDER BY retry_number DESC, id DESC\n ) AS row_number\n FROM public.superhero_requests\n) r\n ON s.id = r.id\nWHERE s.created_at >= CURRENT_DATE - INTERVAL '30 days'\n AND s.created_at <= CURRENT_DATE\n AND r.row_number = 1\nGROUP BY\n s.superhero_id,\n p.power_name\nLIMIT 10;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE IF NOT EXISTS public.superhero_requests (\n id BIGINT NOT NULL,\n superhero_id BIGINT NOT NULL,\n superpower_id BIGINT NOT NULL,\n status TEXT NOT NULL,\n created_at TIMESTAMPTZ NOT NULL,\n retry_number SMALLINT NOT NULL,\n main_request_uuid VARCHAR NOT NULL,\n PRIMARY KEY (id)\n);", "INSERT INTO public.superhero_requests (\n id,\n superhero_id,\n superpower_id,\n status,\n created_at,\n retry_number,\n main_request_uuid\n)\nSELECT\n generate_series(1, 1000000) AS id,\n (random() * 750)::int + 1 AS superhero_id, -- IDs between 1..750\n (random() * 5)::int + 1 AS superpower_id, -- referencing our 5 sample powers (1..5)\n CASE WHEN random() < 0.8 THEN 'success'\n ELSE 'failure'\n END AS status, \n NOW() - (random() * 30)::int * '1 day'::interval AS created_at,\n (random() * 5)::int AS retry_number, -- 0..5\n md5(random()::text) AS main_request_uuid -- random UUID-like string\n;"], "clean_up_sql": ["DROP TABLE public.superhero_requests;"], "test_cases": [], "efficiency": true} {"instance_id": 135, "selected_database": "formula_1", "query": "In the Formula 1 database, I have a table named 'races' that contains information about each race, including the date of the race. I want to create a SELECT statement that not only returns the contents of the 'races' table but also includes an additional column that tells me how many races were held in the same year. For example, if there were 3 races in '2009', then for each race on that date, the 'same_year_races' column should be 3. I can create a separate statement using GROUP BY, but I'm looking for a way to make a single statement that includes the 'same_year_races' column in the results table.", "error_sql": ["SELECT raceId, name, year, COUNT(*) AS same_year_races FROM races GROUP BY raceid, name, year"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 136, "selected_database": "card_games", "query": "In the card_games database, we have a table named 'card_prices' that records the price changes of cards over time. Each entry includes the timestamp of the price change, the card's UUID, and the new price. When a new price is recorded, we need to take the first price older than 30 days, along with prices from the last 30 days, and return the minimum. When new price came, we should not include in range: New Price Date: 2022/08/11; 30 days subtracted date: 2022/07/12. However, since price changes are not daily, we must also consider the price before the 30-day window to ensure we capture the correct minimum price. The current query is slow and sometimes returns incorrect results due to the way it handles the 30-day window and the price before it. We need to optimize the query to ensure it runs efficiently and accurately.", "error_sql": ["SELECT min(price) FROM card_prices WHERE (timestamp >= (SELECT MAX(timestamp) FROM card_prices WHERE timestamp < '2022-07-12T15:30:00-00:00' AND uuid = '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c') OR timestamp >= '2022-07-12T15:30:00-00:00' AND timestamp < '2022-08-11T15:30:00-00:00') AND uuid = '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c' AND price > 0"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE card_prices (timestamp timestamp with time zone not null, uuid varchar(200) not null, price numeric(12, 2));", "INSERT INTO card_prices (timestamp, uuid, price) VALUES ('2022-07-09 18:18:39.000000 +00:00','5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 120.00), ('2022-07-10 15:45:56.000000 +00:00', '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 125.00), ('2022-07-12 08:00:10.000000 +00:00', '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 130.00), ('2022-07-14 13:15:55.000000 +00:00', '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 135.00), ('2022-07-16 10:33:11.000000 +00:00', '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 140.00), ('2022-07-18 20:18:48.000000 +00:00', '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 145.00), ('2022-07-20 07:40:29.000000 +00:00', '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 150.00), ('2022-07-22 14:11:59.000000 +00:00', '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 155.00), ('2022-07-25 11:55:30.000000 +00:00', '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 160.00), ('2022-07-28 16:05:07.000000 +00:00', '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 165.00), ('2022-07-30 09:40:25.000000 +00:00', '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 170.00), ('2022-08-02 18:30:13.000000 +00:00', '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 175.00), ('2022-08-05 21:19:40.000000 +00:00','5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c',130.00), ('2022-08-10 11:20:39.000000 +00:00','5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c',140.00);"], "clean_up_sql": ["DROP TABLE card_prices;"], "test_cases": [], "efficiency": true} {"instance_id": 137, "selected_database": "superhero", "query": "Imagine the following data representing the attribute scores of superheroes over five consecutive years. We are interested in identifying superheroes whose attribute scores have gaps (null values) or have changed from one year to another, or both. The output should include only those superheroes who have gaps or scores different from their maximum score recorded over the years. For example, if a superhero's maximum score in an attribute is 100, and their scores over the years are 100, 90, 100, null, 100, this superhero should be included in the output because of the gap in year 4. Similarly, if a superhero's scores are 100, 90, 100, 100, 100, this superhero should also be included because their score in year 2 is different from their maximum score.", "error_sql": ["with hero_attribute_data (hero_id, attribute_id, max_score, year_1, year_2, year_3, year_4, year_5) as (values (1, 1, 80, 80, 80, 80, null, 80), (2, 2, 90, 90, 85, 90, 88, 90), (3, 3, 75, 75, 70, null, 75, 75), (4, 4, 60, null, 60, 60, 60, null)), score_check as (select *, case when (max_score <> year_1 or max_score <> year_2 or max_score <> year_3 or max_score <> year_4 or max_score <> year_5) then false else true end as is_a_match from hero_attribute_data) select * from score_check where is_a_match is false"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 138, "selected_database": "superhero", "query": "In the superhero database, we have a table that represents the crafting recipes for special items used by superheroes. Each item can be bought directly from the store or crafted using other items and resources. The goal is to determine whether it is more cost-effective to buy an item directly or to craft it using the available resources and other items. The table includes the item ID, its retail price, the quantity needed, and the resources or items required to craft it along with their respective prices. We need to calculate both the partial craft price (cost of crafting using only resources) and the full craft price (cost of crafting using both resources and other items). The partial craft price is straightforward to calculate, but the full craft price requires a recursive approach to account for nested dependencies. The user attempted to use a recursive CTE to calculate the full craft price but encountered issues with the query logic. We need to correct the query to accurately compute the full craft price for each item.", "error_sql": ["select item_id, item_price as retail_price, sum(coalesce(uses_item_price, 0) * quantity) + sum(coalesce(resource_price*quantity, 0)) as partial_craft_price FROM store GROUP BY item_id, retail_price;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE store ( item_id integer, item_price real, quantity integer, uses_item_id integer, uses_item_price real, resource_id integer, resource_price real );", "INSERT INTO store (item_id, item_price, quantity, uses_item_id, uses_item_price, resource_id, resource_price) VALUES (1, 10000, 10, null, null, 5, 50 ), (1, 10000, 20, null, null, 6, 50 ), (2, 150, 1, 1, 10000, null, null), (2, 150, 5, null, null, 8, 50 ), (3, 5500, 3, null, null, 9, 50 ), (3, 5500, 50, 1, 10000, null, null ), (3, 5500, 1, 2, 150, null, null );"], "clean_up_sql": ["DROP TABLE store;"], "test_cases": []} {"instance_id": 139, "selected_database": "superhero", "query": "I want to UPDATE the superhero's full_name in the superhero table using a WHERE clause by team_id = 91 and using JOIN. The main table superhero structure looks like: | id | superhero_name | full_name | The two fields in two more connected tables with the values I need are in team_member and team_member_superhero tables. Table team_member_superhero structure looks like: | id | team_member_id | superhero_id | Table team_member: | id | team_id | superhero_id |", "error_sql": ["UPDATE superhero SET full_name = 'Superman' JOIN team_member_superhero ON superhero.id = team_member_superhero.superhero_id JOIN team_member ON team_member_superhero.team_member_id = team_member.id WHERE team_id = 91;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE team_member_superhero (id bigint NOT NULL, team_member_id bigint NULL, superhero_id bigint NULL, PRIMARY KEY (id));", "CREATE TABLE team_member (id bigint NOT NULL, team_id bigint NULL, PRIMARY KEY (id));", "INSERT INTO team_member_superhero (id, team_member_id, superhero_id) VALUES (1, 1, 1);", "INSERT INTO team_member (id, team_id) VALUES (1, 91);"], "clean_up_sql": ["UPDATE superhero s SET full_name = 'Charles Chandler' FROM team_member_superhero tms JOIN team_member tm ON tms.team_member_id = tm.id WHERE s.id = tms.superhero_id AND tm.team_id = 91;", "DROP TABLE team_member_superhero;", "DROP TABLE team_member;"], "test_cases": []} {"instance_id": 140, "selected_database": "european_football_2", "query": "The football league management system requires a report that shows the performance of each team in terms of the number of matches played, victories, defeats, draws, and the total score. The score is calculated by awarding 3 points for a victory, 1 point for a draw, and 0 points for a defeat. The data is stored in the 'team' and 'match' tables. The 'team' table contains the team details, and the 'match' table contains the match details including the goals scored by the home and away teams. The task is to generate a report that includes the team name, number of matches, victories, defeats, draws, and the total score for each team. The user has attempted to write a query but is seeking a more efficient and cleaner solution.", "error_sql": ["SELECT t.team_long_name, count(m.home_team_api_id) filter(WHERE t.team_api_id = m.home_team_api_id) + count(m.away_team_api_id) filter(WHERE t.team_api_id = m.away_team_api_id) as matches, count(m.home_team_api_id) filter(WHERE t.team_api_id = m.home_team_api_id AND m.home_team_goal > m.away_team_goal) + count(m.away_team_api_id) filter(WHERE t.team_api_id = m.away_team_api_id AND m.away_team_goal > m.home_team_goal) as victories, count(m.home_team_api_id) filter(WHERE t.team_api_id = m.home_team_api_id AND m.home_team_goal < m.away_team_goal) + count(m.away_team_api_id) filter(WHERE t.team_api_id = m.away_team_api_id AND m.away_team_goal < m.home_team_goal) as defeats, count(m.home_team_api_id) filter(WHERE t.team_api_id = m.home_team_api_id AND m.home_team_goal = m.away_team_goal) + count(m.away_team_api_id) filter(WHERE t.team_api_id = m.away_team_api_id AND m.away_team_goal = m.home_team_goal) as draws, ((count(m.home_team_api_id) filter(WHERE t.team_api_id = m.home_team_api_id AND m.home_team_goal > m.away_team_goal) + count(m.away_team_api_id) filter(WHERE t.team_api_id = m.away_team_api_id AND m.away_team_goal > m.home_team_goal)) * 3) + count(m.home_team_api_id) filter(WHERE t.team_api_id = m.home_team_api_id AND m.home_team_goal = m.away_team_goal) + count(m.away_team_api_id) filter(WHERE t.team_api_id = m.away_team_api_id AND m.away_team_goal = m.home_team_goal) as score FROM team t JOIN match m ON t.team_api_id IN (m.home_team_api_id, m.away_team_api_id) GROUP BY t.team_long_name ORDER BY victories DESC"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": [], "efficiency": true} {"instance_id": 141, "selected_database": "thrombosis_prediction", "query": "We have two tables in our thrombosis_prediction database: patient and examination. The patient table contains patient information, and the examination table contains examination results for each patient. We want to create a report that shows each patient's ID and whether they have had an examination with specific diagnoses (e.g., 'SLE', 'PSS', 'RA susp.') recorded. The result should be a table with patient IDs and columns for each diagnosis, indicating TRUE if the patient has had an examination with that diagnosis and FALSE otherwise. The user attempted to write a query but encountered issues with multiple rows for each patient and incorrect TRUE/FALSE values.", "error_sql": ["SELECT p.id, CASE WHEN e.id = p.id AND e.diagnosis = 'SLE' THEN TRUE ELSE FALSE END AS SLE, CASE WHEN e.id = p.id AND e.diagnosis = 'PSS' THEN TRUE ELSE FALSE END AS PSS, CASE WHEN e.id = p.id AND e.diagnosis = 'RA susp.' THEN TRUE ELSE FALSE END AS RA_susp FROM patient p LEFT JOIN examination e ON p.id = e.id WHERE e.diagnosis IN ('SLE', 'PSS', 'RA susp.') ORDER BY p.id DESC"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 142, "selected_database": "superhero", "query": "We have two tables in our superhero database, 'hero_birth_info' and 'hero_birth_info_alt'. The 'hero_birth_info' table contains the birthdate of superheroes, while the 'hero_birth_info_alt' table contains an alternative date of birth for some superheroes. We need to combine these two tables to get a single birth date for each superhero, prioritizing the date from 'hero_birth_info_alt' if it exists. However, when we run the following query, we get incorrect results where the birthdate from 'hero_birth_info_alt' is not correctly combined with the birthdate from 'hero_birth_info'.", "error_sql": ["SELECT hbi.id, hbi.hero_name, hbi.birthdate, hbialt.date_of_birth FROM hero_birth_info hbi LEFT JOIN hero_birth_info_alt hbialt ON hbi.id = hbialt.id"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE hero_birth_info (id bigint NOT NULL, hero_name text NULL, birthdate date NULL, PRIMARY KEY (id));", "INSERT INTO hero_birth_info (id, hero_name, birthdate) VALUES (1, 'Sylvie', '2016-06-01'), (2, 'Rolf', NULL), (3, 'Jose', '2004-02-16'), (4, 'Eugin', NULL), (5, 'Andrey', '1998-09-29'), (6, 'Ivan', '2000-05-12'), (7, 'Vasiys', '2001-07-17'), (8, 'Alexey', '1993-09-05');", "CREATE TABLE hero_birth_info_alt (id bigint NOT NULL, hero_name text NULL, date_of_birth date NULL, PRIMARY KEY (id));", "INSERT INTO hero_birth_info_alt (id, hero_name, date_of_birth) VALUES (1, 'Sylvie', NULL), (2, 'Rolf', '2015-12-06'), (3, 'Jose', NULL), (4, 'Eugin', '1995-04-01'), (5, 'Andrey', '1998-09-29');"], "clean_up_sql": ["DROP TABLE hero_birth_info;", "DROP TABLE hero_birth_info_alt;"], "test_cases": []} {"instance_id": 143, "selected_database": "superhero", "query": "In the superhero database, there are instances where the hair_colour_ids of superheroes within the same publisher are not contiguous due to deletions. To address this, I want to create a function that will reindex these hair_colour_ids to make them contiguous again. The function should take a publisher ID as input and reindex the hair_colour_ids of superheroes belonging to that publisher. I attempted to create a function that uses a temporary sequence to achieve this, but encountered an error when trying to use the sequence within the function. The error message was 'relation "id_seq_temp" does not exist'. I tried creating the sequence outside the function, but I prefer to keep the sequence within the function for cleaner code. Here is my function, with some names anonymized for privacy reasons.", "error_sql": ["CREATE OR REPLACE FUNCTION reindex_superhero_ids(IN BIGINT) RETURNS VOID LANGUAGE SQL AS $$ CREATE TEMPORARY SEQUENCE id_seq_temp MINVALUE 1 START WITH 1 INCREMENT BY 1; ALTER SEQUENCE id_seq_temp RESTART; UPDATE superhero SET hair_colour_id=hair_colour_id+2000 WHERE publisher_id=$1; UPDATE superhero SET hair_colour_id=nextval('id_seq_temp') WHERE publisher_id=$1; $$;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": ["DROP FUNCTION IF EXISTS reindex_superhero_ids(BIGINT);", "UPDATE superhero SET hair_colour_id = 1 WHERE publisher_id = 9;"], "test_cases": []} {"instance_id": 144, "selected_database": "card_games", "query": "In the card_games database, a table named card_versions was created to track different versions of a card with a unique sequence number, definition ID, attribute ID, and input data. The primary key is a composite key consisting of defn_id, attr_id, and seqnr. Records were inserted into the card_versions table with sequential seqnr values for a specific defn_id and attr_id. When attempting to update the seqnr values by incrementing them for all records with defn_id = 100 and attr_id = 100, an error occurred in PostgreSQL due to the immediate uniqueness constraint check on the primary key. The task is to reproduce this issue and provide a solution to update the seqnr values without violating the primary key constraint.", "error_sql": ["UPDATE card_versions SET seqnr=seqnr+1 WHERE defn_id = 100 AND attr_id = 100 AND seqnr >= 1"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE card_versions(seqnr smallint NOT NULL, defn_id int NOT NULL, attr_id int NOT NULL, input CHAR(50) NOT NULL, CONSTRAINT pk_card_versions PRIMARY KEY (defn_id, attr_id, seqnr));", "INSERT INTO card_versions(seqnr,defn_id,attr_id,input) VALUES (1,100,100,'test1'), (2,100,100,'test2'), (3,100,100,'test3'), (4,100,100,'test4'), (5,100,100,'test5');"], "clean_up_sql": ["DROP TABLE card_versions;"], "test_cases": []} {"instance_id": 145, "selected_database": "european_football_2", "query": "As part of an analysis for a football analytics project, I need to create a JSONB column in the 'team_attributes' table that consolidates several existing attributes into a single JSONB object. Initially, I attempted to use the following query to populate this JSONB column with values from other columns in the same table:", "error_sql": ["UPDATE team_attributes SET attributes_jsonb = jsonb_insert('{}', '{buildupplayspeed}', buildupplayspeed) WHERE team_api_id = 1773;", "SELECT id, attributes_jsonb FROM team_attributes WHERE team_api_id = 1773 ORDER BY id;"], "sol_sql": [], "preprocess_sql": ["ALTER TABLE team_attributes ADD COLUMN attributes_jsonb jsonb"], "clean_up_sql": ["ALTER TABLE team_attributes DROP COLUMN attributes_jsonb"], "test_cases": []} {"instance_id": 146, "selected_database": "toxicology", "query": "In the toxicology database, we need to identify all ancestor atoms of a given atom using the 'connection' table, which contains the relationships between atoms through bonds. Each atom is linked to its parent atom via the 'atom_id' and 'parent_id' fields in the 'connection' table. Additionally, each atom has an 'enabled' status in the table, which indicates whether the atom is active or not. If any ancestor atom of a given atom has its 'enabled' status set to false, the query should return no results for that atom. For example, if we are querying for all ancestor atoms of atom 'TR000_4', and any of its ancestor atoms have 'enabled' set to false, the query should return no results.", "error_sql": ["WITH RECURSIVE atom_ancestors AS ( SELECT atom_id, parent_id, enabled FROM connection WHERE atom_id = 4 UNION ALL SELECT c.atom_id, c.parent_id, c.enabled FROM connection c INNER JOIN atom_ancestors aa ON c.atom_id = aa.parent_id) SELECT * FROM atom_ancestors"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE connection (atom_id integer, parent_id integer, enabled boolean)", "INSERT INTO connection (atom_id, parent_id, enabled) VALUES (1, null, true), (2, 1, false), (3, 1, true), (4, 2, true);"], "clean_up_sql": ["DROP TABLE connection;"], "test_cases": []} {"instance_id": 147, "selected_database": "card_games", "query": "\nIs there an efficient way to aggregate data from a JSONB column in PostgreSQL? Given the table card_preference(customerid STRING, preference JSONB) and the data in the table. As you notice, I want unique values of keys (for example, \"dis\") across all records, grouped by customerid. I tried extracting values using jsonb_agg and jsonb_array_elements, but I couldn’t aggregate all keys and distinct values correctly. I also couldn't figure out how to use jsonb_each to get all keys. What I tried is something like this to get a single key. Any help with the query is appreciated.\n", "error_sql": ["\nselect customerid,\n (select jsonb_agg(t->>'dis') from jsonb_array_elements(preference::jsonb) as x(t) where t->>'dis' is not null) as sdata\nfrom card_preference where customerid='123.abc'\n"], "sol_sql": [], "preprocess_sql": ["\nCREATE TABLE card_preference (\n customerid TEXT NOT NULL,\n preference JSONB NOT NULL\n);\nINSERT INTO card_preference (customerid, preference)\nVALUES\n ('123.abc', '{\"dis\": [\"close\"]}'),\n ('123.abc', '{\"purpose\": {\"score\": 0.1, \"text\": \"hi\"}, \"dis\": [\"hello\", \"close\"]}'),\n ('123.abc', '{\"dis\": [\"bye\"], \"dir\": 1}'),\n ('123.abc', '{}'),\n ('567.bhy', '{\"dis\": [\"close\"]}');\n"], "clean_up_sql": ["drop table card_preference"], "test_cases": [], "external_data": "('123.abc', '{\"dis\": [\"close\"]}'), ('123.abc', '{\"purpose\": {\"score\": 0.1, \"text\": \"hi\"}, \"dis\": [\"hello\", \"close\"]}'), ('123.abc', '{\"dis\": [\"bye\"], \"dir\": 1}'), ('123.abc', '{}'), ('567.bhy', '{\"dis\": [\"close\"]}')"} {"instance_id": 148, "selected_database": "superhero", "query": "In the superhero database, we have a table named 'hero_attribute' that stores the attribute values for each superhero. Each superhero can have multiple attributes, and each attribute can have different values for different superheroes. The goal is to identify any differences in attribute values for the same superhero across different records. For example, if a superhero has different values for the same attribute in different records, we need to flag that attribute for that superhero. The outcome should be a list of superheroes with the attribute names that have differences.", "error_sql": ["\nSELECT hero_id, 'attribute_value' AS Difference FROM hero_attribute \nGROUP BY hero_id HAVING COUNT(DISTINCT attribute_value) > 1 \nOR (COUNT(attribute_value) != COUNT(*) AND COUNT(DISTINCT attribute_value) > 0) \nUNION ALL SELECT hero_id, 'attribute_id' AS Difference FROM hero_attribute GROUP BY hero_id \nHAVING COUNT(DISTINCT attribute_id) > 1 OR (COUNT(attribute_id) != COUNT(*) \nAND COUNT(DISTINCT attribute_id) > 0)\n"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 149, "selected_database": "student_club", "query": "In the student_club database, there is a table named `member` with the following columns: `member_id` (primary key), `first_name`, `last_name`, `email`, `position`, `t_shirt_size`, `phone`, `zip`, and `link_to_major`. The `link_to_major` column has a `NOT NULL` constraint. The user attempted to insert a new member into the `member` table with the following query:\n\nsql\nINSERT INTO member(member_id, first_name, last_name)\nVALUES ('new_member_id', 'John', 'Doe')\nON CONFLICT (member_id)\nDO UPDATE SET first_name=excluded.first_name, last_name=excluded.last_name;\n\n\nHowever, the query resulted in an error because the `link_to_major` column, which has a `NOT NULL` constraint, was not provided a value. The error message from PostgreSQL was:\n\n> ERROR: null value in column \"link_to_major\" of relation \"member\" violates not-null constraint\n\nThe user expected the `ON CONFLICT` clause to handle the update without requiring a value for `link_to_major`, but this did not happen. The user is unsure why the `NOT NULL` constraint is being enforced during the `ON CONFLICT` update, even though the column has a value in the existing row.", "error_sql": ["INSERT INTO member(member_id, first_name, last_name) VALUES ('new_member_id', 'John', 'Doe') ON CONFLICT (member_id) DO UPDATE SET first_name=excluded.first_name, last_name=excluded.last_name;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 150, "selected_database": "student_club", "query": "I have a table called `event` that stores `event_id` and `event_date`. I want to grab the most recent 'streak' for an event with a given name. A 'streak' is the number of consecutive days that the event has occurred at least once. An event may occur more than once a day. Big gotcha: The streak should also take into account a given timezone. Given a query for 'April Meeting' in 'MST' timezone, I'd expect the streak to be: | Streak Count | Name | TimeZone | Start Date | End Date |. However, my current query is not working as expected and I'm not sure why. Here's the problematic SQL statement I used:", "error_sql": ["SELECT COUNT(*) AS streak_count, 'April Meeting' AS event_name, 'MST' AS timezone, MIN(event_date) AS start_date, MAX(event_date) AS end_date FROM attendance WHERE event_name = 'April Meeting' GROUP BY DATE_TRUNC('day', event_date AT TIME ZONE 'UTC' AT TIME ZONE 'MST') ORDER BY end_date DESC LIMIT 1;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 151, "selected_database": "formula_1", "query": "We have a table named 'pitstops' that stores pit stop data for Formula 1 races, including a column 'transaction_timestamp' which records the timestamp of each pit stop in nanoseconds. We need to group and count the number of pit stops by day. We attempted to convert the nanosecond timestamp to milliseconds and then use DATE_TRUNC to group by day, but encountered errors in our SQL queries.", "error_sql": ["SELECT DATE_TRUNC('day', to_timestamp(transaction_timestamp / 1000000000.0)), COUNT(*) FROM pitstops GROUP BY DATE_TRUNC('day', transaction_timestamp)"], "sol_sql": [], "preprocess_sql": ["ALTER TABLE pitstops ADD COLUMN transaction_timestamp bigint;", "UPDATE pitstops SET transaction_timestamp = EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000000000 + (random() * 1000000000)::bigint;"], "clean_up_sql": ["ALTER TABLE pitstops DROP COLUMN transaction_timestamp;"], "test_cases": []} {"instance_id": 152, "selected_database": "thrombosis_prediction", "query": "I am trying to obtain the laboratory test results for each patient where the values of 'got' and 'gpt' at the minimum end_date are equal to the values of 'got' and 'gpt' at the maximum end_date, grouped by patient id. My current query only obtains the laboratory test results from the maximum end_date for each patient, but I need the row minimum end_date where 'got' and 'gpt 'match the 'got' and 'gpt' in the maximum end_date, grouped by patient id.", "error_sql": ["select a.id, a.date, a.got, a.gpt from laboratory as a inner join ( select id, max(date) as date from laboratory group by id ) as b on a.id = b.id and a.date = b.date order by id, date"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 153, "selected_database": "formula_1", "query": "In the Formula 1 database, we need to generate a report that lists the financial roles associated with each race based on the roles of the constructors in that race. Each race can have multiple constructors, and each constructor can have multiple roles such as 'AR (Customer Billing)', 'AP (Commander)', and 'AP (Agent)'. The roles are determined by the constructor's performance and participation in the race. The issue arises when a constructor has multiple roles in a race, and the query only considers the first true value, ignoring the others. We need to ensure that all roles for each constructor in a race are considered and listed in the report.", "error_sql": ["WITH constructor_roles AS ( SELECT 18 race_id, 1 constructor_id, false customer_billing, true commander, true agent UNION ALL SELECT 18, 2, true, false, false ) SELECT n.race_id, string_agg(distinct CASE WHEN n.customer_billing = TRUE THEN 'AR (Customer Billing)' WHEN n.commander = TRUE THEN 'AP (Commander)' WHEN n.agent = TRUE THEN 'AP (Agent)' ELSE NULL END, ', ') AS finance FROM constructor_roles n WHERE n.race_id = 18 AND (n.customer_billing = TRUE or n.commander = TRUE or n.agent = TRUE) GROUP BY race_id"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 154, "selected_database": "california_schools", "query": "A school district is analyzing the academic performance of students across different years and classes. They have a database with tables that track students, the years they attended, and the classes they took. The district wants to generate a report that lists each student's first name along with the years they attended and the classes they took in each year. The current query is producing duplicate entries for years when a student takes multiple classes in the same year. The goal is to merge these entries so that each year appears only once with all the classes listed under it.", "error_sql": ["SELECT s.firstName, jsonb_agg(DISTINCT jsonb_build_object('yearId', y.id, 'classes', (SELECT jsonb_agg(jsonb_build_object('classId', c.id)) FROM classes AS c WHERE y.id = cy.yearId AND c.id = cy.classId AND s.id = cys.studentId))) AS years FROM users3 AS s LEFT JOIN classYearStudents AS cys ON cys.studentId = s.id LEFT JOIN classYears AS cy ON cy.id = cys.classYearId LEFT JOIN years AS y ON y.id = cy.yearId GROUP BY s.id order by s.id"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE users3 (id SERIAL PRIMARY KEY, firstName TEXT);", "CREATE TABLE years (id UUID PRIMARY KEY);", "CREATE TABLE classes (id UUID PRIMARY KEY);", "CREATE TABLE classYears (id SERIAL PRIMARY KEY, yearId UUID, classId UUID);", "CREATE TABLE classYearStudents (id SERIAL PRIMARY KEY, studentId INT, classYearId INT);", "INSERT INTO users3 (firstName) VALUES ('Jarrell'), ('Kevon'), ('Antone');", "INSERT INTO years (id) VALUES ('bd5b69ac-6638-4d3e-8a52-94c24ed9a039'), ('7f5789b5-999e-45e4-aba4-9f45b29a69ef');", "INSERT INTO classes (id) VALUES ('2590b596-e894-4af5-8ac5-68d109eee995'), ('fe4a11f2-5f38-4f7a-bbce-609bc7ad8f99'), ('c8cda7d1-7321-443c-b0ad-6d18451613b5');", "INSERT INTO classYears (yearId, classId) VALUES ('bd5b69ac-6638-4d3e-8a52-94c24ed9a039', '2590b596-e894-4af5-8ac5-68d109eee995'), ('bd5b69ac-6638-4d3e-8a52-94c24ed9a039', 'fe4a11f2-5f38-4f7a-bbce-609bc7ad8f99'), ('7f5789b5-999e-45e4-aba4-9f45b29a69ef', 'c8cda7d1-7321-443c-b0ad-6d18451613b5');", "INSERT INTO classYearStudents (studentId, classYearId) VALUES (1, 1), (1, 2), (2, 3), (2, 1), (2, 2), (3, 3), (3, 1), (3, 2);"], "clean_up_sql": ["DROP TABLE users3;", "DROP TABLE years;", "DROP TABLE classes;", "DROP TABLE classYears;", "DROP TABLE classYearStudents;"], "test_cases": []} {"instance_id": 155, "selected_database": "thrombosis_prediction", "query": "In the thrombosis_prediction database, there is a need to analyze the hierarchy of medical staff within the hospital. Each staff member has an employeeid, a bossid, and a salary. The hierarchy is already established, and each staff member can have direct and indirect managers. The task is to find, for each staff member, the lowest-ranked indirect manager in the hierarchy who earns at least twice as much as the staff member. I has attempted to create a recursive CTE to establish the hierarchy but is struggling to find the correct indirect manager based on the salary condition. The user's query is provided below and is producing incorrect results. In the final result, I need the employeeId, employeeSalary, hierarchical_level, bossId, bossSalary where the boss is the first one whose salary is at least twice as much as the employee.", "error_sql": ["WITH RECURSIVE EmpMgrCTE AS (SELECT id, bossid, salary, 0 as EmployeeLevel FROM staff WHERE bossid IS NULL UNION ALL SELECT emp.id, emp.bossid, emp.salary, mgr.EmployeeLevel + 1 as EmployeeLevel FROM staff emp INNER JOIN EmpMgrCTE mgr ON emp.bossid = mgr.id) SELECT * FROM EmpMgrCTE emp"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE staff (id bigint PRIMARY KEY, bossid bigint, salary int);", "INSERT INTO staff (id, bossid, salary) VALUES (20, NULL, 10000), (10, 20, 4500), (50, 10, 3000), (70, 10, 1500), (40, 50, 1500), (60, 70, 2000), (30, 50, 1501);"], "clean_up_sql": ["DROP TABLE staff;"], "test_cases": []} {"instance_id": 156, "selected_database": "card_games", "query": "In the card_games database, there is a table named 'cards' which contains various attributes of Magic: The Gathering cards. Each card has a unique identifier (id), a name, a converted mana cost (convertedmanacost), a rarity, and other attributes. For each rarity, I want to find the card with the highest converted mana cost, highest edhrecrank, and lowest multiverseid. For a single rarity, I can do it like this: sql select rarity, id from cards where rarity = 'uncommon' order by convertedmanacost desc nulls last, edhrecrank desc nulls last, multiverseid asc limit 1; but I haven't been able to make it for all rarities. So the output should be something like this: I am using PostgreSQL. Any idea how I should do this?", "error_sql": ["select rarity, id from cards order by convertedmanacost desc nulls last, edhrecrank desc nulls last, multiverseid asc limit 1;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 157, "selected_database": "financial", "query": "In the financial database, we have a scenario where each account must have at least one associated disposition (disp). However, when attempting to enforce this relationship, the following SQL query fails due to a chicken-egg problem. The user's attempt to create the tables and enforce the relationship is as follows:", "error_sql": ["DROP TABLE IF EXISTS card, account, disp; CREATE TABLE account (account_id INT PRIMARY KEY NOT NULL, district_id INT NOT NULL, frequency TEXT NOT NULL, date DATE NOT NULL, disp_id INT NOT NULL, FOREIGN KEY (disp_id) REFERENCES disp(disp_id) ON UPDATE CASCADE ON DELETE CASCADE); CREATE TABLE disp (disp_id INT PRIMARY KEY NOT NULL, client_id INT NOT NULL, account_id INT NOT NULL, type TEXT NOT NULL, FOREIGN KEY (account_id) REFERENCES account(account_id) ON UPDATE CASCADE ON DELETE CASCADE);"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 158, "selected_database": "financial", "query": "In the financial database, I am trying to aggregate client information into a array, but I am encountering an issue where the array contains a null value as `[null]` instead of an empty array when there are no qualifying rows. I am using PostgreSQL and have tried using `COALESCE` to replace null values, but it doesn't seem to work as expected. Here is the problematic SQL query I used:", "error_sql": ["SELECT COALESCE(json_agg(CASE WHEN client.client_id IS NULL THEN NULL ELSE json_build_object('client_id', client.client_id, 'gender', client.gender, 'birth_date', client.birth_date) END), '[]') AS AS clients FROM client;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 159, "selected_database": "debit_card_specializing", "query": "In the debit_card_specializing database, we have a table named transactions_1k that records all transactions made by customers at various gas stations. Each transaction includes details such as the date, time, customer ID, card ID, gas station ID, product ID, amount, and price. We have noticed that there are duplicate transactions in the table, where the same transaction (based on card ID, gas station ID, product ID) appears multiple times with different transaction IDs. Specifically, we want to identify and delete the duplicate transactions where the product ID is 5 (Natural) and keep the ones where the product ID is 2 (Nafta). However, our current query is only selecting the transactions with product ID 5.", "error_sql": ["\nselect * from transactions_1k e\nwhere exists\n ( select * from transactions_1k e2 \n where e.date=e2.date and e.time=e2.time \n and e.cardid=e2.cardid \n and e.gasstationid=e2.gasstationid \n and e.productid='2' and e2.productid='5') order by e.date asc;\n"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 160, "selected_database": "financial", "query": "I have a table named \"transfer\" under the database \"financial\". The customer id and their transfer amount columns are given, Cum.sum and Bucket columns we need to find using postgresql. To Find cumulative sum , i can write sum(amount) over (order by id rows between unbounded preceding and current row) . But ask is reset cum.sum if amount reach threshold amount. For example threshold amount is 20 and sum of the row 1,2 and 3 values are 23 which is greater than 20 . so we reset the window function. The next threshold value calculate from id 4 onwards. How to write Postgresql code to implement these functions?", "error_sql": ["\nselect id, amount as cum_sum, 1 as bucket from transfer where id = 1 union all select transfer.id, (case when cum_sum + amount > 20 then amount else cum_sum + amount end), (case when cum_sum + amount > 20 then bucket + 1 else bucket end) from cte join transfer on transfer.id = cte.id + 1\n"], "sol_sql": [], "preprocess_sql": ["\nCREATE TABLE transfer (\n id INT,\n amount INT\n);\n\nINSERT INTO transfer (id, amount)\nVALUES\n(1, 11),\n(2, 6),\n(3, 6),\n(4, 6),\n(5, 13),\n(6, 6),\n(7, 15),\n(8, 6),\n(9, 19),\n(10, 10);\n"], "clean_up_sql": ["drop table if exists transfer;"], "test_cases": []} {"instance_id": 161, "selected_database": "formula_1", "query": "In the Formula 1 database, we have a table named 'results' that contains various performance metrics for each driver in each race. We are interested in analyzing the modal value of certain performance metrics (laps) for each race. The modal value is the most frequent value in a data set, and if there are multiple equally frequent values, we want to return the one that occurs first in the data set. For example, if in a race, the laps completed by drivers are [10, 10, 20, 20, 30], the modal value should be 10 because it occurs first among the most frequent values. We need to calculate the modal value for each race based on the laps columns and return the result along with the raceid.", "error_sql": ["SELECT raceid mode() within group(order by laps) as modal_laps FROM results;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 162, "selected_database": "card_games", "query": "In the card_games database, I want to run two tests: 1. Identify tables in the 'public' schema that are not listed in the 'required_tables' table. 2. Identify tables listed in the 'required_tables' table that are not present in the 'cards_schema' schema. For the first test, I use the following query which works correctly:\\nsql \\\\/* First Query *\\\\/\\nselect t1.table_name as t1_table_name, t2.table_name as t2_extra_tables_in_schema \\\\/nfrom required_tables t1 \\\\/nright join information_schema.tables t2 \\\\/non t1.table_name = t2.table_name \\\\/nwhere t2.table_schema='public' \\\\/nand t1.table_name IS NULL \\\\/n\\nHowever, for the second test, when I try the following query (the equivalent to the first query but with a left join this time):\\nsql \\\\/* Second Query *\\\\/\\nselect t1.table_name as t1_tables_missing_from_schema, t2.table_name from required_tables t1 left join information_schema.tables t2 on t1.table_name = t2.table_name where t2.table_schema='public' and t2.table_name IS NULL; \\\\/n\\nI always get zero results, even though I know that there are some tables in required_tables which is not in the 'public' schema. How do I get around this issue? Can you provide me with a way to get both missing results in a single query (maybe somehow with a full outer join is my guess), the results should include two colums: 'kind' (WHEN required_tables.table_name IS NULL THEN 'extra' ELSE 'missing') and the corresponding 'table_name'?", "error_sql": ["select t1.table_name as t1_table_name, t2.table_name as t2_extra_tables_in_schema from required_tables t1 right join information_schema.tables t2 on t1.table_name = t2.table_name where t2.table_schema='public' and t1.table_name IS NULL;", "select t1.table_name as t1_tables_missing_from_schema, t2.table_name from required_tables t1 left join information_schema.tables t2 on t1.table_name = t2.table_name where t2.table_schema='public' and t2.table_name IS NULL;"], "sol_sql": [], "preprocess_sql": ["CREATE SCHEMA IF NOT EXISTS cards_schema; CREATE TABLE IF NOT EXISTS required_tables (table_name name PRIMARY KEY); INSERT INTO required_tables (table_name) VALUES ('cards'), ('foreign_data'), ('rulings'), ('sets'), ('price'), ('source');"], "clean_up_sql": ["DROP TABLE IF EXISTS required_tables CASCADE;"], "test_cases": []} {"instance_id": 163, "selected_database": "european_football_2", "query": "In the context of the 'european_football_2' database, we are managing a graph-like structure to represent football matches and their dependencies. Each match is a node, and the dependencies between matches (such as follow-up matches or related matches) are represented as edges. The match table has id as the primary key and a unique constraint on (id, stage). The dependency table references both id and stage from the match table for match1 and match2.The business requirement is that whenever a match's stage changes, its dependencies need to be re-evaluated and possibly updated. To handle this, we have a 'match' table and a 'dependency' table. The 'match' table includes a stage number to track changes, and the 'dependency' table references the 'match' table using the match ID and stage number. However, when we try to update the version of a match, we encounter an error due to foreign key constraints ('dependency_match1_stage1_fkey' and 'dependency_match2_stage2_fkey'). We need to find a way to update the stage number (the stage number of match1 incresed by 1) and automatically handle the dependencies without starting a transaction manually.", "error_sql": ["update match set stage = stage + 1 where id = 'match1';"], "sol_sql": [], "preprocess_sql": ["drop table if exists dependency;", "drop table if exists match;", "create table match (id varchar(32), stage int not null default 1, status varchar(32), primary key (id), unique (id, stage));", "create table dependency (match1 varchar(32) not null, stage1 int not null, match2 varchar(32) not null, stage2 int not null, constraint normalize check (match1 < match2), foreign key (match1, stage1) references match (id, stage) on delete cascade, foreign key (match2, stage2) references match (id, stage) on delete cascade, primary key (match1, match2));", "insert into match (id, stage, status) values ('match1', 1, 'Scheduled'), ('match2', 2, 'Scheduled');", "insert into dependency (match1, stage1, match2, stage2) values ('match1', 1, 'match2', 2);"], "clean_up_sql": ["drop table if exists dependency;", "drop table if exists match;"], "test_cases": []} {"instance_id": 164, "selected_database": "superhero", "query": "Suppose we have a superhero event schedule where each superhero is scheduled to perform at different events. We have a table `superhero_events` that records the start and end times of these events. We want to retrieve a list of events that: Started within the last 3 days (inclusive) and end before 5 hours into the future (exclusive). The results should be ordered so that events that started in the past appear first, followed by events that start in the future. We can do something like the following query, but it is slow and needs optimization. Is there a way to use indexes to make this faster?", "error_sql": ["DROP INDEX IF EXISTS idx_a;", "SELECT * from superhero_events WHERE start_time >= Now()::timestamp - INTERVAL '3 days' AND end_time < now()+'5 hours'::interval ORDER BY CASE WHEN now()+'5 hours'::interval > Now()::timestamp AND start_time < Now()::timestamp THEN 1 WHEN start_time < Now()::timestamp THEN 2 ELSE 3 END;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE superhero_events (hero_id bigint NOT NULL, start_time timestamp without time zone NOT NULL, end_time timestamp without time zone NOT NULL);", "ALTER TABLE superhero_events ADD COLUMN event_id SERIAL PRIMARY KEY;", "ALTER TABLE superhero_events ADD CONSTRAINT chk_time_order CHECK (start_time < end_time);", "INSERT INTO superhero_events (hero_id, start_time, end_time) SELECT s.id, NOW() - INTERVAL '1 hour' * (random()+0.5), NOW() + INTERVAL '1 hour' * (random()+0.5) FROM superhero s ORDER BY random() LIMIT 250;", "INSERT INTO superhero_events (hero_id, start_time, end_time) SELECT s.id, NOW() + INTERVAL '5 hour' * (random()+0.5), NOW() + INTERVAL '5 hour' * (random()+0.5) + INTERVAL '2 hour' * (random()+0.5) FROM superhero s ORDER BY random() LIMIT 500;", "INSERT INTO superhero_events (hero_id, start_time, end_time) SELECT s.id, NOW() - INTERVAL '3 day' * (random()+0.5), (NOW() - INTERVAL '3 day' * (random()+0.5)) + INTERVAL '3 hour' * (random()+0.5) FROM superhero s ORDER BY random() LIMIT 1500;", "INSERT INTO superhero_events (hero_id, start_time, end_time) SELECT s.id, NOW() - INTERVAL '15 day' * (random()+0.5) - INTERVAL '3 day', (NOW() - INTERVAL '15 day' * (random()+0.5) - INTERVAL '3 day') + INTERVAL '4 hour' * (random()+0.5) FROM superhero s ORDER BY random() LIMIT 2750;"], "clean_up_sql": ["DROP TABLE IF EXISTS superhero_events;"], "test_cases": [], "efficiency": true} {"instance_id": 165, "selected_database": "california_schools", "query": "In the context of analyzing superhero attributes, I have a table ordered by the `hero_id` column. I aim to perform an aggregation on `n` rows at a time but also wish to incorporate the previous `k` and the next `k'` rows as context. For instance, considering the `hero_attribute` table with data ordered by `hero_id`, I want to aggregate `n` rows with overlapping context from adjacent rows. An example query to get the sum of `attribute_value` for `n=2` would group the rows into `[1, 2]`, `[3, 4]`, `[5, 6]` based on `(hero_id-1) / 2`. However, achieving overlapping groups, say with `k = k' = 2`, to get groups like `[1, 2, 3, 4]`, `[1, 2, 3, 4, 5, 6]`, `[3, 4, 5, 6]` based on `attribute_value`, proves challenging. Is there a way to accomplish this in PostgreSQL using `group by` or window functions? The output should contain only one column 'sum', which stores the three aggregation values of group `[1, 2, 3, 4]`, `[1, 2, 3, 4, 5, 6]` and `[3, 4, 5, 6]`.", "error_sql": ["with hero_attribute(hero_id, attribute_id, attribute_value) as ( values (1, 1, 80), (2, 1, 75), (3, 1, 95), (4, 1, 85), (5, 1, 90), (6, 1, 70) ) select sum(attribute_value) from hero_attribute group by (hero_id-1) / 2;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 166, "selected_database": "european_football_2", "query": "In the database 'european_football_2', there is a table named 'players' that stores information about football players, including their skills in different areas of the game. Each player has a unique ID, a name, and a array of skills where each skill has a unique skill ID and a description. The task is to retrieve a list of players along with their skills in a specific format, where each player only has a single row, and their skills are represented as an array of skill descriptions. For example, (1, Alice, ['Passing', 'Shooting']). If a player has no skills, their skill array should be empty. The user attempted to write a query to achieve this but encountered issues with duplicate rows and missing entries for players with no skills.", "error_sql": ["select id, name, d ->> 'description' as skill from player_skills, json_array_elements(skills) as d;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE player_skills (id INT PRIMARY KEY, name TEXT, skills JSON);", "INSERT INTO player_skills (id, name, skills) VALUES (1, 'Alice', '[{\"id\": 11, \"description\": \"Passing\"}, {\"id\": 13, \"description\": \"Shooting\"}]'::json), (2, 'Bob', '[{\"id\": 10, \"description\": \"Defending\"}, {\"id\": 9, \"description\": \"Tackling\"}]'::json), (3, 'Sam', '[]'::json);"], "clean_up_sql": ["DROP TABLE player_skills;"], "test_cases": [], "external_data": "{\"id\": 11, \"description\": \"Passing\"}, {\"id\": 13, \"description\": \"Shooting\"}, {\"id\": 10, \"description\": \"Defending\"}, {\"id\": 9, \"description\": \"Tackling\"}"} {"instance_id": 167, "selected_database": "european_football_2", "query": "The database contains a table named 'match_events' with a column 'events' that stores JSON arrays of event objects for each football match. Each event object includes an 'id' and 'description'. The task is to extract all event objects with 'id' equal to 2 from each match record. The user attempted to achieve this using a CASE statement but encountered issues when the number of events in a match exceeded the hardcoded indices in the query. Can you write a sql query without using 'WHERE' or 'HAVING' clause - only inside 'SELECT' without relying on indices?", "error_sql": ["SELECT CASE when (t.events::json->0->'id')::varchar::int = 2 then (t.events::json->0)::varchar when (t.events::json->1->'id')::varchar::int = 2 then (t.events::json->1)::varchar when (t.events::json->2->'id')::varchar::int = 2 then (t.events::json->2)::varchar else null::varchar end as \"result\" FROM match_events as t;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE match_events (match_id SERIAL PRIMARY KEY, events JSON);", "INSERT INTO match_events (events) VALUES ('[{\"id\": 1, \"description\": \"Goal\"}, {\"id\": 2, \"description\": \"Yellow Card\"}, {\"id\": 3, \"description\": \"Substitution\"}]'::json), ('[{\"id\": 1, \"description\": \"Goal\"}, {\"id\": 4, \"description\": \"Substitution\"}, {\"id\": 3, \"description\": \"Red Card\"}, {\"id\": 2, \"description\": \"Goal\"}]'::json);"], "clean_up_sql": ["DROP TABLE match_events;"], "test_cases": [], "external_data": "{\"id\": 1, \"description\": \"Goal\"}, {\"id\": 2, \"description\": \"Yellow Card\"}, {\"id\": 3, \"description\": \"Substitution\"}, {\"id\": 1, \"description\": \"Goal\"}, {\"id\": 4, \"description\": \"Substitution\"}, {\"id\": 3, \"description\": \"Red Card\"}, {\"id\": 2, \"description\": \"Goal\"}"} {"instance_id": 168, "selected_database": "thrombosis_prediction", "query": "In the context of a medical database, we have a table `examination` that records various tests and diagnoses for patients over time. Each record includes a patient ID, the date of examination, and several test results including `aCL IgG`, `aCL IgM`, `ANA`, and `aCL IgA`. We are interested in finding out how many times each test result occurs in each year between 1993 and 1996. Specifically, we want to count the occurrences of each `ANA Pattern` in each year, and then find the pattern with the highest count. Here is a query that attempts to do this but fails to return only the rows with the highest count of `ANA Pattern` per year. How to get only rows with the highest count of `ANA Pattern` per year between 1993 and 1996?", "error_sql": ["SELECT COUNT(\"ANA Pattern\") AS c, \"ANA Pattern\", EXTRACT(YEAR FROM \"Examination Date\") AS examination_year FROM examination WHERE EXTRACT(YEAR FROM \"Examination Date\") BETWEEN 1993 AND 1996 GROUP BY EXTRACT(YEAR FROM \"Examination Date\"), \"ANA Pattern\" ORDER BY examination_year, c DESC;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 169, "selected_database": "european_football_2", "query": "In the context of the 'european_football_2' database, a user is trying to generate a report that combines two parts: a list of players along with their birth year, ordered by the player's name, and a summary of the total number of players in each birth year, ordered by the count of players and the year. The user has two separate queries that work individually but when combined using UNION ALL, the order of the first part changes unexpectedly. The user wants to maintain the order of the first part when combined with the second part.", "error_sql": ["WITH player_names AS (SELECT 1 AS source, ROW_NUMBER() OVER (ORDER BY player_name) AS row_number, CONCAT(player_name, '(', LEFT(birthday, 4), ')') AS dest FROM player_table), birth_year_summary AS (SELECT 2 AS source, ROW_NUMBER() OVER (ORDER BY COUNT(*), LEFT(birthday, 4)) AS row_number, CONCAT('There are a total of ', COUNT(*), ' player', CASE WHEN COUNT(*) > 1 THEN 's' ELSE '' END, ' born in ', LEFT(birthday, 4), '.') AS dest FROM player_table GROUP BY LEFT(birthday, 4)) SELECT dest FROM (SELECT * FROM player_names UNION ALL SELECT * FROM birth_year_summary) AS combined_results ORDER BY ROW_NUM;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE player_table AS SELECT * FROM player ORDER BY RANDOM();"], "clean_up_sql": ["DROP TABLE player_table;"], "test_cases": []} {"instance_id": 170, "selected_database": "formula_1", "query": "In the Formula 1 database, I want to generate a report that lists each race along with the stops and ids of all constructors who participated in that race. However, when I use a query with two LEFT JOINs, I encounter duplicates in the constructor and stops. I need a solution to ensure that the constructor and stop are listed without duplicates while maintaining the correct aggregation of data. Particularly, I can't just add distinct to remove duplicates because duplicate name is allowed.", "error_sql": ["SELECT rs.raceId AS race_id, string_agg(constructorId::TEXT, ',' ORDER BY res.resultId) AS constructor_ids, string_agg(p.stop::TEXT, ', ' ORDER BY p.raceId) AS stops FROM races rs LEFT JOIN results res ON res.raceId = rs.raceId LEFT JOIN pitstops p ON rs.raceId = p.raceId GROUP BY rs.raceId"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 171, "selected_database": "formula_1", "query": "In the context of the 'formula_1' database, we have a scenario involving race routes and their events. The 'routes' table represents the race routes, and we have two additional tables, 'route_detail' and 'route_event', which track various events and their details for each route. The 'route_events' table contains records of events for each route, and the 'route_detail' table contains detailed information about each route. We need to find all routes with a specific status (e.g., status 5, which is stored in route_detail) but do not have an event of a certain type (e.g., type 3, which is stored in route_event). However, the provided SQL query does not correctly filter out the routes with the unwanted event type, leading to incorrect results.", "error_sql": ["SELECT r.id, r.start_day, r.end_day, de.point_of_delivery_plant_name, de.point_of_delivery_plant_number, de.visit_status FROM route r JOIN route_detail de ON de.route_id = r.id WHERE NOT EXISTS (SELECT 1 FROM route ro JOIN route_detail rd ON rd.route_id = ro.id JOIN route_event ev ON ev.route_detail_id = rd.id WHERE rd.route_id = r.id AND ev.event_type !=3 AND rd.visit_status = '5' AND rd.id = de.id) AND de.visit_status = '5' GROUP BY 1,2,3,4,5,6 ORDER BY r.id;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE route(id INT, start_day DATE, end_day DATE);", "INSERT INTO route VALUES (1, '2023/05/01', '2023/05/07'), (2, '2023/05/01', '2023/05/07'), (3, '2023/05/01', '2023/05/07'), (4, '2023/05/01', '2023/05/07'), (5, '2023/05/01', '2023/05/07');", "CREATE TABLE route_detail(id INT, route_id INT, visit_status INT, point_of_delivery_plant_name VARCHAR(30), point_of_delivery_plant_number INT);", "INSERT INTO route_detail VALUES (1, 1, 5, 'CROP SOLUTIONS S.A.', 563), (2, 1, 5, 'CROP SOLUTIONS S.A.', 563), (3, 1, 5, 'CROP SOLUTIONS S.A.', 563), (4, 2, 0, 'SAMA S.A.', 781), (5, 3, 0, 'WALTER SAMA HARMS', 732), (6, 4, 5, 'AGROSER S.A.', 242), (7, 4, 5, 'AGROSER S.A.', 242), (8, 5, 5, 'AGROFERTIL S.A.', 287), (9, 5, 5, 'AGROFERTIL S.A.', 287), (10, 5, 5, 'AGROFERTIL S.A.', 287);", "CREATE TABLE route_event (id INT, route_detail_id INT, event_type INT, event_description VARCHAR(30));", "INSERT INTO route_event VALUES (50, 1, 1, 'start visit'), (51, 2, 2, 'recurrent form'), (52, 3, 3, 'end visit'), (53, 4, 1, 'start visit'), (54, 5, 1, 'start visit'), (55, 6, 1, 'start visit'), (56, 7, 2, 'recurrent form'), (57, 8, 1, 'start visit'), (58, 9, 2, 'recurrent form'), (59, 10, 4, 'harvest advance')"], "clean_up_sql": ["DROP TABLE route_event;", "DROP TABLE route;", "DROP TABLE route_detail;"], "test_cases": []} {"instance_id": 172, "selected_database": "european_football_2", "query": "We are managing a database for a football analytics platform where we track the attributes of teams over time. Each record in the 'team_attributes' table represents the attributes of a team on a specific date. We need to ensure that the 'date' field of each record is correctly associated with an 'eff_to' field, which indicates the date just before the next record for the same team. If there is no subsequent record for the team, 'eff_to' should be set to '5999-12-31'. We are trying to automate this process using a trigger function that updates the 'eff_to' field whenever a new record is inserted into the 'team_attributes' table. However, our current trigger function is incorrectly updating all 'eff_to' fields with the last 'date' value instead of calculating them individually for each team. We need to correct this issue to ensure accurate data representation.", "error_sql": ["CREATE OR REPLACE FUNCTION update_team_attributes_eff_to() RETURNS TRIGGER AS $$ BEGIN UPDATE team_attributes SET eff_to = subquery.next_date FROM ( SELECT COALESCE( LEAD(TO_TIMESTAMP(date, 'YYYY-MM-DD HH24:MI:SS')::DATE, 1) OVER ( ORDER BY TO_TIMESTAMP(date, 'YYYY-MM-DD HH24:MI:SS')::DATE DESC), TO_DATE('6000-00-00', 'YYYY-MM-DD') ) - 1 AS next_date FROM team_attributes ) AS subquery; RETURN NULL; END; $$ LANGUAGE plpgsql; CREATE OR REPLACE TRIGGER after_insert_team_attributes AFTER INSERT ON team_attributes FOR EACH ROW EXECUTE PROCEDURE update_team_attributes_eff_to();"], "sol_sql": [], "preprocess_sql": ["ALTER TABLE team_attributes ADD COLUMN eff_to DATE;"], "clean_up_sql": ["ALTER TABLE team_attributes DROP COLUMN eff_to;"], "test_cases": []} {"instance_id": 173, "selected_database": "formula_1", "query": "In the Formula 1 database, I need to analyze the results of a specific race to identify the drivers who finished in the same position across multiple races, excluding the driver with the highest driver ID in each group. For example, if drivers 5 and 9 both finished in 3rd place in different races, and drivers 8, 12, and 13 all finished in 2nd place in different races, I want to exclude the driver with the highest ID in each group and get the remaining driver IDs. The final result should be a list of driver IDs excluding the highest ID in each group of drivers who finished in the same position across multiple races.", "error_sql": ["select position, array_agg(driverid) as driverids from results group by position having COUNT(*)>1 order by position"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 174, "selected_database": "superhero", "query": "In the superhero2 database, we have a representation of a (binary) tree where each superhero2 is a node, and each node has a parent column and a color column. The color column represents the color of the superhero2's costume. The leaf nodes (superheroes without children) have a color (their color column is not null and can be either green or red). The goal is to color the whole tree based on the following rules: If a parent has one child, then the parent's color is the child's color. If a parent has two children and both have the same color, then the parent color is its children's color. If a parent has two children and they have different colors, then the parent color is gray. The id and parent id are text and (their length - 1) is the their depth, for example, 'A' is the root node and 'AB' is the child and 'ABC' is the child of 'AB'. The id represents the path from the root to the node. If the leaf node is 'ABDE', then the path is 'A', 'AB', 'ABD', 'ABDE'. How can I write a recursive query in PostgreSQL for this algorithm?", "error_sql": ["WITH RECURSIVE cte AS ( SELECT id, parent_id, color FROM superhero2 WHERE parent_id IS NULL UNION ALL SELECT s.id, s.parent_id, CASE WHEN c1.color IS NULL THEN c2.color WHEN c2.color IS NULL THEN c1.color WHEN c1.color = c2.color THEN c1.color ELSE 'gray' END AS color FROM superhero2 s LEFT JOIN cte c1 ON s.id = c1.parent_id LEFT JOIN cte c2 ON s.id = c2.parent_id ) UPDATE superhero2 SET color = cte.color FROM cte WHERE superhero2.id = cte.id"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE superhero2 ( id text NOT NULL, parent_id text NULL, color text NULL, PRIMARY KEY (id) );", "INSERT INTO superhero2 (parent_id, id, color) VALUES (null, 'A', null), ('A', 'AB', null), ('A', 'AC', null), ('AB', 'ABD', null), ('ABD', 'ABDE', 'green'), ('AC', 'ACF', null), ('AC', 'ACG', null), ('ACF', 'ACFH', 'red'), ('ACF', 'ACFI', 'green'), ('ACG', 'ACGJ', 'red'), ('ACG', 'ACGK', 'red');"], "clean_up_sql": ["DROP TABLE IF EXISTS superhero2;"], "test_cases": []} {"instance_id": 175, "selected_database": "superhero", "query": "We need to count the occurrences of specific superheroes in two different datasets: one dataset includes superheroes with a specific gender, and the other includes superheroes with a specific alignment. We want to return a single result set that includes the counts of these superheroes from both datasets. The challenge is to ensure that the query is optimized and that the database planner can effectively use indexes to speed up the query. The user encountered an issue where applying the filter condition after the join operation prevented the planner from using indexes, leading to a suboptimal execution plan. The user wants to avoid manually applying the filter condition to each joined table to maintain query simplicity and performance.", "error_sql": ["SELECT * \nFROM (\n SELECT gender_id, COUNT(*) as cnt1 \n FROM superhero \n WHERE gender_id IN (1, 2) \n GROUP BY gender_id\n) AS c1\nFULL OUTER JOIN (\n SELECT alignment_id, COUNT(*) as cnt2 \n FROM superhero \n WHERE alignment_id IN (1, 2) \n GROUP BY alignment_id\n) AS c2\nON c1.gender_id = c2.alignment_id\nWHERE c1.gender_id IN (1,2) AND c2.alignment_id IN (1,2);"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": [], "efficiency": true} {"instance_id": 176, "selected_database": "card_games", "query": "In the context of a card games database, I have a table named 'cards' that tracks each card's details, including its artist, name, and set code. Each card can belong to multiple sets, and each set can contain multiple cards. I want to generate a list of artists with the most cards in the database. However, for a comprehensive view, I need to list all sets and the count of cards per set for each artist, alongside the set with the highest number of cards. I'm not interested in artists with only one card. The result should be ordered by the artist with the most cards first, followed by the rest of the sets for the same artist, and so on. Here's the SQL query I tried, but it doesn't fully meet my requirements:", "error_sql": ["SELECT artist, setcode, COUNT(setcode) AS counter FROM cards GROUP BY setcode, artist HAVING COUNT(setcode) > 1 ORDER BY counter DESC;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 177, "selected_database": "european_football_2", "query": "In the context of the 'european_football_2' database, we have a table that tracks the lineup changes between consecutive matches for football teams. Each row in the table represents a match, and it includes the match ID, the player IDs in the current lineup, and the player IDs in the next lineup. We need to count the number of players who are scheduled to play in the next match and are already in the current lineup. For example, if a player is listed twice in the current lineup and once in the next lineup, they should be counted only once. The user attempted to write a query to achieve this but encountered issues with the logic and syntax.", "error_sql": ["SELECT match_id, current_lineup, next_lineup, (SELECT COUNT(case when arr=matches then matches end) FROM unnest(current_lineup) arr CROSS JOIN unnest(next_lineup) matches WHERE arr IS NOT NULL AND matches IS NOT NULL ) FROM match_lineups;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE match_lineups (match_id Integer PRIMARY KEY, current_lineup Integer[], next_lineup Integer[]); INSERT INTO match_lineups(match_id, current_lineup, next_lineup) VALUES (101, '{1, 2, 3, 4}', '{2, 4, 5}'); INSERT INTO match_lineups(match_id, current_lineup, next_lineup) VALUES (102, '{1, 3, 5, 6}', '{3, 5, 5, 7}');"], "clean_up_sql": ["DROP TABLE match_lineups;"], "test_cases": []} {"instance_id": 178, "selected_database": "formula_1", "query": "I have a table called circuit_json that contains details about Formula 1 circuits. The table has a column named circuit_id_name, which stores JSON data with information about circuit IDs and their corresponding names. I am trying to extract the circuit ID and name into separate columns for better readability. Here is my attempt and the query I used:", "error_sql": ["SELECT * \nFROM jsonb_to_record(circuit_id_name) AS x(circuitid int, name text) \nFROM circuit_json;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE circuit_json AS SELECT json_build_object('circuitid', circuitid, 'name', name) as circuit_id_name FROM circuits;"], "clean_up_sql": ["DROP TABLE circuit_json;"], "test_cases": []} {"instance_id": 179, "selected_database": "superhero", "query": "We have a table `hero_attribute` that stores the attribute values of superheroes. Each superhero can have multiple attributes, such as Intelligence, Strength, and Speed. The data in `hero_attribute` includes the `hero_id`, `attribute_id`, and `attribute_value`. We want to insert this data into another table `hero_attribute_bifurcation` where each attribute value greater than 50 is split into multiple rows of 50 and the remaining amount (if any) is inserted as a separate row. The new table `hero_attribute_bifurcation` should include the columns `hero_id`, `attribute_id`, `attribute_value`, and `is_bifurcated` indicating whether the attribute value was split (1) or not (0). The inserted data set should reflect this bifurcation logic.", "error_sql": ["INSERT INTO hero_attribute_bifurcation (hero_id, attribute_id, attribute_chunk, is_bifurcated)\nSELECT \n hero_id, \n attribute_id, \n attribute_value, \n CAST(attribute_value > 100 AS integer) AS is_bifurcated\nFROM hero_attribute;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE hero_attribute_bifurcation (hero_id bigint, attribute_id bigint, attribute_chunk bigint, is_bifurcated integer);"], "clean_up_sql": ["DROP TABLE hero_attribute_bifurcation;"], "test_cases": []} {"instance_id": 180, "selected_database": "financial", "query": "I need to get a list of all districts from the account table. For each district, I want two arrays of loan IDs from the loan table. The first array should include loan IDs where the status is either 'A' or 'B', and the second array should include loan IDs where the status is 'C'. The results should be grouped by district_id and ordered by district_id.", "error_sql": ["SELECT y.district_id,\n CASE WHEN y.status IN ('A', 'B') THEN array_agg(loan_id) END AS type_A_B,\n CASE WHEN y.status = 'C' THEN array_agg(loan_id) END AS type_C\nFROM (\n SELECT x.district_id, l.loan_id, l.status\n FROM loan l\n JOIN account x ON l.account_id = x.account_id\n) y\nGROUP BY 1, y.status\nORDER BY 1;"], "sol_sql": [], "preprocess_sql": [""], "clean_up_sql": [""], "test_cases": []} {"instance_id": 181, "selected_database": "superhero", "query": "In the superhero database, we have a timeseries of superhero activities recorded at 5-minute intervals. Each activity is associated with a specific superhero and an activity code. We need to aggregate these activities so that consecutive activities (over several continuous intervals) by the same superhero with the same activity code are grouped together, and the interval is summed up. The goal is to produce a list of valid intervals for each superhero and activity code combination.", "error_sql": ["SELECT ts, superhero_id, activity_code, LEAD(ts) OVER (PARTITION BY superhero_id, activity_code ORDER BY ts) as next_ts FROM superhero_activities"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE superhero_activities ( ts timestamptz, activity_code bigint, superhero_id bigint );", "INSERT INTO superhero_activities VALUES ('2023-03-01 12:00:00', 1, 1), ('2023-03-01 12:05:00', 1, 1), ('2023-03-01 12:10:00', 1, 1), ('2023-03-01 12:10:00', 2, 1), ('2023-03-01 12:25:00', 1, 1), ('2023-03-01 12:30:00', 1, 1), ('2023-03-01 12:00:00', 1, 2), ('2023-03-01 12:20:00', 1, 2), ('2023-03-01 12:20:00', 3, 2), ('2023-03-01 12:25:00', 3, 2);"], "clean_up_sql": ["DROP TABLE superhero_activities;"], "test_cases": []} {"instance_id": 182, "selected_database": "card_games", "query": "I am working on a project to analyze card game tournaments and their participants. I have three tables: 'card_players', 'card_matches', and 'tournaments'. The 'card_players' table contains information about the players, the 'card_matches' table contains information about the matches played, and the 'tournaments' table contains information about the tournaments. I want to count how many tournaments have had at least one match where a player of type 'Pro' has participated. However, if both players in a match are of type 'Pro', I only want to count one tournament. Here's a simplified SQL of my database schema and some seed data. The problematic SQL query I used is provided below, and it counts both players in a match as separate tournaments, which is incorrect. I need a corrected query that counts each tournament only once if there is at least one 'Pro' player in any match.", "error_sql": ["SELECT count(*) FROM card_matches INNER JOIN card_players ON card_matches.player1_id = card_players.id OR card_matches.player2_id = card_players.id WHERE card_players.type = 'Pro'"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE card_players (id bigint NOT NULL, name text NOT NULL, type text NOT NULL, PRIMARY KEY(id));", "CREATE TABLE card_matches (id bigint NOT NULL, tournament_id bigint NOT NULL, player1_id bigint NOT NULL, player2_id bigint NOT NULL, PRIMARY KEY(id));", "CREATE TABLE tournaments (id bigint NOT NULL, name text NOT NULL, PRIMARY KEY(id));", "INSERT INTO card_players (id, name, type) VALUES (1, 'Alice', 'Pro'), (2, 'Bob', 'Pro'), (3, 'Charlie', 'Amateur'), (4, 'David', 'Amateur');", "INSERT INTO tournaments (id, name) VALUES (1, 'Grand Prix'), (2, 'Pro Tour'), (3, 'Super Bowl');", "INSERT INTO card_matches (id, tournament_id, player1_id, player2_id) VALUES (1, 1, 1, 3), (2, 1, 2, 4), (3, 2, 1, 2), (4, 3, 3, 4), (5, 2, 3, 4);"], "clean_up_sql": ["DROP TABLE card_players;", "DROP TABLE card_matches;", "DROP TABLE tournaments;"], "test_cases": []} {"instance_id": 183, "selected_database": "european_football_2", "query": "In the context of the European Football database, I have a set of matches where each match has a related home team, away team, season, and date. Most matches have been played several times during a season. In some cases, several matches took place at the same day and in the same league. I'd like to have one group (a match series) for all matches that have been played together during one season in one specific league, something like this:\n| League ID | Season | Match IDs(a list of match ids) | Dates(a list of match dates)\nI've been doing the heavy lifting in Python, but the code is quite slow and involves lots of queries. I've been wondering if any of you has ideas to combine the matches in one (or a few) queries?\\nI have had no success doing this in Postgres so far.", "error_sql": ["WITH all_dates AS (SELECT league_id, season, ARRAY_AGG(DISTINCT id order by id) as match_ids, date AS match_date FROM match WHERE season IS NOT NULL AND league_id IS NOT NULL AND id is not null AND date IS NOT NULL GROUP BY league_id, season, date) SELECT DISTINCT league_id, season, match_ids, ARRAY_AGG(DISTINCT all_dates.match_date ORDER BY match_date) AS dates FROM all_dates GROUP BY season, league_id, match_ids order by league_id;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 184, "selected_database": "card_games", "query": "We have a dataset of card rulings in the 'ruling' table, where each ruling is associated with a unique card UUID. We need to transform this dataset into a format where each row represents a unique ruling id, and each column represents a different card UUID. The values in the cells should be the ruling text for that card. For each unique id, group all rules by card_uuid (e.g., card1, card2, card3). Assign a row number starting from 1 for each card_uuid grouping, and place the corresponding rule in the appropriate column. If a card_uuid doesn't have a rule for an id, insert NULL. The final output should have one row per id, with columns for each card_uuid and the corresponding rules or NULLs. The expected output should have ruling ids as rows and card UUIDs as columns, with ruling texts as the cell values. There are 3 uuids:'5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c' as card1, '56f4935b-f6c5-59b9-88bf-9bcce20247ce' as card2, '6d268c95-c176-5766-9a46-c14f739aba1c' as card3.\n The expected output is like | id | card1 ruling | card2 ruling | card3 ruling |\nHowever, when attempting to use the crosstab function, we encountered an error. Here is the problematic query we tried:", "error_sql": ["select * from crosstab ('select id, uuid, text from ruling order by 1,2') AS final_result(id int, uuid1 text, uuid2 text, uuid3 text);"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE ruling ( id integer, text text NULL, uuid text NULL);", "INSERT INTO ruling (id, text, uuid) VALUES (1, 'First ruling text', '5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c'), (2, 'Second ruling text', '56f4935b-f6c5-59b9-88bf-9bcce20247ce'), (2, 'Second ruling text 2', '56f4935b-f6c5-59b9-88bf-9bcce20247ce'), (2, 'Second ruling text 3', '56f4935b-f6c5-59b9-88bf-9bcce20247ce'), (3, 'Third ruling text', '6d268c95-c176-5766-9a46-c14f739aba1c');"], "clean_up_sql": ["DROP TABLE ruling;"], "test_cases": []} {"instance_id": 185, "selected_database": "card_games", "query": "\nIn the card_games database, there are two tables: cards_info and card_choice. The cards_info table contains information about various Magic: The Gathering cards, including their IDs and names. The card_choice table contains information about the customers' selections of different card types, including the card's ID and a JSONB field that lists the IDs of corresponding non-valid cards. These non-valid cards are the ones that a customer has deemed unsuitable or irrelevant to their selection, represented as an array of card IDs. The goal is to query the cards_info table and return the cards that are not listed in the non_valid_cards array for each card choice, based on the matching card_id.\n", "error_sql": ["\nSELECT c.* \nFROM cards_info c \nWHERE NOT EXISTS (\n SELECT 1 \n FROM card_choice cc \n WHERE cc.card_id = c.id \n AND c.id = ANY (cc.non_valid_cards)\n);\n\n"], "sol_sql": [], "preprocess_sql": ["\nCREATE TABLE cards_info (\n id SERIAL PRIMARY KEY,\n name VARCHAR(255) NOT NULL\n);\nINSERT INTO cards_info (id, name)\nVALUES\n (1, 'Ancestor`s Chosen'),\n (2, 'Angel of Mercy'),\n (3, 'Aven Cloudchaser');\n \nCREATE TABLE card_choice (\n id SERIAL PRIMARY KEY,\n card_id INT REFERENCES cards_info(id),\n non_valid_cards JSONB\n);\nINSERT INTO card_choice (id, card_id, non_valid_cards)\nVALUES\n (1, 1, '[1,3]'),\n (2, 3, '[1]'),\n (3, 2, '[2,3]');\n"], "clean_up_sql": ["DROP TABLE IF EXISTS cards_info; DROP TABLE IF EXISTS card_choice;"], "test_cases": [], "external_data": "(1, 1, '[1,3]'), (2, 3, '[1]'), (3, 2, '[2,3]');"} {"instance_id": 186, "selected_database": "card_games", "query": "\nI have a certain hierarchy of data in the card_type table, where each row represents a type of cards with a unique identifier (uuid), a type name (card_name), and a reference to its parent card through the parent_uuid. The data is structured in a way that cards can be grouped under parent cards, forming a tree-like hierarchy.\nI initially managed to create a recursive query that fetches the data, but the result isn't in the format I desire. The query correctly returns each card along with a list of parent uuids. However, instead of having the list of parent uuids, I would prefer to have a structured output where each parent card includes a list of its child cards (i.e., uuid and card_name).\nFor example, I want to convert the result into a structure where each parent card lists all its direct child cards grouped together, forming a tree-like structure. This would help me better visualize the hierarchy and relationships between the cards, with each parent card having an array of its children's uuid values.\nCan you guide me on how to achieve this transformation using SQL?\n", "error_sql": ["\nWITH RECURSIVE nodes AS (\n SELECT\n uuid,\n card_name AS name,\n ARRAY[]::uuid[] AS parents\n FROM card_type\n WHERE parent_uuid IS NULL\n\n UNION ALL\n\n SELECT\n c.uuid,\n c.card_name AS name,\n nodes.parents || c.uuid\n FROM card_type c\n JOIN nodes ON nodes.uuid = c.parent_uuid\n)\nSELECT * FROM nodes;\n"], "sol_sql": [], "preprocess_sql": ["\nCREATE TABLE card_type\n(\n uuid uuid NOT NULL PRIMARY KEY,\n card_name character varying(32),\n parent_uuid uuid REFERENCES card_type(uuid)\n);\n\nINSERT INTO card_type (uuid, card_name, parent_uuid) \nVALUES \n('8a70180b-3644-4b17-af5f-93cbe0090cce', 'Creature', null),\n('d9093660-241a-48f6-bf09-b6a8c6c7f12a', 'Human', '8a70180b-3644-4b17-af5f-93cbe0090cce'),\n('376ae1cb-425d-44d2-b19a-19b6f1e86314', 'Cleric', 'd9093660-241a-48f6-bf09-b6a8c6c7f12a'),\n('5d5f174a-5c8e-4d12-912f-8173e255e35a', 'Knight', 'd9093660-241a-48f6-bf09-b6a8c6c7f12a'),\n('f79f5fa0-6eaf-465b-9b14-e3b49c5ac9ef', 'Enchantment', null),\n('8aa95eda-7963-40ef-be44-076cdf06c5c1', 'Aura', 'f79f5fa0-6eaf-465b-9b14-e3b49c5ac9ef');\n"], "clean_up_sql": ["DROP TABLE IF EXISTS card_type;"], "test_cases": []} {"instance_id": 187, "selected_database": "student_club", "query": "In the context of the student_club database, we have two tables: `event` and `budget`. The `event` table contains information about various events, including their start dates and statuses. The `budget` table contains financial details related to these events, including the amount budgeted and the remaining budget. The user wants to know the average remaining budget and the number of events that are open or closed on a daily basis between '2020-01-01' and '2020-03-31'. The user attempted to write a query to achieve this, but it resulted in incorrect results or errors. Below is the problematic SQL statement the user used, followed by the corrected solution.", "error_sql": ["SELECT d.the_day AS \"Date\", COUNT(e.event_id) AS \"Number of Events\", AVG(b.remaining) AS \"Avg Remaining Budget\" FROM (SELECT ts::date AS the_day FROM generate_series (timestamp '2020-01-01', timestamp '2020-03-31', interval '1 day'::interval) ts) d LEFT JOIN \"event\" e ON e.event_date::date = d.the_day LEFT JOIN budget b ON b.link_to_event = e.event_id GROUP BY d.the_day ORDER BY d.the_day;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 188, "selected_database": "financial", "query": "I log the daily transactions of my bank accounts. Now I want to create a SQL statement to get the sum of transaction amounts for each month but separate columns for each year. I came up with the following SQL statement: sql SELECT LPAD(extract (month from trans.date)::text, 2, '0') as month, sum(trans.amount) as 1998 from trans WHERE trans.date >= '1998-01-01' and trans.date < '1999-01-01' group by month order by 1; This results in only getting the values from 1998: | month | a1998 | | -------- | -------------- | | 1 | 100 | | 2 | 358 | | 3 | 495 | How could I change the SQL statement to get new columns for each year? Is this even possible?", "error_sql": ["SELECT LPAD(extract (month from trans.date)::text, 2, '0') as month, sum(trans.amount) as a1997 from trans WHERE trans.date >= '1997-01-01' and trans.date < '1998-01-01' group by month order by 1;"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 189, "selected_database": "formula_1", "query": "I'm trying to run a query that will find circuits within a given distance of any of the selected locations. This is for a search result where users can select multiple locations to look around. My current approach is to use `ST_ClosestPoint` and pass in an array of `ST_Point` generated in PHP. Then I pass that string into `ST_Collect`. However, this doesn't work because it looks like `ST_ClosestPoint` doesn't like these mixed arguments. I have a `gist(coordinate::geography)` index on `circuits` which seems like it would be useful to use. What am I missing - is there a better way to do this, or is this a bad approach? Should I be performing the query each time with a different location?", "error_sql": ["SELECT * FROM circuits WHERE ST_DWithin(ST_SetSRID(ST_MakePoint(lng, lat), 4326)::geography, ST_ClosestPoint((ST_MakePoint(lng, lat), 4326)::geography, ST_Collect(Array[ST_SetSRID(ST_MakePoint(2.76083, 101.73800), 4326)::geography, ST_SetSRID(ST_MakePoint(26.03250, 50.51060), 4326)::geography])), 1000000, FALSE);"], "sol_sql": [], "preprocess_sql": ["CREATE EXTENSION postgis;"], "clean_up_sql": [], "test_cases": []} {"instance_id": 190, "selected_database": "formula_1", "query": "In the Formula 1 database, I have a results table currently containing around 400 million entries and the following query on it:\n\nThe query retrieves the top 10 result IDs for a specific driver or another driver, ordered by the result ID in descending order. The query works fine when filtering by a single driver ID, but it takes several minutes when filtering by two driver IDs, even if both drivers have a small number of results (e.g., 2 for the first driver and 57 for the second driver). The issue seems to be related to the combination of ORDER BY and LIMIT clauses.", "error_sql": ["SELECT resultid FROM results WHERE driverid = 3 OR driverid = 4 ORDER BY resultid DESC LIMIT 10"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": [], "efficiency": true} {"instance_id": 191, "selected_database": "card_games", "query": "In a multiplayer card game platform, when a player is misbehaving, their 'muted' status is set to true. Chat messages from muted players should be hidden from all other players except the muted player themselves to prevent them from noticing their muted status and creating new accounts. The platform uses PostgreSQL 14.2 and has the following tables: 'words_users', 'words_social', 'words_games', and 'words_chat'. The user has prepared a test case with two users, one of whom is muted, and a game where both users have exchanged messages. The user's current SQL function to retrieve chat messages does not filter out messages from muted players for other players. The user seeks to modify the SQL function to hide messages from muted players for everyone except the muted player themselves.", "error_sql": ["CREATE OR REPLACE FUNCTION words_get_chat(in_gid integer, in_social integer, in_sid text) RETURNS TABLE (out_mine integer, out_msg text) AS $func$ SELECT CASE WHEN c.uid = s.uid THEN 1 ELSE 0 END, c.msg FROM words_chat c JOIN words_games g USING (gid) JOIN words_social s ON s.uid IN (g.player1, g.player2) WHERE c.gid = in_gid AND s.social = in_social AND s.sid = in_sid ORDER BY c.CREATED ASC; $func$ LANGUAGE sql;", "SELECT words_get_chat(10, 100, 'abc') AS nice_user;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE words_users (uid SERIAL PRIMARY KEY, muted BOOLEAN NOT NULL DEFAULT false);", "CREATE TABLE words_social (sid text NOT NULL CHECK (sid ~ '\\S'), social integer NOT NULL CHECK (0 < social AND social <= 256), given text NOT NULL CHECK (given ~ '\\S'), uid integer NOT NULL REFERENCES words_users ON DELETE CASCADE, PRIMARY KEY(sid, social));", "CREATE TABLE words_games (gid SERIAL PRIMARY KEY, player1 integer REFERENCES words_users(uid) ON DELETE CASCADE NOT NULL CHECK (player1 <> player2), player2 integer REFERENCES words_users(uid) ON DELETE CASCADE);", "CREATE TABLE words_chat (cid BIGSERIAL PRIMARY KEY, created timestamptz NOT NULL, gid integer NOT NULL REFERENCES words_games ON DELETE CASCADE, uid integer NOT NULL REFERENCES words_users ON DELETE CASCADE, msg text NOT NULL);", "INSERT INTO words_users (uid, muted) VALUES (1, false), (2, true);", "INSERT INTO words_social (sid, social, given, uid) VALUES ('abc', 100, 'Nice user', 1), ('def', 200, 'Bad user', 2);", "INSERT INTO words_games (gid, player1, player2) VALUES (10, 1, 2);", "INSERT INTO words_chat (gid, uid, created, msg) VALUES (10, 1, CURRENT_TIMESTAMP + INTERVAL '1 min', 'Hi how are you doing?'), (10, 1, CURRENT_TIMESTAMP + INTERVAL '2 min', 'I am a nice user'), (10, 2, CURRENT_TIMESTAMP + INTERVAL '3 min', 'F*** ***!!'), (10, 2, CURRENT_TIMESTAMP + INTERVAL '4 min', 'I am a bad user'), (10, 1, CURRENT_TIMESTAMP + INTERVAL '5 min', 'Are you there??');"], "clean_up_sql": ["DROP TABLE words_users;", "DROP TABLE words_social;", "DROP TABLE words_games;", "DROP TABLE words_chat;"], "test_cases": []} {"instance_id": 192, "selected_database": "formula_1", "query": "A Formula 1 team is analyzing the performance and financial impact of their drivers in various races. They need to calculate the total earnings for each driver based on their points and a bonus system. The bonus is calculated as follows: if the total earnings exceed 5000 points, a 20% bonus is applied; if the total earnings exceed 3000 points, a 15% bonus is applied. The team wants to avoid repeating the calculation of total earnings multiple times in their query.", "error_sql": ["SELECT driverid, points, (points * 100) as earnings, CASE WHEN (points * 100) > 5000 THEN (points * 100) * 0.2 WHEN (points * 100) > 3000 THEN (points * 100) * 0.15 ELSE null END AS bonus FROM driverstandings"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 193, "selected_database": "european_football_2", "query": "The data returned as `dataset` in the CTE below represents the number of times team attributes were recorded for each date within a specific time frame. The dataset looks like this:\n\n| date | rows_added |\nHow can I incorporate a count of the duplicate records, by date, in the following CTE? If I was going to only count the duplicate dates I would use the following but I can't incorporate it into the CTE above:\n\nsql\nSELECT date, COUNT(date)\nFROM dataset \nGROUP BY date \nHAVING COUNT(date) >1 \n\n\nDesired output given the example above:\n\n|total_days_in_result_set | total_days_w_distinct_record_counts | toal_days_w_duplicate_record_counts | duplicate_dates |\n", "error_sql": ["with dataset as (\n SELECT \n date,\n COUNT(*) as rows_added\n FROM\n team_attributes\n WHERE \n date between '2010-01-01 00:00:00'\n AND '2015-12-31 00:00:00'\n GROUP BY \n date\n )\nSELECT\n COUNT(*) as total_days_in_result_set,\n COUNT(DISTINCT rows_added) as total_days_w_distinct_record_counts,\n COUNT(*) - COUNT(DISTINCT rows_added) as toal_days_w_duplicate_record_counts\nFROM dataset"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 194, "selected_database": "card_games", "query": "I'm trying to handle an array of counters column in Postgres for a card collection tracking system. For example, let's say I have this table:\n\n| card_name | counters | where counters is a list of numbers like [1,2,3,4] and now I'm adding 2 values [2,0,2,1] and [1,3,1,0]).\n\nI expect the query to sum between the 2 counters vectors on conflict ([1,3,1,0] + [2,0,2,1] = [3,3,3,1]).\n\nThe expected counters are [3,3,3,1]. I had a try but it didn't seem to work, what am I missing?", "error_sql": ["insert into card_counters (card_name, counters) values ('Lightning Bolt', array[2,0,2,1]) on conflict (card_name) do update set counters = array_agg(unnest(card_counters.counters) + unnest(array[2,0,2,1]))"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE card_counters (card_name text PRIMARY KEY, counters integer[]);", "INSERT INTO card_counters (card_name, counters) VALUES ('Lightning Bolt', array[1,3,1,0]);"], "clean_up_sql": ["DROP TABLE card_counters;"], "test_cases": []} {"instance_id": 195, "selected_database": "erolp", "query": "In the erolp database, we have a table named sales_transactions that records the transaction details of a financial application. Each transaction has an id, a transaction amount (trx), an event multiplier (event), and a desired result (result_good) which is the accumulation of the transaction amounts and previous results, multiplied by the event multiplier. The user is trying to calculate the 'result_good' column based on the recursive relationship between the rows. The user has attempted various methods including arrays, lateral views, recursive views, custom functions, and variables but has not been successful. The expected output is | id | result | and result is retained to 6 decimal places", "error_sql": ["select id, round(prev + event * sum(prev) over(order by id range between unbounded preceding and 1 preceding)::numeric(10, 6), 6) as not_quite_my_tempo from (select *, event*sum(trx) over(order by id) as prev from sales_transactions) t order by id"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE sales_transactions (id int, trx int, event numeric(10,5), result_good numeric(10,6));", "INSERT INTO sales_transactions (id, trx, event, result_good) VALUES (1, 20, 0.1, 2.000000), (2,-10, 0.1, 1.200000), (3, 20,-0.1,-3.320000), (4,-10, 0.1, 1.988000), (5, 20, 0.1, 4.186800), (6,-10,-0.1,-3.605480), (7, 20, 0.1, 5.244932);"], "clean_up_sql": ["DROP TABLE IF EXISTS sales_transactions;"], "test_cases": []} {"instance_id": 196, "selected_database": "california_schools", "query": "We have a dataset of schools in California, and we are interested in analyzing the distribution of schools based on their funding type. We have created a Common Table Expression (CTE) named cte_funding_count that contains the count of schools for each funding type. The CTE looks like this:\n| fundingtype | count |\nFrom this CTE, we want to calculate the percentage of the count compared to the sum of the count as a new third column, and we want the percentage without decimals. However, when we do that, we get a sum of the percent column that is not exactly 100 due to rounding. How do we avoid this?", "error_sql": ["WITH cte_funding_count AS (SELECT fundingtype, COUNT(*) AS count FROM schools GROUP BY fundingtype) SELECT fundingtype, count, ROUND(count*100/(SELECT SUM(count) FROM cte_funding_count),0) AS percent FROM cte_funding_count"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 197, "selected_database": "thrombosis_prediction", "query": "In the thrombosis_prediction database, I need to find the first laboratory test activity for each patient that occurred between the patient's first recorded data date and the date of their first hospital admission. The laboratory table contains the test dates, and the patient table contains the first recorded data date and the admission date. The patient's ID is the common key between the two tables. I want to retrieve the date of the first laboratory test activity and patient id for patients with sex F.", "error_sql": ["SELECT lab.date AS firstActivity, pat.id FROM patient pat JOIN laboratory lab ON lab.id = pat.id AND lab.date <= pat.description AND lab.date > pat.\"First Date\" WHERE pat.sex='F' order by pat.id"], "sol_sql": [], "preprocess_sql": [], "clean_up_sql": [], "test_cases": []} {"instance_id": 198, "selected_database": "card_games", "query": "In the card_games database, I have a table (cards) that contains an id column (id) and another column (keywords) that contains an array of strings. I have a select query (SelectQuery) that gets me an id that matches cards.id, as well as an array of values (RemoveKeywords). I would like to now remove from the keywords array, any strings that are contained in the RemoveKeywords array that match on id. If the array is empty, the output return is []. For example, given cards (1, ['test']) and selectquery (1, ['test']), the output is (1, []) but not none", "error_sql": ["select id, array_agg(elem) from cards, unnest(string_to_array(cards.keywords, ',')::text[]) elem where elem <> all(SELECT unnest(sq.RemoveKeywords) from SelectQuery sq) and id in (61, 65) group by id order by id;"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE SelectQuery (id bigint, RemoveKeywords text[]);", "INSERT INTO SelectQuery (id, RemoveKeywords) VALUES (65, ARRAY['Flying']), (61, ARRAY['Landwalk']);"], "clean_up_sql": ["DROP TABLE SelectQuery;"], "test_cases": []} {"instance_id": 199, "selected_database": "toxicology", "query": "We have a table named \"Experiment\" in the toxicology database that records the hourly measurements of various chemical reactions over a period of 2009 to the present. Each record includes a timestamp and the concentration levels of different chemicals such as Chlorine (CL) and Carbon (C). We need to aggregate (average) the concentration levels across different intervals from specific timepoints, for example, data from 2021-01-07T00:00:00.000Z for one year at 7 day intervals, or 3 months at 1 day interval or 7 days at 1h interval etc. The date_trunc() function partly solves this, but rounds the weeks to the nearest Monday, e.g. the following query returns the first time series interval as 2021-01-04 with an incorrect count:", "error_sql": ["SELECT date_trunc('week', \"TIMESTAMP\") AS week, count(*), AVG(\"CL\") AS cl, AVG(\"C\") AS c FROM \"Experiment\" WHERE \"TIMESTAMP\" >= '2021-01-07T00:00:00.000Z' AND \"TIMESTAMP\" <= '2022-01-06T23:59:59.999Z' GROUP BY week ORDER BY week ASC"], "sol_sql": [], "preprocess_sql": ["CREATE TABLE \"Experiment\" (\"TIMESTAMP\" timestamp NOT NULL, \"CL\" numeric NOT NULL, \"C\" numeric NOT NULL);", "INSERT INTO \"Experiment\" (\"TIMESTAMP\", \"CL\", \"C\") VALUES ('2021-01-07 00:00:00', 10.0, 5.0), ('2021-01-07 01:00:00', 11.0, 6.0), ('2021-01-14 00:00:00', 9.0, 4.0), ('2021-01-14 01:00:00', 10.0, 5.0), ('2021-01-21 00:00:00', 8.0, 3.0), ('2021-01-21 01:00:00', 9.0, 4.0);"], "clean_up_sql": ["DROP TABLE \"Experiment\";"], "test_cases": []}