Datasets:

Modalities:
Text
Formats:
json
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
pandas
License:
Dataset Viewer
Auto-converted to Parquet Duplicate
dialect
stringclasses
1 value
version
stringclasses
1 value
instance_id
int64
0
199
db_id
stringclasses
12 values
query
stringlengths
92
2.94k
issue_sql
sequencelengths
1
4
preprocess_sql
sequencelengths
0
10
clean_up_sql
sequencelengths
0
5
category
stringclasses
4 values
efficiency
bool
2 classes
PostgreSQL
14.12
0
financial
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 betwee...
[ "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;" ]
[]
[]
Query
false
PostgreSQL
14.12
1
codebase_community
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: 0:00:00 10:00:00 04:00:00 However, when I tried to use the following SQL query, it didn't give m...
[ "SELECT CreationDate::time FROM comments;" ]
[]
[]
Query
false
PostgreSQL
14.12
2
financial
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 certa...
[ "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 ...
[ "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;" ]
[]
Management
false
PostgreSQL
14.12
3
european_football_2
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 ...
[ "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::buildupplayspeed...
[ "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;" ]
[]
Management
false
PostgreSQL
14.12
4
student_club
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...
[ "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;" ]
[]
[]
Management
false
PostgreSQL
14.12
5
debit_card_specializing
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_1...
[ "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 *;" ]
[]
[]
Management
false
PostgreSQL
14.12
6
codebase_community
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?
[ "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;" ]
[]
[]
Query
false
PostgreSQL
14.12
7
codebase_community
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 refer...
[ "DROP TABLE IF EXISTS users;" ]
[]
[]
Management
false
PostgreSQL
14.12
8
student_club
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...
[ "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);" ]
[ "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'), ('...
[ "drop table if exists users;", "drop table if exists assets;" ]
Personalization
false
PostgreSQL
14.12
9
student_club
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:
[ "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;" ]
[]
[]
Query
false
PostgreSQL
14.12
10
student_club
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 ...
[ "INSERT INTO attendance VALUES ('recEVTik3MlqbvLFi', 'rec280Sk7o31iG0Tx', 1)" ]
[ "ALTER TABLE attendance ADD COLUMN attend INTEGER DEFAULT 0;" ]
[ "ALTER TABLE attendance DROP COLUMN attend;" ]
Management
false
PostgreSQL
14.12
11
financial
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 informa...
[ "UPDATE account\n SET date__timestamp = date__bigint::timestamp;" ]
[ "\n ALTER TABLE account\n ALTER COLUMN date\n TYPE BIGINT\n USING to_char(date, 'YYYYMMDD')::bigint;\n " ]
[]
Management
false
PostgreSQL
14.12
12
card_games
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 ...
[ "SELECT * FROM cards GROUP BY artist;" ]
[ "\n DELETE FROM cards\n WHERE artist NOT IN ('Ralph Horsley', 'Daarken');\n ", "\n DELETE FROM cards\n WHERE artist IS NULL;\n " ]
[]
Personalization
false
PostgreSQL
14.12
13
debit_card_specializing
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: sql IF SELECT * FROM transac...
[ "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'" ]
[]
[]
Query
false
PostgreSQL
14.12
14
financial
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 o...
[ "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" ]
[]
[]
Personalization
false
PostgreSQL
14.12
15
financial
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.
[ "(\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 ...
[]
[]
Personalization
false
PostgreSQL
14.12
16
student_club
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 outp...
[ "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);" ]
[]
[]
Personalization
false
PostgreSQL
14.12
17
financial
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...
[ "SELECT to_char(generate_series, 'YYYY') FROM generate_series(MIN(date)::timestamptz, MAX(date)::timestamptz, '1 year') FROM loan;" ]
[]
[]
Personalization
false
PostgreSQL
14.12
18
financial
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....
[ "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;" ]
[]
[]
Query
false
PostgreSQL
14.12
19
financial
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 ...
[ "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) );" ]
[]
[ "DROP TABLE IF EXISTS client_information;" ]
Management
false
PostgreSQL
14.12
20
card_games
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 w...
[ "INSERT INTO cards(uuid, name) VALUES ('5f8287b1-5bb6-5f4c-ad17-316a40d5bb0c', 'Ancestor''s Chosen') ON CONFLICT DO NOTHING RETURNING id;" ]
[]
[]
Management
false
PostgreSQL
14.12
21
financial
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...
[ "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" ]
[]
[ "UPDATE account SET date = '1995-03-24'", "DELETE FROM account WHERE account_id = 22222" ]
Management
false
PostgreSQL
14.12
22
card_games
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 ...
[ "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" ]
[ "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'), ('2...
[ "DROP TABLE IF EXISTS sets_releaseInfo;" ]
Query
false
PostgreSQL
14.12
23
card_games
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 ...
[ "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;" ]
[ "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);" ]
[ "DROP TABLE IF EXISTS collection" ]
Query
false
PostgreSQL
14.12
24
financial
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('1...
[ "SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');" ]
[]
[ "DROP FUNCTION what_quarter_is(date, integer);" ]
Management
false
PostgreSQL
14.12
25
codebase_community
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:\...
[ "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] <@...
[]
[]
Query
false
PostgreSQL
14.12
26
financial
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 '...
[ "SELECT first_value(bank ignore nulls) over (partition by account_id order by date rows unbounded following) as next_bank FROM trans;" ]
[ "ALTER TABLE trans ADD COLUMN next_amount int;" ]
[ "ALTER TABLE trans DROP COLUMN next_amount;" ]
Query
false
PostgreSQL
14.12
27
european_football_2
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 thete...
[ "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;" ]
[]
[]
Query
false
PostgreSQL
14.12
28
financial
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, with...
[ "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;" ]
[]
[]
Query
false
PostgreSQL
14.12
29
debit_card_specializing
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...
[ "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;" ]
[]
[]
Personalization
false
PostgreSQL
14.12
30
card_games
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. ...
[ "INSERT INTO card_information(price) SELECT jsonb_agg(price) FROM (SELECT price FROM card_information) AS subquery;SELECT * FROM card_information;" ]
[ "\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" ]
[ "DROP TABLE card_information;" ]
Management
false
PostgreSQL
14.12
31
financial
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`, `freque...
[ "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" ]
[]
[]
Personalization
false
PostgreSQL
14.12
32
card_games
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. F...
[ "SELECT 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...
[ "\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'), ('...
[ "DROP TABLE purchase;" ]
Personalization
false
PostgreSQL
14.12
33
financial
I am working with a table 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_...
[ "WITH 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_c...
[ "\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" ]
[ "DROP TABLE card_info;" ]
Personalization
false
PostgreSQL
14.12
34
european_football_2
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 ...
[ "SELECT player_api_id, MAX(date), FIRST(overall_rating) FROM Player_Attributes GROUP BY player_api_id ORDER BY date desc;" ]
[]
[]
Query
false
PostgreSQL
14.12
35
codebase_community
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...
[ "SELECT Age::numeric FROM users;" ]
[ "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);" ]
[ "DELETE FROM users WHERE id = 1212121; ALTER TABLE users ALTER COLUMN age SET DATA TYPE integer USING age::integer;" ]
Management
false
PostgreSQL
14.12
36
codebase_community
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 us...
[ "begin insert into profiles (Id, CreationDate, WebsiteUrl) select new.Id, new.CreationDate, left(replace(new.WebsiteUrl, '.', '-'), charindex('@', replace(new.WebsiteUrl, '.', '-')) - 1);return new;end;" ]
[ "DROP TABLE IF EXISTS profiles; CREATE TABLE profiles (id varchar(256) NOT NULL, CreationDate text, WebsiteUrl text, PRIMARY KEY (id));" ]
[]
Management
false
PostgreSQL
14.12
37
financial
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 transacti...
[ "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')" ]
[]
[]
Efficiency
true
PostgreSQL
14.12
38
card_games
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...
[ "SELECT * FROM cards WHERE availability = 'paper' AND bordercolor = 'black' AND rarity = 'uncommon' AND types = 'Creature';" ]
[]
[]
Query
false
PostgreSQL
14.12
39
student_club
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 ...
[ "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', 'rec2...
[ "CREATE TABLE failure (event VARCHAR(255) NOT NULL, member VARCHAR(255) NOT NULL, PRIMARY KEY (event, member));" ]
[ "DROP TABLE IF EXISTS failure;" ]
Management
false
PostgreSQL
14.12
40
european_football_2
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_au...
[ "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 ...
[ "CREATE TABLE player_audits (player_id int, old_player_name text, changed_on timestamp );" ]
[ "DROP TABLE IF EXISTS player_audits;" ]
Management
false
PostgreSQL
14.12
41
student_club
I 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_Attendance...
[ "SELECT\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_Atten...
[ "\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, 10...
[ "DROP TABLE event_attendance;" ]
Efficiency
true
PostgreSQL
14.12
42
codebase_community
I'm working with a table called `preference_tag`, which contains a `userid` and an array of tags in the `tag` column. I need to find rows in the user's tag preference table where the array contains the corresponding tags. For example, when querying with `ARRAY['friend', 'cat']`, it works as expected, returning the r...
[ "SELECT DISTINCT userid, tag\nFROM preference_tag\nWHERE tag @> (ARRAY['friend', 'cat']::VARCHAR[]);" ]
[ "\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" ]
[ "DROP TABLE preference_tag;" ]
Personalization
false
PostgreSQL
14.12
43
financial
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 ...
[ "SELECT * FROM account_info WHERE ((condition->0->>'conditions')::json->>'rootcompanyid')::json->>'$in' = '[5]';" ]
[ "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\":\"rootcompan...
[ "DROP TABLE IF EXISTS account_info;" ]
Personalization
false
PostgreSQL
14.12
44
superhero
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...
[ "ALTER TABLE hero_power ADD CONSTRAINT unique_active_hero_power UNIQUE (hero_id, power_id);" ]
[ "ALTER TABLE hero_power ADD COLUMN active BOOLEAN DEFAULT TRUE;" ]
[ "ALTER TABLE hero_power DROP COLUMN IF EXISTS active;", "DROP INDEX IF EXISTS idx_hero_power_active;" ]
Management
false
PostgreSQL
14.12
45
toxicology
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`, `destination`, and `revenue`. We need to identify users who meet specific criteria based on their purchase history:\n1) Users who have made a purchase in the `luxu...
[ "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')" ]
[ "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,...
[ "DROP TABLE orders;" ]
Query
false
PostgreSQL
14.12
46
formula_1
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 l...
[ "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" ]
[ "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')" ]
[ "DROP TABLE cars;" ]
Personalization
false
PostgreSQL
14.12
47
thrombosis_prediction
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 ea...
[ "WITH aspirin_patients AS ( SELECT DISTINCT patient_id FROM prescriptions WHERE medication_id = 1 ) SELECT p.patient_id, array_agg(DISTINCT p.medication_id ORDER BY p.medication_id) AS medications FROM prescriptions p JOIN aspirin_patients ap ON p.patient_id = ap.patient_id GROUP BY p.patient_id;" ]
[ "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 (medica...
[]
Efficiency
true
PostgreSQL
14.12
48
formula_1
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 ...
[ "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" ]
[]
[]
Query
false
PostgreSQL
14.12
49
superhero
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...
[ "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;" ]
[]
[]
Query
false
PostgreSQL
14.12
50
formula_1
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 th...
[ "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\"...
[]
[]
Personalization
false
PostgreSQL
14.12
51
formula_1
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 ...
[ "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;" ]
[]
[]
Query
false
PostgreSQL
14.12
52
toxicology
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 list...
[ "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" ]
[]
[]
Personalization
false
PostgreSQL
14.12
53
toxicology
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` t...
[ "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;" ]
[]
[]
Query
false
PostgreSQL
14.12
54
european_football_2
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 t...
[ "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...
[]
[]
Query
false
PostgreSQL
14.12
55
debit_card_specializing
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 transac...
[ "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);" ]
[ "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_...
[ "DROP TABLE clients;", "DROP TABLE groups;", "DROP TABLE clients_to_groups;" ]
Efficiency
true
PostgreSQL
14.12
56
european_football_2
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 or negative. The goal is to group these transactions by club and sign (positive ...
[ "SELECT transaction_date AS date, club_name, sum(amount) over (partition by club_name, sign(amount) order by transaction_date) from club_transactions" ]
[ "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', 'Manc...
[ "DROP TABLE club_transactions;" ]
Query
false
PostgreSQL
14.12
57
california_schools
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_modu...
[ "SELECT array_to_json(array_agg(row_to_json(alias))) FROM (select * from modules ) alias" ]
[ "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', 'asd...
[ "DROP TABLE modules;" ]
Personalization
false
PostgreSQL
14.12
58
toxicology
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 update...
[ "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;" ]
[ "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);" ]
[ "DROP TABLE atom_edits;" ]
Efficiency
true
PostgreSQL
14.12
59
debit_card_specializing
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 `...
[ "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;" ]
[ "ALTER TABLE customers\nADD CONSTRAINT customers_customerid_segment_currency_uk\nUNIQUE (customerid, segment, currency);" ]
[ "DROP TABLE customers;" ]
Management
false
PostgreSQL
14.12
60
financial
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 ...
[ "SELECT client.client_id, client.gender, disp.disp_id, address ->> 'PostCode' AS PostCode FROM client JOIN disp ON client.client_id = disp.client_id CROSS JOIN jsonb_array_elements(disp.addresses) AS address WHERE disp.client_id IN (100, 414);" ]
[ "ALTER TABLE disp \nADD COLUMN addresses jsonb;", "INSERT INTO disp (disp_id, client_id, account_id, addresses) VALUES\n (324124, 100, 518, '[{\"PostCode\":\"12345\"}]'),\n (43244241, 94, 2090, '[null]'),\n (42342436, 414, 11325, 'null');" ]
[ "\n DELETE FROM disp \n WHERE disp_id IN (324124, 43244241, 42342436);\n ", "\n ALTER TABLE disp \n DROP COLUMN addresses;\n " ]
Management
false
PostgreSQL
14.12
61
financial
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 incre...
[ "INSERT 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;" ]
[ "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 (1...
[ "DROP TABLE IF EXISTS loan;" ]
Management
false
PostgreSQL
14.12
62
card_games
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, rar...
[ "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 WHER...
[ "\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" ]
[ "\nDROP TABLE norm1; DROP TABLE norm2;\n" ]
Efficiency
true
PostgreSQL
14.12
63
financial
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 nullab...
[ "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||' se...
[ "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 );" ]
[]
Management
false
PostgreSQL
14.12
64
financial
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,...
[ "UPDATE card SET disp_id = 1 WHERE disp_id = 41;" ]
[]
[]
Management
false
PostgreSQL
14.12
65
financial
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 ...
[ "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');EXP...
[]
[]
Management
false
PostgreSQL
14.12
66
european_football_2
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. Between two such draws, you might have several othe...
[ "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...
[]
[]
Query
false
PostgreSQL
14.12
67
debit_card_specializing
We have a table called transactions_1k that contains transaction details for multiple customers across different gas stations. Each row in this table has: 1. transaction date 2. ransaction time 3. customerid (the ID of the customer) 4. gasstationid (the ID of the gas station) 5. productid (the product involved) 6. amou...
[ "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 MA...
[]
[]
Query
false
PostgreSQL
14.12
68
superhero
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 line...
[ "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(DISTIN...
[ "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 lineag...
[ "DROP TABLE lineage;" ]
Efficiency
true
PostgreSQL
14.12
69
card_games
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`...
[ "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.us...
[ "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', '2...
[ "DROP TABLE user_actions" ]
Query
false
PostgreSQL
14.12
70
card_games
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 list...
[ "SELECT c.id, c.name FROM cards c WHERE c.id IN (SELECT unnest(card_order) FROM decks WHERE id = 1);" ]
[ "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]);" ]
[ "DROP TABLE decks;" ]
Personalization
false
PostgreSQL
14.12
71
card_games
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...
[ "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" ]
[ "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 o...
[ "DROP TABLE card_prices;", "DROP TABLE order_cards;" ]
Query
false
PostgreSQL
14.12
72
european_football_2
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 perf...
[ "select player_id, stats_keys, stats_values from player_stats" ]
[ "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');...
[ "DROP TABLE player_stats;" ]
Query
false
PostgreSQL
14.12
73
european_football_2
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...
[ "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);" ]
[ "CREATE TABLE teams_config (configurations jsonb);", "INSERT INTO teams_config VALUES ('[{\"id\": 100, \"name\": \"testOne\", \"settings\": \"settingOne\"}, {\"id\": 101, \"name\": \"testTwo\", \"settings\": \"settingTwo\"}]');" ]
[ "DROP TABLE teams_config" ]
Management
false
PostgreSQL
14.12
74
formula_1
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 F...
[ "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 m...
[ "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');" ]
[ "DROP TABLE race_dates" ]
Query
false
PostgreSQL
14.12
75
student_club
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 attending the same event. If an attendance record for the member and event already exists, the date column should be updated to re...
[ "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 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 " ]
[]
Management
false
PostgreSQL
14.12
76
financial
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 trie...
[ "pg_advisory_xact_lock(lkhndl);" ]
[ "\n DROP FUNCTION IF EXISTS pg_try_advisory_lock_with_timeout(bigint);\n " ]
[]
Management
false
PostgreSQL
14.12
77
student_club
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...
[ "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 ...
[ "\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 ('rec0Si5cQ4rJRVzd6', 'rec1x5zBFIqoOuPW8', 64.5),\n ('rec0akZnLLpGUloLH', 'recEFd8s6pkrTt4Pz', 60.0),\n ('re...
[]
Personalization
false
PostgreSQL
14.12
78
financial
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.
[ "CREATE INDEX ix_account ON account USING btree (district_id, frequency, date);" ]
[ "\n CREATE INDEX ix_account ON account USING btree (district_id, frequency, date); \n " ]
[]
Personalization
false
PostgreSQL
14.12
79
european_football_2
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 vie...
[ "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 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 find...
[]
Management
false
PostgreSQL
14.12
80
codebase_community
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 'di...
[ "select posttypeid\n case when tags like ('%bayesian%','%distributions%')\n then 1 else 0 end as keyword_count\n from posts" ]
[ "\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, '<bayesian><prior><elicitation>'),\n (2, 1, '<distributions><normality>'),...
[]
Personalization
false
PostgreSQL
14.12
81
debit_card_specializing
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 ea...
[ "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" ]
[ "\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, ...
[ "\nDROP TABLE test;\n" ]
Efficiency
true
PostgreSQL
14.12
82
toxicology
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 b...
[ "SELECT count(bond_id), molecule_id FROM bond GROUP BY molecule_id ORDER BY molecule_id last_update DESC;" ]
[ "ALTER TABLE bond ADD COLUMN last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP;" ]
[ "ALTER TABLE bond DROP COLUMN last_update;" ]
Personalization
false
PostgreSQL
14.12
83
european_football_2
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 c...
[ "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(colum...
[ "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:0...
[ "DROP TABLE IF EXISTS player_stats_changes;" ]
Personalization
false
PostgreSQL
14.12
84
superhero
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 ...
[ "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 su...
[ "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)" ]
[]
Query
false
PostgreSQL
14.12
85
superhero
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, especial...
[ "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;" ]
[ "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;" ]
[ "DROP TABLE hero_access;" ]
Efficiency
true
PostgreSQL
14.12
86
superhero
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 repo...
[ "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_te...
[ "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,...
[ "DROP TABLE utm;", "DROP TABLE report" ]
Personalization
false
PostgreSQL
14.12
87
card_games
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: "{{...
[ "SELECT\n id,\n text,\n REGEXP_MATCHES(\n text,\n '\\{.*?\\}',\n 'g'\n ) AS bracketed_tokens\nFROM cards;" ]
[]
[]
Personalization
false
PostgreSQL
14.12
88
superhero
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 sho...
[ "SELECT race_id, top(count(*), 5) as cnt FROM superhero group by gender_id" ]
[]
[]
Query
false
PostgreSQL
14.12
89
card_games
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 curre...
[ "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...
[]
[]
Personalization
false
PostgreSQL
14.12
90
formula_1
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 | ...
[ "select rank() over (order by total_points desc) as place, id, name, total_points, race_points, raceId from racers" ]
[ "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), (...
[ "DROP TABLE racers;" ]
Query
false
PostgreSQL
14.12
91
california_schools
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 e...
[ "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" ]
[]
[]
Efficiency
true
PostgreSQL
14.12
92
card_games
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 cus...
[ "SELECT month_year, COUNT(DISTINCT customer_id) FROM orders GROUP BY month_year HAVING COUNT(order_id) > 1" ]
[ "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...
[ "DROP TABLE orders;" ]
Query
false
PostgreSQL
14.12
93
european_football_2
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 ...
[ "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'" ]
[ "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'), (...
[ "DROP TABLE player_movements;" ]
Query
false
PostgreSQL
14.12
94
european_football_2
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,...
[ "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_att...
[]
[]
Efficiency
true
PostgreSQL
14.12
95
financial
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, th...
[ "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;" ]
[]
[ "DROP INDEX IF EXISTS idx_a;" ]
Efficiency
true
PostgreSQL
14.12
96
financial
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 wi...
[ "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" ]
[]
[]
Personalization
false
PostgreSQL
14.12
97
debit_card_specializing
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...
[ "SELECT * FROM transactions_1k WHERE (Date, Time, Amount) < ('2012-08-24', '10:00:00', 20);" ]
[]
[]
Personalization
false
PostgreSQL
14.12
98
financial
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 ...
[ "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';" ]
[]
[]
Personalization
false
PostgreSQL
14.12
99
codebase_community
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 t...
[ "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.vie...
[ "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', nu...
[ "DROP TABLE IF EXISTS view_logs;" ]
Query
false
End of preview. Expand in Data Studio

BIRD-CRITIC-1.0-Flash

BIRD-Critic is the first SQL debugging benchmark designed to answer a critical question: Can large language models (LLMs) fix user issues in real-world database applications?
Each task in BIRD-CRITIC has been verified by human experts on the following dimensions:

  1. Reproduction of errors on BIRD env to prevent data leakage.
  2. Carefully curate test case functions for each task specifically.
    • Soft EX: This metric can evaluate SELECT-ONLY tasks.
    • Soft EX + Parsing: This metric can evaluate tasks with user specific requirements or refinements.
    • Test Case: For DBA tasks, such as CRUD (CREAT, READ, UPDATE, DELET), test cases should be promised to evaluate the correct logic. This is also effective for user issues requiring multiple sequential SQLs to resolve.
    • Query Execution Plan: For user tasks involving efficiency improvement or runtime errors, QEP can be introduced to evaluate solution SQLs on algorithm level.
  3. Fast Eval Sandbox via PostgreSQL template & docker.
  4. Created new RDBs in different scale and professional domains.

We are releasing a lite version of BIRD-Critic, bird-critic-1.0-flash-exp, which includes 200 high-quality user issues on PostgreSQL when developing real-world applications. We curate tasks by:

  • Collecting and understanding realistic user issues.
  • Distilling problem definitions and SQL knowledge.
  • Reproducing bugs and solutions in the BIRD environment.
  • Designing test cases for evaluation.

Model Performance Results

Rank Model Name Query Management Personalization Efficiency Overall Score Level
1 o1-preview-2024-09-12 46.88 36.73 30.77 40.91 38.50 πŸ† Leading
2 o3-mini-2025-01-31 26.56 40.00 42.19 45.45 37.00 🌟 Elite
3 deepseek-reasoner (r1) 34.38 36.73 32.31 31.82 34.00 🌟 Elite
4 claude-3-7-sonnet-2025-02-19 (thinking) 26.56 28.00 42.19 27.27 32.00 🌟 Elite
5 claude-3-7-sonnet-2025-02-19 20.31 40.00 31.25 22.73 29.00 🌟 Elite
5 gpt-4o-2024-11-20 32.81 22.45 32.31 22.73 29.00 🌟 Elite
6 o1-mini 28.13 32.65 26.15 22.73 28.00 πŸ’Ž Superior
7 deepseek-V3 28.13 30.61 26.15 22.73 27.50 πŸ’Ž Superior
8 phi-4 25.00 30.61 20.00 22.73 24.50 πŸ’Ž Superior
8 QwQ-32B 23.44 26.00 25.00 22.73 24.50 πŸ’Ž Superior
9 Claude-3-5-sonnet 15.63 32.65 26.15 22.73 24.00 πŸ”Έ Advanced
10 gemini-2.0-flash-exp 20.31 26.53 24.62 27.27 24.00 πŸ”Έ Advanced
11 Qwen2.5-Coder-32B-Instruct 25.00 26.53 23.08 9.09 23.00 πŸ”Έ Advanced
12 gemini-2.0-flash-thinking-exp 20.31 16.33 18.46 27.27 19.50 πŸ”Έ Advanced
13 Meta-Llama-3.3-70B-Instruct 18.75 24.49 12.31 22.73 18.50 πŸ’« Standard
14 Codestral-22B-v0.1 10.94 18.37 23.08 22.73 18.00 πŸ’« Standard
15 gemma-2-27b-it 17.19 16.33 20.00 18.18 18.00 πŸ’« Standard
16 QwQ-32B-Preview 21.88 14.29 16.92 13.64 17.50 πŸ’« Standard
17 starcoder2-15b-instruct-v0.1 10.94 16.33 16.92 4.55 13.50 πŸ’« Standard
18 DeepSeek-Coder-V2-Lite-Instruct 10.94 14.29 12.31 13.64 12.50 βšͺ Basic
19 Mixtral-8x7B-Instruct-v0.1 12.50 10.20 10.77 13.64 11.50 βšͺ Basic
20 gemma-2-9b-it 9.38 8.16 12.31 18.18 11.00 βšͺ Basic
21 Yi-1.5-34B-Chat-16K 6.25 14.29 12.31 9.09 10.50 βšͺ Basic
22 CodeLlama-34b-Instruct-hf 9.38 10.20 9.23 13.64 10.00 βšͺ Basic
23 CodeLlama-13b-Instruct-hf 10.94 12.24 4.62 9.09 9.00 βšͺ Basic
24 Mistral-7B-Instruct-v0.2 3.13 4.08 4.62 0.00 3.50 βšͺ Basic

Tier Classification (By Ranking):

  • πŸ† Leading: The Best!
  • 🌟 Elite: Top 15%
  • πŸ’Ž Superior: Top 30%
  • πŸ”Έ Advanced: Top 45%
  • πŸ’« Standard: Top 70%
  • βšͺ Basic: Bottom 30%

Instance Categories:

  • Query: Instances that involve classic retrieval operations (i.e., SELECT).
  • Management: Instances that perform database management (e.g, CREATE, UPDATE, INSERT).
  • Personalization: Instances requiring a custom approach to achieve.
  • Efficiency: Instances focused on query optimization.

Represent as issue_type in each data instance.

Dataset Details

Uses

To avoid data leakage by auto-crawling, certain fields (e.g., sol_sql, test_cases) are excluded from the public dataset. For the full dataset, please email: πŸ“§ bird.bench25@gmail.com with subject tag [bird-critic-1 GT&Test Cases], which will be sent automatically within 30 mins.

Code Sources

Dataset Structure

Below is a description of the dataset fields and additional information about the structure:

  • db_id: The name of the database.
  • query: The user query is rewritten in the BIRD environment.
  • error_sql: The buggy SQL query written by the user.
  • sol_sql: The ground truth SQL solution.
  • preprocess_sql: SQL queries to run before executing the solution or prediction.
  • clean_up_sql: SQL queries to run after the test cases to revert any changes made to the database.
  • test_cases: A set of test cases to validate the predicted corrected SQL.
  • efficiency: True if this question needs optimization, measure the cost by Query Execution Plan (QEP)
  • external_data: For the external JSON data if present

πŸ“„ Paper

If you find our work helpful, please cite as:

@article{li2025swe,
  title={SWE-SQL: Illuminating LLM Pathways to Solve User SQL Issues in Real-World Applications},
  author={Li, Jinyang and Li, Xiaolong and Qu, Ge and Jacobsson, Per and Qin, Bowen and Hui, Binyuan and Si, Shuzheng and Huo, Nan and Xu, Xiaohan and Zhang, Yue and others},
  journal={arXiv preprint arXiv:2506.18951},
  year={2025}
}

Todo Lists

  • Release lite version, bird-critic-1.0-flash (200).
  • Open source code, leaderboard page.
  • Release Full bird-critic-1.0-open (600 w/ 5 dialects).
  • Release Full bird-critic-1.0-postgresql (600 pg tasks).
  • BIRD-Nest, a Gym-like training set for bird-critic-1.0
  • LiveSQLBench Base
  • BIRD-CRITIC 1.5 / 2.0 on track!

Post By:

BIRD Team & Google Cloud

Downloads last month
85

Collection including birdsql/bird-critic-1.0-flash-exp

Paper for birdsql/bird-critic-1.0-flash-exp