Dataset Viewer
Auto-converted to Parquet Duplicate
conversations
listlengths
2
8
system
stringlengths
276
7.75k
[ { "role": "user", "content": "Show me the count of service orders for each distinct status." }, { "role": "assistant", "content": "SELECT status, COUNT(order_id) FROM hospitality_technology.service_orders GROUP BY status;" }, { "role": "user", "content": "Also, include the total quantity of items ordered for each status." }, { "role": "assistant", "content": "SELECT status, COUNT(order_id), SUM(quantity) FROM hospitality_technology.service_orders GROUP BY status;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) ) CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
[ { "role": "user", "content": "For each route, show the route number and the total number of trips associated with it." }, { "role": "assistant", "content": "SELECT T2.route_number, count(T1.trip_id) FROM transportation.trips AS T1 JOIN transportation.routes AS T2 ON T1.route_id = T2.route_id GROUP BY T2.route_number" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date ) CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text ) CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text ) CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text ) CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text ) CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
[ { "role": "user", "content": "Show me all customers who have missing contact information (either phone number or email is null), along with their state and city." }, { "role": "assistant", "content": "SELECT first_name, last_name, state, city FROM insurance.customers WHERE phone_number IS NULL OR email IS NULL;" }, { "role": "user", "content": "Now filter these to only show customers from Florida or New York who were created in the last year." }, { "role": "assistant", "content": "SELECT first_name, last_name, state, city FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '1 year';" }, { "role": "user", "content": "I also want to see when these customers were last updated (updated_at field)." }, { "role": "assistant", "content": "SELECT first_name, last_name, state, city, updated_at FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '1 year';" }, { "role": "user", "content": "Finally, order the results by state first, then by the most recently updated customers first." }, { "role": "assistant", "content": "SELECT first_name, last_name, state, city, updated_at FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '1 year' ORDER BY state, updated_at DESC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE insurance.customers ( customer_id character varying(64) NOT NULL, -- unique identifier for the customer first_name character varying(100) NOT NULL, -- customer's first name last_name character varying(100) NOT NULL, -- customer's last name date_of_birth date NOT NULL, -- customer's date of birth ssn_hash character varying(128), -- Hashed social security number (or national ID) address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL DEFAULT 'USA', phone_number character varying(30), email character varying(128) UNIQUE, -- unique email address created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created updated_at timestamp, -- when the customer record was last updated status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect PRIMARY KEY (customer_id) )
[ { "role": "user", "content": "For each developer, can you find the next developer in the same country using a self join, returning developer_ids and names?" }, { "role": "assistant", "content": "SELECT d1.developer_id AS current_dev,\n d1.name AS current_name,\n d2.developer_id AS next_dev,\n d2.name AS next_name,\n d2.founded_year - d1.founded_year AS years_diff\nFROM developers d1\nJOIN developers d2\n ON d1.country = d2.country\n AND d2.founded_year > d1.founded_year;" }, { "role": "user", "content": "Exclude developers who don't have a next developer, and ensure we only pick the closest next by founded_year." }, { "role": "assistant", "content": "SELECT d1.developer_id AS current_dev,\n d1.name AS current_name,\n d2.developer_id AS next_dev,\n d2.name AS next_name,\n d2.founded_year - d1.founded_year AS years_diff\nFROM developers d1\nJOIN LATERAL (\n SELECT d2.developer_id, d2.name, d2.founded_year\n FROM developers d2\n WHERE d2.country = d1.country\n AND d2.founded_year > d1.founded_year\n ORDER BY d2.founded_year ASC\n LIMIT 1\n) d2 ON true;" }, { "role": "user", "content": "Finally, only include pairs where the difference in founded years is at most 5 years." }, { "role": "assistant", "content": "SELECT d1.developer_id AS current_dev,\n d1.name AS current_name,\n d2.developer_id AS next_dev,\n d2.name AS next_name,\n d2.founded_year - d1.founded_year AS years_diff\nFROM developers d1\nJOIN LATERAL (\n SELECT d2.developer_id, d2.name, d2.founded_year\n FROM developers d2\n WHERE d2.country = d1.country\n AND d2.founded_year > d1.founded_year\n ORDER BY d2.founded_year ASC\n LIMIT 1\n) d2 ON true\nWHERE (d2.founded_year - d1.founded_year) <= 5\nORDER BY d1.developer_id, years_diff ASC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
[ { "role": "user", "content": "List all guests who have placed service orders for services in the 'Transportation' department, along with their full names and the service names." }, { "role": "assistant", "content": "SELECT g.guest_id, g.first_name, g.last_name, s.service_name\nFROM hospitality_technology.guests g\nJOIN hospitality_technology.service_orders so ON g.guest_id = so.guest_id\nJOIN hospitality_technology.services s ON so.service_id = s.service_id\nWHERE s.department = 'Transportation';" }, { "role": "user", "content": "Actually, only include guests who have placed at least two such service orders. Also, order the results by the guest's last name." }, { "role": "assistant", "content": "SELECT g.guest_id, g.first_name, g.last_name, COUNT(so.order_id) AS order_count\nFROM hospitality_technology.guests g\nJOIN hospitality_technology.service_orders so ON g.guest_id = so.guest_id\nJOIN hospitality_technology.services s ON so.service_id = s.service_id\nWHERE s.department = 'Transportation'\nGROUP BY g.guest_id, g.first_name, g.last_name\nHAVING COUNT(so.order_id) >= 2\nORDER BY g.last_name ASC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp ) CREATE TABLE hospitality_technology.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp ) CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text ) CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text ) CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
[ { "role": "user", "content": "How many documents were uploaded in the year 2023?" }, { "role": "assistant", "content": "SELECT count(*) FROM government_services.documents WHERE date_part('year', upload_timestamp) = 2023;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
[ { "role": "user", "content": "List the names of employees and the agency they work for who have scheduled at least one appointment. Show the employee's first name, last name, and agency_id." }, { "role": "assistant", "content": "SELECT DISTINCT e.first_name, e.last_name, e.agency_id\nFROM government_services.employees e\nJOIN government_services.appointments a ON e.employee_id = a.employee_id;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text ) CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text ) CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text ) CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text ) CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text ) CREATE TABLE government_services.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
[ { "role": "user", "content": "Show me all policies that expired in the last 60 days, along with their product IDs and premium amounts." }, { "role": "assistant", "content": "SELECT policy_id, product_id, premium_amount FROM insurance.policies WHERE status = 'expired' AND end_date >= CURRENT_DATE - INTERVAL '60 days' AND end_date <= CURRENT_DATE;" }, { "role": "user", "content": "Now include only policies that had a deductible of $1000 or more." }, { "role": "assistant", "content": "SELECT policy_id, product_id, premium_amount, deductible FROM insurance.policies WHERE status = 'expired' AND end_date >= CURRENT_DATE - INTERVAL '60 days' AND end_date <= CURRENT_DATE AND deductible >= 1000;" }, { "role": "user", "content": "I also want to see the count of such expired policies per product ID." }, { "role": "assistant", "content": "SELECT product_id, COUNT(*) as policy_count FROM insurance.policies WHERE status = 'expired' AND end_date >= CURRENT_DATE - INTERVAL '60 days' AND end_date <= CURRENT_DATE AND deductible >= 1000 GROUP BY product_id ORDER BY policy_count DESC;" }, { "role": "user", "content": "Finally, show me the average premium amount for these expired high-deductible policies grouped by product ID." }, { "role": "assistant", "content": "SELECT product_id, AVG(premium_amount) as avg_premium FROM insurance.policies WHERE status = 'expired' AND end_date >= CURRENT_DATE - INTERVAL '60 days' AND end_date <= CURRENT_DATE AND deductible >= 1000 GROUP BY product_id ORDER BY avg_premium DESC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
[ { "role": "user", "content": "List each guest’s full name and the total number of service orders they have placed, ordered by order count descending." }, { "role": "assistant", "content": "SELECT g.guest_id,\n g.first_name || ' ' || g.last_name AS full_name,\n COUNT(so.order_id) AS order_count\nFROM hospitality_technology.guests g\nLEFT JOIN hospitality_technology.service_orders so\n ON g.guest_id = so.guest_id\nGROUP BY g.guest_id, full_name\nORDER BY order_count DESC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp ) CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp ) CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text ) CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )
[ { "role": "user", "content": "Calculate the total value of unspent UTXOs for each user whose KYC status has been 'approved'." }, { "role": "assistant", "content": "SELECT kyc.user_id, SUM(u.amount) FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status = 'approved' AND u.spent = false GROUP BY kyc.user_id;" }, { "role": "user", "content": "Refine that to only show users where this total value exceeds 1000." }, { "role": "assistant", "content": "SELECT kyc.user_id, SUM(u.amount) FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status = 'approved' AND u.spent = false GROUP BY kyc.user_id HAVING SUM(u.amount) > 1000;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean ) CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
[ { "role": "user", "content": "Show me all events emitted by contracts where the event name contains 'Approval', along with the contract ID and transaction ID, sorted by emitted timestamp in descending order." }, { "role": "assistant", "content": "SELECT event_id, contract_id, event_name, transaction_id, emitted_at FROM web3.events WHERE event_name LIKE '%Approval%' ORDER BY emitted_at DESC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, -- unique identifier for the event contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event event_name character varying(128) NOT NULL, -- name of the event data text NOT NULL, -- data payload of the event emitted_at timestamp NOT NULL, -- time when the event was emitted transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event log_index integer NOT NULL, -- index of the event log in the transaction PRIMARY KEY (event_id) )
[ { "role": "user", "content": "Show me the top 3 smart money addresses by profit across all chains, along with their most profitable token and chain information." }, { "role": "assistant", "content": "SELECT address, profit, most_profit_token, chain\nFROM smart_money_profit\nORDER BY profit DESC\nLIMIT 3;" }, { "role": "user", "content": "Actually, I only want to see addresses from Ethereum chain with ROI over 30%." }, { "role": "assistant", "content": "SELECT address, profit, most_profit_token, roi\nFROM smart_money_profit\nWHERE chain = 'Ethereum' AND roi > 30\nORDER BY profit DESC\nLIMIT 3;" }, { "role": "user", "content": "Can you add their realized profit ratio and filter to only show results with profit over $100,000?" }, { "role": "assistant", "content": "SELECT address, profit, most_profit_token, roi, realized_ratio\nFROM smart_money_profit\nWHERE chain = 'Ethereum' AND roi > 30 AND profit > 100000\nORDER BY profit DESC\nLIMIT 3;" }, { "role": "user", "content": "Now order these results by ROI in descending order instead of profit." }, { "role": "assistant", "content": "SELECT address, profit, most_profit_token, roi, realized_ratio\nFROM smart_money_profit\nWHERE chain = 'Ethereum' AND roi > 30 AND profit > 100000\nORDER BY roi DESC\nLIMIT 3;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL, -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested ) CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) ) CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )
[ { "role": "user", "content": "What is the total estimated_loss and average settlement_amount for all claims with status 'Approved'?" }, { "role": "assistant", "content": "SELECT SUM(estimated_loss) AS total_estimated_loss,\n AVG(settlement_amount) AS average_settlement\nFROM insurance.claims\nWHERE status = 'Approved';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
[ { "role": "user", "content": "Show me the top 5 users by the total trade volume (quantity * price) as buyers, along with their email addresses and the number of distinct assets they traded." }, { "role": "assistant", "content": "SELECT u.user_id, u.email, COUNT(DISTINCT t.asset_id) AS distinct_assets_traded, SUM(t.quantity * t.price) AS total_trade_volume FROM trading_platform.users u JOIN trading_platform.trades t ON u.user_id = t.buyer_id GROUP BY u.user_id, u.email ORDER BY total_trade_volume DESC LIMIT 5;" }, { "role": "user", "content": "Now filter these results to only include trades that happened in the last 30 days." }, { "role": "assistant", "content": "SELECT u.user_id, u.email, COUNT(DISTINCT t.asset_id) AS distinct_assets_traded, SUM(t.quantity * t.price) AS total_trade_volume FROM trading_platform.users u JOIN trading_platform.trades t ON u.user_id = t.buyer_id WHERE t.traded_at >= NOW() - INTERVAL '30 days' GROUP BY u.user_id, u.email ORDER BY total_trade_volume DESC LIMIT 5;" }, { "role": "user", "content": "Actually, I want to see the average trade size (quantity) for each of these users as well." }, { "role": "assistant", "content": "SELECT u.user_id, u.email, COUNT(DISTINCT t.asset_id) AS distinct_assets_traded, SUM(t.quantity * t.price) AS total_trade_volume, AVG(t.quantity) AS avg_trade_size FROM trading_platform.users u JOIN trading_platform.trades t ON u.user_id = t.buyer_id WHERE t.traded_at >= NOW() - INTERVAL '30 days' GROUP BY u.user_id, u.email ORDER BY total_trade_volume DESC LIMIT 5;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) ) CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) ) CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, -- unique identifier for the trade order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade buyer_id character varying(64) NOT NULL, -- identifier of the buyer seller_id character varying(64) NOT NULL, -- identifier of the seller asset_id character varying(64) NOT NULL, -- identifier of the asset being traded quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade price numeric(38,14) NOT NULL, -- price per unit of the asset traded_at timestamp NOT NULL, -- time when the trade was executed PRIMARY KEY (trade_id) ) CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) ) CREATE TABLE trading_platform.utxos ( utxo_id character varying(64) NOT NULL, transaction_id character varying(64) NOT NULL, output_index integer NOT NULL, address character varying(128) NOT NULL, amount numeric(38,14) NOT NULL, spent boolean NOT NULL, PRIMARY KEY (utxo_id) ) CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) ) CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp ) CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, -- unique identifier for the metadata asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with key character varying(128) NOT NULL, -- key of the metadata value text NOT NULL, -- value of the metadata PRIMARY KEY (metadata_id) ) CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text, user_id text, status text, reviewed_at timestamp ) CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) ) CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )
[ { "role": "user", "content": "For each Avalanche token tick, calculate the total transfer volume and transaction count over the past 7 days using token_activities_avalanche. Include the token tick, total_volume, and tx_count." }, { "role": "assistant", "content": "SELECT\n tick,\n SUM(amt) AS total_volume,\n COUNT(*) AS tx_count\nFROM token_activities_avalanche\nWHERE block_timestamp >= CURRENT_DATE - INTERVAL '7 days'\nGROUP BY tick;" }, { "role": "user", "content": "Also include the creator address from token_info for each tick, and filter where total_volume > 1000 and creator starts with '0x1'." }, { "role": "assistant", "content": "SELECT\n a.tick,\n SUM(a.amt) AS total_volume,\n COUNT(*) AS tx_count,\n i.creator\nFROM token_activities_avalanche a\nJOIN token_info i\n ON a.tick = i.tick\nWHERE a.block_timestamp >= CURRENT_DATE - INTERVAL '7 days'\nGROUP BY a.tick, i.creator\nHAVING SUM(a.amt) > 1000\n AND i.creator LIKE '0x1%';" }, { "role": "user", "content": "Sort the results by total_volume descending and limit to the top 5 tokens." }, { "role": "assistant", "content": "SELECT\n a.tick,\n SUM(a.amt) AS total_volume,\n COUNT(*) AS tx_count,\n i.creator\nFROM token_activities_avalanche a\nJOIN token_info i\n ON a.tick = i.tick\nWHERE a.block_timestamp >= CURRENT_DATE - INTERVAL '7 days'\nGROUP BY a.tick, i.creator\nHAVING SUM(a.amt) > 1000\n AND i.creator LIKE '0x1%'\nORDER BY total_volume DESC\nLIMIT 5;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer ) CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, -- Block number containing the transaction block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction transaction_index integer NOT NULL, -- Index of the transaction within the block transaction_hash varchar(66) NOT NULL, -- Transaction hash log_index integer NOT NULL, -- Log index contract_address varchar(42) NOT NULL -- Event contract address ) CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer ) CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text ) CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, -- Block number containing the transaction contract_address varchar NOT NULL, -- Event contract address wallet_address varchar NOT NULL, -- The wallet address for the contract(with bloom filter) token_id varchar NOT NULL, -- NFT token id contract_type varchar NOT NULL, -- NFT contract type amount varchar NOT NULL, -- The quantity held in the wallet pk integer NOT NULL -- Partition key for the table(floor(block_number / 7200)) ) CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL ) CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text ) CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL ) CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL ) CREATE TABLE token_prices ( uuid.text, blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp ) CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp ) CREATE TABLE token_balances ( block_number bigint NOT NULL, -- Block number containing the transaction block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction tick varchar NOT NULL, -- Token tick wallet_address varchar(42) NOT NULL, -- Address of owner total_supply decimal(38,0) NOT NULL, -- Max supply amount decimal(38,0) NOT NULL -- The balance of wallet balance at the corresponding block height ) CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL ) CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text ) CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint ) CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, -- Block number containing the transaction block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription wallet_address varchar(42) NOT NULL, -- Address of owner total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription amount varchar NOT NULL -- The balance of wallet balance at the corresponding block height ) CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text ) CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
[ { "role": "user", "content": "Show me a list of all properties along with their average overall review rating." }, { "role": "assistant", "content": "SELECT p.property_id, p.property_name, AVG(r.rating_overall) AS avg_rating\nFROM hospitality_technology.properties p\nJOIN hospitality_technology.reviews r ON p.property_id = r.property_id\nGROUP BY p.property_id, p.property_name;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) ) CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )
[ { "role": "user", "content": "For each driver, find the other driver whose license_expiry_date is the next one after theirs. Show both IDs, names and their expiry dates." }, { "role": "assistant", "content": "SELECT\n d1.driver_id AS driver_id,\n d1.first_name || ' ' || d1.last_name AS driver_name,\n d1.license_expiry_date AS expiry_date,\n d2.driver_id AS next_driver_id,\n d2.first_name || ' ' || d2.last_name AS next_driver_name,\n d2.license_expiry_date AS next_expiry_date\nFROM transportation.drivers d1\nJOIN transportation.drivers d2\n ON d2.license_expiry_date = (\n SELECT MIN(d3.license_expiry_date)\n FROM transportation.drivers d3\n WHERE d3.license_expiry_date > d1.license_expiry_date\n );" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
[ { "role": "user", "content": "List pairs of smoking and non-smoking rooms on the same floor for each property, showing the property_id, floor, smoking room_number, and non_smoking room_number." }, { "role": "assistant", "content": "SELECT r1.property_id,\n r1.floor,\n r1.room_number AS smoking_room,\n r2.room_number AS non_smoking_room\nFROM hospitality_technology.rooms r1\nJOIN hospitality_technology.rooms r2\n ON r1.property_id = r2.property_id\n AND r1.floor = r2.floor\n AND r1.is_smoking = TRUE\n AND r2.is_smoking = FALSE;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
[ { "role": "user", "content": "For each group chat, list its ID, name, creation time, and the creation time of the next group chat created after it, ordered by creation time." }, { "role": "assistant", "content": "SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ORDER BY created_at;" }, { "role": "user", "content": "Only show pairs where the next group chat was created within 48 hours of the current one, and also include the time difference in hours." }, { "role": "assistant", "content": "WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 ORDER BY created_at;" }, { "role": "user", "content": "Further refine: Only include group chats whose names contain 'Discuss'." }, { "role": "assistant", "content": "WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 AND group_name LIKE '%Discuss%' ORDER BY created_at;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
[ { "role": "user", "content": "Find employees who are managers and list the number of employees they directly manage. Show the manager's full name and the count of their direct reports." }, { "role": "assistant", "content": "SELECT m.first_name || ' ' || m.last_name AS manager_full_name, COUNT(e.employee_id) AS number_of_direct_reports FROM government_services.employees AS e JOIN government_services.employees AS m ON e.manager_employee_id = m.employee_id GROUP BY m.employee_id, manager_full_name;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, -- unique identifier for the government employee agency_id character varying(64) NOT NULL, -- FK to agencies table first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, -- null if currently employed access_level character varying(50), -- Role or permission level manager_employee_id character varying(64), -- FK to self for reporting structure PRIMARY KEY (employee_id) )
[ { "role": "user", "content": "Show me all claims with police reports that were filed in the last 3 months, along with the policy details and customer information." }, { "role": "assistant", "content": "SELECT c.claim_id, c.policy_id, c.customer_id, c.incident_date, c.reported_date, c.description, c.estimated_loss, c.status, c.settlement_amount, c.settlement_date, c.police_report_number, pp.payment_date, pp.amount_paid, pp.payment_method FROM insurance.claims c JOIN insurance.premium_payments pp ON c.policy_id = pp.policy_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months';" }, { "role": "user", "content": "I also want to see how many documents were submitted for each of these claims." }, { "role": "assistant", "content": "SELECT c.claim_id, c.policy_id, c.customer_id, COUNT(cd.document_id) AS document_count FROM insurance.claims c LEFT JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months' GROUP BY c.claim_id, c.policy_id, c.customer_id;" }, { "role": "user", "content": "Now filter to only show claims where the estimated loss is above $10,000." }, { "role": "assistant", "content": "SELECT c.claim_id, c.policy_id, c.customer_id, COUNT(cd.document_id) AS document_count FROM insurance.claims c LEFT JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND c.estimated_loss > 10000 GROUP BY c.claim_id, c.policy_id, c.customer_id;" }, { "role": "user", "content": "Finally, order the results by the highest estimated loss first." }, { "role": "assistant", "content": "SELECT c.claim_id, c.policy_id, c.customer_id, COUNT(cd.document_id) AS document_count, c.estimated_loss FROM insurance.claims c LEFT JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND c.estimated_loss > 10000 GROUP BY c.claim_id, c.policy_id, c.customer_id, c.estimated_loss ORDER BY c.estimated_loss DESC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text ) CREATE TABLE insurance.premium_payments ( payment_id.text, policy_id.text, customer_id.text, payment_date.timestamp, amount_paid.numeric, payment_method.text, transaction_reference.text, due_date.date, payment_period_start.date, payment_period_end.date, status.text ) CREATE TABLE insurance.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
[ { "role": "user", "content": "Show me the usernames along with the names of group chats they are participating in and the dates they joined each group." }, { "role": "assistant", "content": "SELECT u.username, c.group_name, cp.joined_at\nFROM social_media.conversation_participants cp\nJOIN social_media.users u ON cp.user_id = u.user_id\nJOIN social_media.conversations c ON cp.conversation_id = c.conversation_id\nWHERE c.is_group_chat = TRUE;" }, { "role": "user", "content": "Only display records where the user joined after January 1, 2024." }, { "role": "assistant", "content": "SELECT u.username, c.group_name, cp.joined_at\nFROM social_media.conversation_participants cp\nJOIN social_media.users u ON cp.user_id = u.user_id\nJOIN social_media.conversations c ON cp.conversation_id = c.conversation_id\nWHERE c.is_group_chat = TRUE\nAND cp.joined_at > '2024-01-01';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean ) CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric ) CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp ) CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp ) CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp ) CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp ) CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp ) CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text ) CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp ) CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
[ { "role": "user", "content": "Find receiver addresses that have received transactions from more than 5 distinct sender addresses. Show the receiver address and the count of distinct senders." }, { "role": "assistant", "content": "SELECT receiver_address, COUNT(DISTINCT sender_address) FROM blockchain.transactions GROUP BY receiver_address HAVING COUNT(DISTINCT sender_address) > 5;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE blockchain.transactions ( transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction block_id character varying(64) NOT NULL, -- identifier of the block containing the transaction sender_address character varying(128) NOT NULL, -- address of the sender receiver_address character varying(128) NOT NULL, -- address of the receiver amount numeric(38,14) NOT NULL, -- amount transferred timestamp timestamp NOT NULL, -- time when the transaction was created signature text NOT NULL, -- digital signature of the transaction PRIMARY KEY (transaction_id) )
[ { "role": "user", "content": "How many reviews does each staff member respond to, along with their full name and the average response time in hours?" }, { "role": "assistant", "content": "SELECT st.staff_id,\n st.first_name || ' ' || st.last_name AS staff_full_name,\n COUNT(*) AS response_count,\n AVG(EXTRACT(EPOCH FROM (r.response_date - r.review_date)) / 3600) AS avg_response_time_hours\nFROM hospitality_technology.reviews r\nJOIN hospitality_technology.staff st\n ON r.response_staff_id = st.staff_id\nWHERE r.response_date IS NOT NULL\nGROUP BY st.staff_id, st.first_name, st.last_name;" }, { "role": "user", "content": "Filter to only include staff who responded to at least 5 reviews." }, { "role": "assistant", "content": "SELECT sub.staff_id,\n sub.staff_full_name,\n sub.response_count,\n sub.avg_response_time_hours\nFROM (\n SELECT st.staff_id,\n st.first_name || ' ' || st.last_name AS staff_full_name,\n COUNT(*) AS response_count,\n AVG(EXTRACT(EPOCH FROM (r.response_date - r.review_date)) / 3600) AS avg_response_time_hours\n FROM hospitality_technology.reviews r\n JOIN hospitality_technology.staff st\n ON r.response_staff_id = st.staff_id\n WHERE r.response_date IS NOT NULL\n GROUP BY st.staff_id, st.first_name, st.last_name\n) sub\nWHERE sub.response_count >= 5;" }, { "role": "user", "content": "Also order the result by average response time ascending." }, { "role": "assistant", "content": "SELECT sub.staff_id,\n sub.staff_full_name,\n sub.response_count,\n sub.avg_response_time_hours\nFROM (\n SELECT st.staff_id,\n st.first_name || ' ' || st.last_name AS staff_full_name,\n COUNT(*) AS response_count,\n AVG(EXTRACT(EPOCH FROM (r.response_date - r.review_date)) / 3600) AS avg_response_time_hours\n FROM hospitality_technology.reviews r\n JOIN hospitality_technology.staff st\n ON r.response_staff_id = st.staff_id\n WHERE r.response_date IS NOT NULL\n GROUP BY st.staff_id, st.first_name, st.last_name\n) sub\nWHERE sub.response_count >= 5\nORDER BY sub.avg_response_time_hours ASC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp ) CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, -- unique identifier for the room property_id character varying(64) NOT NULL, -- FK to properties table room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B') room_type_id character varying(64) NOT NULL, -- FK to room_types table floor integer, -- floor number the room is on status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi) current_condition text, -- notes on room condition last_cleaned_at timestamp with time zone, -- timestamp of last cleaning PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) ) CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text ) CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp ) CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp ) CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service property_id character varying(64) NOT NULL, -- FK to properties table service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt description text, category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities price numeric(10, 2) NOT NULL, -- price per unit/instance unit character varying(30), -- e.g., Per Item, Per Hour, Per Day is_available boolean NOT NULL DEFAULT true, -- is the service currently offered? department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping) PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) ) CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text ) CREATE TABLE hospitality_technology.payments ( payment_id character varying(64) NOT NULL, -- unique identifier for the payment transaction reservation_id character varying(64), -- FK to reservations (if payment is for a stay) guest_id character varying(64) NOT NULL, -- FK to guests (who paid) bill_id character varying(64), -- FK to bills/invoices this payment applies to amount numeric(12,2) NOT NULL, -- amount of the payment currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR) payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC) card_last_four character varying(4), -- last 4 digits of CC (if CC) transaction_ref character varying(128), -- reference ID from payment gateway or processor payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed staff_id_processed character varying(64), -- FK to staff (who processed the payment) notes text, -- notes about the payment PRIMARY KEY (payment_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id) ) CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )
[ { "role": "user", "content": "Find the average percentage share among all beneficiaries for each distinct relationship type." }, { "role": "assistant", "content": "SELECT relationship, AVG(percentage_share) FROM insurance.policy_beneficiaries GROUP BY relationship ORDER BY relationship;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp ) CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
[ { "role": "user", "content": "Show me the top 5 games by number of online servers in European regions. I want the game title and the server count." }, { "role": "assistant", "content": "SELECT g.title, COUNT(s.server_id) AS server_count\nFROM gaming_technology.games g\nJOIN gaming_technology.servers s ON g.game_id = s.game_id\nWHERE s.region ILIKE 'eu%' AND s.status = 'online'\nGROUP BY g.title\nORDER BY server_count DESC\nLIMIT 5;" }, { "role": "user", "content": "Now include only those games whose average current_players per online server exceeds 100." }, { "role": "assistant", "content": "SELECT g.title,\n COUNT(s.server_id) AS server_count,\n AVG(s.current_players)::numeric(10,2) AS avg_players\nFROM gaming_technology.games g\nJOIN gaming_technology.servers s ON g.game_id = s.game_id\nWHERE s.region ILIKE 'eu%' AND s.status = 'online'\nGROUP BY g.title\nHAVING AVG(s.current_players) > 100\nORDER BY server_count DESC\nLIMIT 5;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb ) CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text ) CREATE TABLE gaming_technology.servers ( server_id uuid PRIMARY KEY, game_id uuid, server_name text, region text, ip_address text, port int, current_players int, max_players int, status text, last_heartbeat timestamptz ) CREATE TABLE gaming_technology.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean ) CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid PRIMARY KEY, player_id uuid, achievement_id uuid, unlocked_at timestamptz ) CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb ) CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )
[ { "role": "user", "content": "I want to list all employees who currently manage at least one other employee, showing their full name, email, and the total number of direct reports for each manager." }, { "role": "assistant", "content": "SELECT e.employee_id, e.first_name || ' ' || e.last_name AS manager_full_name, e.email, COUNT(r.employee_id) AS direct_report_count\nFROM financial_services.employees e\nJOIN financial_services.employees r ON e.employee_id = r.manager_id\nWHERE e.status = 'Active'\nGROUP BY e.employee_id, e.first_name, e.last_name, e.email;" }, { "role": "user", "content": "Can you also include the job_title and department of each manager in the result?" }, { "role": "assistant", "content": "SELECT e.employee_id, e.first_name || ' ' || e.last_name AS manager_full_name, e.email, e.job_title, e.department, COUNT(r.employee_id) AS direct_report_count\nFROM financial_services.employees e\nJOIN financial_services.employees r ON e.employee_id = r.manager_id\nWHERE e.status = 'Active'\nGROUP BY e.employee_id, e.first_name, e.last_name, e.email, e.job_title, e.department;" }, { "role": "user", "content": "I noticed some managers don't have any reports—that shouldn't be the case. Only show managers who have at least two direct reports." }, { "role": "assistant", "content": "SELECT e.employee_id, e.first_name || ' ' || e.last_name AS manager_full_name, e.email, e.job_title, e.department, COUNT(r.employee_id) AS direct_report_count\nFROM financial_services.employees e\nJOIN financial_services.employees r ON e.employee_id = r.manager_id\nWHERE e.status = 'Active'\nGROUP BY e.employee_id, e.first_name, e.last_name, e.email, e.job_title, e.department\nHAVING COUNT(r.employee_id) >= 2;" }, { "role": "user", "content": "Please order the output by the number of direct reports in descending order." }, { "role": "assistant", "content": "SELECT e.employee_id, e.first_name || ' ' || e.last_name AS manager_full_name, e.email, e.job_title, e.department, COUNT(r.employee_id) AS direct_report_count\nFROM financial_services.employees e\nJOIN financial_services.employees r ON e.employee_id = r.manager_id\nWHERE e.status = 'Active'\nGROUP BY e.employee_id, e.first_name, e.last_name, e.email, e.job_title, e.department\nHAVING COUNT(r.employee_id) >= 2\nORDER BY direct_report_count DESC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE financial_services.accounts ( account_id character varying(64) NOT NULL, -- unique identifier for the account customer_id character varying(64) NOT NULL, -- foreign key linking to the customer account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR) opened_date date NOT NULL, -- date the account was opened status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen interest_rate numeric(5, 4), -- annual interest rate, if applicable last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update PRIMARY KEY (account_id), FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id) ) CREATE TABLE financial_services.transactions ( transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction account_id character varying(64) NOT NULL, -- account involved in the transaction related_account_id character varying(64), -- counterpart account for transfers transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest amount numeric(19, 4) NOT NULL, -- transaction amount currency character varying(3) NOT NULL, -- transaction currency transaction_date timestamp NOT NULL, -- exact time of the transaction effective_date date NOT NULL, -- date the transaction affects the balance description text, -- description or memo of the transaction status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed reference_number character varying(128), -- external reference if applicable (e.g., check number) PRIMARY KEY (transaction_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id) ) CREATE TABLE financial_services.employees ( employee_id character varying(64) NOT NULL, -- unique identifier for the employee first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst department character varying(100), -- e.g., Retail Banking, Wealth Management, IT branch_id character varying(64), -- Identifier for the branch they work at (if applicable) email character varying(128) NOT NULL UNIQUE, phone_extension character varying(20), hire_date date NOT NULL, termination_date date, -- Date of termination, null if currently employed manager_id character varying(64), -- Self-referencing key for manager relationship status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave PRIMARY KEY (employee_id), FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id) )
[ { "role": "user", "content": "Give me each server's name, the region, and the maximum number of players that have been connected at once." }, { "role": "assistant", "content": "SELECT s.server_id, s.server_name, s.region, MAX(s.current_players) AS max_players_seen\nFROM gaming_technology.servers s\nGROUP BY s.server_id, s.server_name, s.region;" }, { "role": "user", "content": "Could you also include the associated game title for each server?" }, { "role": "assistant", "content": "SELECT s.server_id, s.server_name, s.region, g.title AS game_title, MAX(s.current_players) AS max_players_seen\nFROM gaming_technology.servers s\nJOIN gaming_technology.games g ON s.game_id = g.game_id\nGROUP BY s.server_id, s.server_name, s.region, g.title;" }, { "role": "user", "content": "Now, can you show only servers where the max number of players ever connected exceeded 20?" }, { "role": "assistant", "content": "SELECT s.server_id, s.server_name, s.region, g.title AS game_title, MAX(s.current_players) AS max_players_seen\nFROM gaming_technology.servers s\nJOIN gaming_technology.games g ON s.game_id = g.game_id\nGROUP BY s.server_id, s.server_name, s.region, g.title\nHAVING MAX(s.current_players) > 20;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb ) CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text ) CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb ) CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance game_id uuid NOT NULL, -- FK linking to the game this server hosts server_name character varying(150), -- display name for the server region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2) ip_address character varying(45), -- IP address (IPv4 or IPv6) port integer, -- network port number current_players integer NOT NULL DEFAULT 0, -- number of players currently connected max_players integer NOT NULL, -- maximum player capacity status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance) last_heartbeat timestamp with time zone, -- last time the server reported its status PRIMARY KEY (server_id) -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id) ) CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean ) CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz ) CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) ) CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )
[ { "role": "user", "content": "For each doctor, list their full name along with the number of prescriptions they have written and the number of unique insurance providers among their patients." }, { "role": "assistant", "content": "SELECT d.doctor_id, d.first_name, d.last_name, COUNT(pr.prescription_id) AS prescriptions_written, COUNT(DISTINCT ip.insurance_provider) AS unique_insurance_providers\nFROM healthcare.doctors d\nLEFT JOIN healthcare.prescriptions pr ON d.doctor_id = pr.doctor_id\nLEFT JOIN healthcare.patient_insurance pi ON pr.patient_id = pi.patient_id\nLEFT JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id\nGROUP BY d.doctor_id, d.first_name, d.last_name;" }, { "role": "user", "content": "Only show doctors who have written more than 20 prescriptions, and also include their specialty in the results." }, { "role": "assistant", "content": "SELECT d.doctor_id, d.first_name, d.last_name, d.specialty, COUNT(pr.prescription_id) AS prescriptions_written, COUNT(DISTINCT ip.insurance_provider) AS unique_insurance_providers\nFROM healthcare.doctors d\nLEFT JOIN healthcare.prescriptions pr ON d.doctor_id = pr.doctor_id\nLEFT JOIN healthcare.patient_insurance pi ON pr.patient_id = pi.patient_id\nLEFT JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id\nGROUP BY d.doctor_id, d.first_name, d.last_name, d.specialty\nHAVING COUNT(pr.prescription_id) > 20;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, -- unique identifier for the patient first_name character varying(100) NOT NULL, -- patient's first name last_name character varying(100) NOT NULL, -- patient's last name date_of_birth date NOT NULL, -- patient's date of birth gender character varying(10), -- patient's gender (e.g., Male, Female, Other) address text, -- patient's home address phone_number character varying(20), -- patient's phone number email character varying(128) UNIQUE, -- patient's email address emergency_contact_name character varying(200), -- name of emergency contact emergency_contact_phone character varying(20), -- phone number of emergency contact created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time PRIMARY KEY (patient_id) ) CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, -- unique identifier for the doctor first_name character varying(100) NOT NULL, -- doctor's first name last_name character varying(100) NOT NULL, -- doctor's last name specialty character varying(100) NOT NULL, -- doctor's medical specialty license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number phone_number character varying(20), -- doctor's contact phone email character varying(128) UNIQUE, -- doctor's contact email hospital_affiliation_id character varying(64), -- FK to hospitals table (optional) created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) ) CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, -- unique identifier for the prescription record_id character varying(64) NOT NULL, -- FK linking to the medical record where it was prescribed patient_id character varying(64) NOT NULL, -- FK to patients table doctor_id character varying(64) NOT NULL, -- FK to prescribing doctor medication_id character varying(64) NOT NULL, -- FK to medications table dosage character varying(100) NOT NULL, -- e.g., '100mg', '1 tablet' frequency character varying(100) NOT NULL, -- e.g., 'Once daily', 'Twice a day with meals' route character varying(50), -- e.g., 'Oral', 'Topical', 'Intravenous' start_date date NOT NULL, -- date prescription begins end_date date, -- date prescription ends (if applicable) quantity_dispensed numeric(10,2), -- amount dispensed (e.g., number of tablets) refills_allowed integer NOT NULL DEFAULT 0, -- number of allowed refills prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) ) CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan plan_name character varying(200) NOT NULL, -- name of the insurance plan insurance_provider character varying(100) NOT NULL, -- name of the insurance company plan_type character varying(50), -- e.g., PPO, HMO, EPO contact_phone character varying(20), -- provider contact number website character varying(255), -- provider website PRIMARY KEY (plan_id) ) CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link patient_id character varying(64) NOT NULL, -- FK to patients table plan_id character varying(64) NOT NULL, -- FK to insurance_plans table policy_number character varying(100) NOT NULL, -- patient's policy number group_number character varying(100), -- group number, if applicable subscriber_name character varying(200), -- name of the primary policy holder effective_date date NOT NULL, -- date the coverage begins expiration_date date, -- date the coverage ends (if known) is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice )
[ { "role": "user", "content": "Show me each service order along with the next order placed by the same guest, including both order IDs and the time difference in minutes between the two orders." }, { "role": "assistant", "content": "SELECT a.order_id,\n b.order_id AS next_order_id,\n EXTRACT(EPOCH FROM (b.order_timestamp - a.order_timestamp)) / 60 AS diff_minutes\nFROM hospitality_technology.service_orders a\nJOIN hospitality_technology.service_orders b\n ON a.guest_id = b.guest_id\n AND b.order_timestamp > a.order_timestamp;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
[ { "role": "user", "content": "Find any two claims made by the same customer on the same day. Return customer_id, the two claim IDs, and the incident date." }, { "role": "assistant", "content": "SELECT c1.customer_id,\n c1.claim_id AS claim1_id,\n c2.claim_id AS claim2_id,\n DATE(c1.incident_date) AS incident_date\nFROM insurance.claims c1\nJOIN insurance.claims c2\n ON c1.customer_id = c2.customer_id\n AND DATE(c1.incident_date) = DATE(c2.incident_date)\n AND c1.claim_id < c2.claim_id;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
[ { "role": "user", "content": "List all pairs of clients who registered on the same day, showing each client's first_name, last_name, and the registration date." }, { "role": "assistant", "content": "SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, DATE(c1.date_registered) AS registration_date FROM legal_services.clients c1 JOIN legal_services.clients c2 ON DATE(c1.date_registered) = DATE(c2.date_registered) AND c1.client_id < c2.client_id;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
[ { "role": "user", "content": "List each citizen's first and last name along with the number of applications they have submitted, only include those with at least 3 applications." }, { "role": "assistant", "content": "SELECT c.first_name, c.last_name, COUNT(a.application_id) AS application_count\nFROM government_services.citizens c\nJOIN government_services.applications a ON c.citizen_id = a.citizen_id\nGROUP BY c.first_name, c.last_name\nHAVING COUNT(a.application_id) >= 3;" }, { "role": "user", "content": "Now also show the average standard fee of the services those applications are associated with." }, { "role": "assistant", "content": "SELECT c.first_name, c.last_name, COUNT(a.application_id) AS application_count, AVG(s.standard_fee) AS avg_service_fee\nFROM government_services.citizens c\nJOIN government_services.applications a ON c.citizen_id = a.citizen_id\nJOIN government_services.services s ON a.service_id = s.service_id\nGROUP BY c.first_name, c.last_name\nHAVING COUNT(a.application_id) >= 3;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE government_services.citizens ( citizen_id.text, national_id_number.text, first_name.text, last_name.text, date_of_birth.date, gender.text, primary_address.text, contact_email.text, contact_phone.text, registration_date.timestamp, is_verified.boolean ) CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text ) CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text ) CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp ) CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text ) CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean ) CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )
[ { "role": "user", "content": "How many messages in total have been sent that do not contain any media attachment?" }, { "role": "assistant", "content": "SELECT COUNT(*) AS non_media_message_count\nFROM social_media.messages\nWHERE media_url IS NULL OR media_url = '';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
[ { "role": "user", "content": "Find all wallets that were created on the same day and list their wallet IDs, addresses, and the creation date." }, { "role": "assistant", "content": "SELECT w1.wallet_id, w1.address, w1.created_at::date AS creation_date FROM web3.wallets w1 JOIN (SELECT created_at::date AS creation_date FROM web3.wallets GROUP BY created_at::date HAVING COUNT(*) > 1) w2 ON w1.created_at::date = w2.creation_date ORDER BY creation_date, w1.wallet_id;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE web3.wallets ( wallet_id character varying(64) NOT NULL, -- unique identifier for the wallet user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet address character varying(128) NOT NULL, -- address of the wallet private_key text NOT NULL, -- private key of the wallet created_at timestamp NOT NULL, -- time when the wallet was created PRIMARY KEY (wallet_id) )
[ { "role": "user", "content": "List all cancelled policies with their cancellation reasons and premium amounts." }, { "role": "assistant", "content": "SELECT policy_id, policy_number, cancellation_reason, premium_amount FROM insurance.policies WHERE status = 'Cancelled';" }, { "role": "user", "content": "Now show only policies that were cancelled within 3 months of their start date." }, { "role": "assistant", "content": "SELECT policy_id, policy_number, cancellation_reason, premium_amount, start_date, cancellation_date FROM insurance.policies WHERE status = 'Cancelled' AND cancellation_date <= start_date + INTERVAL '3 months';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, -- unique identifier for the policy customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers) product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products) agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents) policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number start_date date NOT NULL, -- date the policy coverage begins end_date date NOT NULL, -- date the policy coverage ends premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
[ { "role": "user", "content": "Can you help me get the total number of operational platforms across all stations?" }, { "role": "assistant", "content": "db.platforms.countDocuments({ status: 'Operational' });" } ]
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure // db.createCollection('platforms') // Optional: db.platforms.createIndex({ platform_id: 1 }, { unique: true }) // Optional: db.platforms.createIndex({ station_id: 1 }) { _id: ObjectId(), platform_id: "plat_123", // String (unique) station_id: "station_xyz", // String (references stations.station_id) platform_number: "1A", // String track_number: "T1", // String status: "Operational", // String ('Operational', 'Maintenance', 'Closed') length_meters: 250.50, // Decimal128 or Double accessible: true // Boolean } // db.createCollection('routes') // Optional: db.routes.createIndex({ route_id: 1 }, { unique: true }) { _id: ObjectId(), route_id: "route_ne_corr", // String (unique) route_name: "Northeast Corridor", // String description: "High-speed rail linking Boston and Washington D.C.", // String origin_station_id: "station_bos", // String (references stations.station_id) destination_station_id: "station_was", // String (references stations.station_id) is_active: true // Boolean } // db.createCollection('route_stations') // Optional: db.route_stations.createIndex({ route_station_id: 1 }, { unique: true }) // Optional: db.route_stations.createIndex({ route_id: 1, sequence_order: 1 }, { unique: true }) { _id: ObjectId(), route_station_id: "rs_ne_1", // String (unique) route_id: "route_ne_corr", // String (references routes.route_id) station_id: "station_bos", // String (references stations.station_id) sequence_order: 1, // Int32 distance_from_previous_km: null, // Decimal128 or Double (null for first stop) typical_stop_duration_minutes: null // Int32 (null for origin/destination or if no stop) } // --- OR --- Embed within the Route document: // { // _id: ObjectId(), route_id: "route_ne_corr", ..., // stations: [ // { station_id: "station_bos", sequence_order: 1, distance_from_previous_km: null, typical_stop_duration_minutes: null }, // { station_id: "station_pvd", sequence_order: 2, distance_from_previous_km: 70.5, typical_stop_duration_minutes: 5 }, // ... // ] // } // db.createCollection('schedules') // Optional: db.schedules.createIndex({ schedule_id: 1 }, { unique: true }) // Optional: db.schedules.createIndex({ route_id: 1, departure_datetime: 1 }) { _id: ObjectId(), schedule_id: "sched_1122", // String (unique) train_id: "train_789", // String (references trains.train_id) route_id: "route_ne_corr", // String (references routes.route_id) departure_datetime: ISODate("2024-05-10T08:00:00-04:00"), // Date (with timezone) arrival_datetime: ISODate("2024-05-10T15:30:00-04:00"), // Date (with timezone) status: "Scheduled", // String ('Scheduled', 'On Time', 'Delayed', 'Cancelled', 'Arrived') notes: "Track work expected near Philadelphia" // String } // db.createCollection('schedule_stops') // Optional: db.schedule_stops.createIndex({ stop_id: 1 }, { unique: true }) // Optional: db.schedule_stops.createIndex({ schedule_id: 1, sequence_order: 1 }, { unique: true }) { _id: ObjectId(), stop_id: "stop_sched1122_1", // String (unique) schedule_id: "sched_1122", // String (references schedules.schedule_id) station_id: "station_bos", // String (references stations.station_id) platform_id: "plat_bos_3", // String (references platforms.platform_id, nullable) sequence_order: 1, // Int32 scheduled_arrival_time: null, // Date scheduled_departure_time: ISODate("2024-05-10T08:00:00-04:00"), // Date actual_arrival_time: null, // Date actual_departure_time: ISODate("2024-05-10T08:01:00-04:00"), // Date status: "On Time" // String } // --- OR --- Embed within the Schedule document using an array 'stops' // db.createCollection('passengers') // Optional: db.passengers.createIndex({ passenger_id: 1 }, { unique: true }) // Optional: db.passengers.createIndex({ email: 1 }, { unique: true, sparse: true }) // Optional: db.passengers.createIndex({ phone_number: 1 }, { unique: true, sparse: true }) { _id: ObjectId(), passenger_id: "pass_pqr", // String (unique) first_name: "Alice", // String last_name: "Smith", // String email: "alice.smith@example.com", // String (unique, sparse) phone_number: "+15551234567", // String (unique, sparse) date_of_birth: ISODate("1990-03-20"), // Date loyalty_program_id: "LOYALTY123", // String created_at: ISODate("2023-02-01T11:00:00Z") // Date } // db.createCollection('staff') // Optional: db.staff.createIndex({ staff_id: 1 }, { unique: true }) // Optional: db.staff.createIndex({ employee_number: 1 }, { unique: true }) // Optional: db.staff.createIndex({ contact_email: 1 }, { unique: true, sparse: true }) { _id: ObjectId(), staff_id: "staff_mno", // String (unique) first_name: "Bob", // String last_name: "Jones", // String role: "Conductor", // String primary_station_id: null, // String (references stations.station_id, nullable) employee_number: "E12345", // String (unique) hire_date: ISODate("2018-06-01"), // Date contact_email: "bob.jones@example-rail.com", // String (unique, sparse) contact_phone: "+15559876543", // String is_active: true // Boolean }
[ { "role": "user", "content": "List all patients who have a current prescription that was prescribed by a doctor with a specialty of 'Endocrinology'. Show patient full name, prescription ID, medication name, and prescription date." }, { "role": "assistant", "content": "SELECT p.patient_id, p.first_name || ' ' || p.last_name AS full_name, pr.prescription_id, m.medication_name, pr.prescription_date\nFROM healthcare.prescriptions pr\nJOIN healthcare.medications m ON pr.medication_id = m.medication_id\nJOIN healthcare.patients p ON pr.patient_id = p.patient_id\nJOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id\nWHERE d.specialty = 'Endocrinology' AND pr.end_date IS NULL OR pr.end_date > CURRENT_DATE;" }, { "role": "user", "content": "Include prescriptions that ended within the past 7 days as well." }, { "role": "assistant", "content": "SELECT p.patient_id, p.first_name || ' ' || p.last_name AS full_name, pr.prescription_id, m.medication_name, pr.prescription_date\nFROM healthcare.prescriptions pr\nJOIN healthcare.medications m ON pr.medication_id = m.medication_id\nJOIN healthcare.patients p ON pr.patient_id = p.patient_id\nJOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id\nWHERE d.specialty = 'Endocrinology' AND (pr.end_date IS NULL OR pr.end_date > CURRENT_DATE OR pr.end_date >= CURRENT_DATE - INTERVAL '7 days');" }, { "role": "user", "content": "I got an error: relation \"healthcare.patients\" does not exist. Can you fix it using existing tables only?" }, { "role": "assistant", "content": "SELECT pr.patient_id, pr.prescription_id, m.medication_name, pr.prescription_date\nFROM healthcare.prescriptions pr\nJOIN healthcare.medications m ON pr.medication_id = m.medication_id\nJOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id\nWHERE d.specialty = 'Endocrinology' AND (pr.end_date IS NULL OR pr.end_date > CURRENT_DATE OR pr.end_date >= CURRENT_DATE - INTERVAL '7 days');" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp ) CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp ) CREATE TABLE healthcare.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean ) CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text ) CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp ) CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text ) CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
[ { "role": "user", "content": "Find all wallets created by users in the last 7 days along with any tokens that have a total supply greater than 10 million, showing the wallet address and token details." }, { "role": "assistant", "content": "SELECT w.address AS wallet_address, t.token_name, t.token_symbol, t.total_supply, t.contract_address FROM web3.wallets w JOIN web3.tokens t ON t.total_supply > 10000000 WHERE w.created_at >= CURRENT_DATE - INTERVAL '7 days';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE web3.tokens ( token_id character varying(64) NOT NULL, contract_address character varying(128) NOT NULL, token_name character varying(128) NOT NULL, token_symbol character varying(32) NOT NULL, decimals integer NOT NULL, total_supply numeric(38,14) NOT NULL, PRIMARY KEY (token_id) ) CREATE TABLE web3.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
[ { "role": "user", "content": "Show me all home loans (loan_id, principal_amount, interest_rate) where the current principal balance is more than 75% of the original principal amount, along with the account_id and employee details (first_name, last_name) of the employee who processed the loan application." }, { "role": "assistant", "content": "SELECT l.loan_id, l.principal_amount, l.interest_rate, l.account_id, e.first_name, e.last_name FROM financial_services.loans l JOIN financial_services.employees e ON l.account_id = e.employee_id WHERE l.loan_type = 'Home' AND l.current_principal_balance > (l.principal_amount * 0.75)" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE financial_services.transactions ( transaction_id.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text ) CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp ) CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text ) CREATE TABLE financial_services.employees ( employee_id.text, first_name.text, last_name.text, job_title.text, department.text, branch_id.text, email.text, phone_extension.text, hire_date.date, termination_date.date, manager_id.text, status.text ) CREATE TABLE financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )
[ { "role": "user", "content": "Provide the count of diagnoses by status." }, { "role": "assistant", "content": "SELECT status,\n COUNT(*) AS count\nFROM healthcare.diagnoses\nGROUP BY status;" }, { "role": "user", "content": "Now only include statuses with more than 10 diagnoses." }, { "role": "assistant", "content": "SELECT status,\n COUNT(*) AS count\nFROM healthcare.diagnoses\nGROUP BY status\nHAVING COUNT(*) > 10;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry patient_id character varying(64) NOT NULL, -- FK to patients table doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor) diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10) code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used description text, -- textual description of the diagnosis diagnosis_date date NOT NULL, -- date the diagnosis was made status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out is_chronic boolean DEFAULT false, -- flag for chronic conditions PRIMARY KEY (diagnosis_id) )
[ { "role": "user", "content": "How many users registered in each month?" }, { "role": "assistant", "content": "SELECT date_trunc('month', created_at) AS month,\n COUNT(*) AS registrations\nFROM web3.users\nGROUP BY month\nORDER BY month;" }, { "role": "user", "content": "Actually, show only those months where registrations exceed 10." }, { "role": "assistant", "content": "SELECT date_trunc('month', created_at) AS month,\n COUNT(*) AS registrations\nFROM web3.users\nGROUP BY month\nHAVING COUNT(*) > 10\nORDER BY month;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE web3.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
[ { "role": "user", "content": "I want to find pairs of transactions where one transaction’s related_account_id matches the other’s account_id, indicating reciprocal transfers between accounts." }, { "role": "assistant", "content": "SELECT t1.transaction_id AS outgoing_txn, t2.transaction_id AS incoming_txn, t1.account_id, t1.related_account_id, t1.transaction_date AS outgoing_date, t2.transaction_date AS incoming_date, t1.currency\nFROM financial_services.transactions t1\nJOIN financial_services.transactions t2\n ON t1.related_account_id = t2.account_id\n AND t2.related_account_id = t1.account_id;" }, { "role": "user", "content": "Actually, limit these transactions to those that occurred in the last 90 days." }, { "role": "assistant", "content": "SELECT t1.transaction_id AS outgoing_txn, t2.transaction_id AS incoming_txn, t1.account_id, t1.related_account_id, t1.transaction_date AS outgoing_date, t2.transaction_date AS incoming_date, t1.currency\nFROM financial_services.transactions t1\nJOIN financial_services.transactions t2\n ON t1.related_account_id = t2.account_id\n AND t2.related_account_id = t1.account_id\nWHERE t1.transaction_date >= CURRENT_DATE - INTERVAL '90 days';" }, { "role": "user", "content": "And make sure both transactions use the same currency." }, { "role": "assistant", "content": "SELECT t1.transaction_id AS outgoing_txn, t2.transaction_id AS incoming_txn, t1.account_id, t1.related_account_id, t1.transaction_date AS outgoing_date, t2.transaction_date AS incoming_date, t1.currency\nFROM financial_services.transactions t1\nJOIN financial_services.transactions t2\n ON t1.related_account_id = t2.account_id\n AND t2.related_account_id = t1.account_id\nWHERE t1.transaction_date >= CURRENT_DATE - INTERVAL '90 days'\n AND t1.currency = t2.currency;" }, { "role": "user", "content": "Finally, order the output by the outgoing transaction date descending." }, { "role": "assistant", "content": "SELECT t1.transaction_id AS outgoing_txn, t2.transaction_id AS incoming_txn, t1.account_id, t1.related_account_id, t1.transaction_date AS outgoing_date, t2.transaction_date AS incoming_date, t1.currency\nFROM financial_services.transactions t1\nJOIN financial_services.transactions t2\n ON t1.related_account_id = t2.account_id\n AND t2.related_account_id = t1.account_id\nWHERE t1.transaction_date >= CURRENT_DATE - INTERVAL '90 days'\n AND t1.currency = t2.currency\nORDER BY t1.transaction_date DESC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE financial_services.transactions ( transaction_id text PRIMARY KEY, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
[ { "role": "user", "content": "What is the total and average amount of unspent UTXOs per address?" }, { "role": "assistant", "content": "SELECT\n address,\n COUNT(*) AS utxo_count,\n SUM(amount) AS total_unspent_amount,\n AVG(amount) AS average_unspent_amount\nFROM trading_platform.utxos\nWHERE spent = FALSE\nGROUP BY address;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp ) CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean ) CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) ) CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
[ { "role": "user", "content": "I want to find all appointment pairs where two appointments are scheduled for the same client at overlapping times. Provide the appointment_id from both overlapping appointments." }, { "role": "assistant", "content": "SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2\nFROM legal_services.appointments a1\nJOIN legal_services.appointments a2\n ON a1.client_id = a2.client_id\n AND a1.appointment_id < a2.appointment_id\n AND a1.start_time < a2.end_time\n AND a2.start_time < a1.end_time;" }, { "role": "user", "content": "Actually, only include pairs where both appointments have status 'scheduled'." }, { "role": "assistant", "content": "SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2\nFROM legal_services.appointments a1\nJOIN legal_services.appointments a2\n ON a1.client_id = a2.client_id\n AND a1.appointment_id < a2.appointment_id\n AND a1.start_time < a2.end_time\n AND a2.start_time < a1.end_time\nWHERE a1.status = 'scheduled'\n AND a2.status = 'scheduled';" }, { "role": "user", "content": "And ensure the overlapping appointments start within 1 hour of each other." }, { "role": "assistant", "content": "SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2\nFROM legal_services.appointments a1\nJOIN legal_services.appointments a2\n ON a1.client_id = a2.client_id\n AND a1.appointment_id < a2.appointment_id\n AND a1.start_time < a2.end_time\n AND a2.start_time < a1.end_time\n AND ABS(EXTRACT(EPOCH FROM (a1.start_time - a2.start_time))) <= 3600\nWHERE a1.status = 'scheduled'\n AND a2.status = 'scheduled';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )
[ { "role": "user", "content": "What is the fuel efficiency of the train car with car_id 'TC456'?" }, { "role": "assistant", "content": "I'm sorry, but I don't have access to information about the fuel efficiency of specific train cars. The data available in the train_cars table only includes details such as car_id, train_id, car_number, car_type, class, capacity, and features. If you have another question or need assistance with something else, I'm happy to help." } ]
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE train_station_management.train_cars ( car_id.text, train_id.text, car_number.text, car_type.text, class.text, capacity.integer, features.text )
[ { "role": "user", "content": "List all agencies that do not have a website URL specified. Return their agency_id, agency_name, and main_phone_number." }, { "role": "assistant", "content": "SELECT agency_id, agency_name, main_phone_number FROM government_services.agencies WHERE website_url IS NULL OR website_url = '';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
[ { "role": "user", "content": "List all rooms that have a 'Jacuzzi' feature, including the room_number, property_id, type_name, and base_rate." }, { "role": "assistant", "content": "SELECT r.room_number,\n r.property_id,\n rt.type_name,\n rt.base_rate\nFROM hospitality_technology.rooms AS r\nJOIN hospitality_technology.room_types AS rt\n ON r.room_type_id = rt.room_type_id\n AND r.property_id = rt.property_id\nWHERE r.features ILIKE '%Jacuzzi%';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp ) CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text ) CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp ) CREATE TABLE hospitality_technology.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp ) CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text ) CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text ) CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )
[ { "role": "user", "content": "Could you provide the total number of game sessions and the number of distinct players for each game genre? Display the genre, session count, and player count." }, { "role": "assistant", "content": "SELECT g.genre, COUNT(gs.session_id) AS session_count, COUNT(DISTINCT gs.player_id) AS player_count FROM gaming_technology.game_sessions AS gs JOIN gaming_technology.games AS g ON gs.game_id = g.game_id WHERE g.genre IS NOT NULL GROUP BY g.genre ORDER BY g.genre;" }, { "role": "user", "content": "Thanks. Can you modify the query to only include games that were released after the year 2020?" }, { "role": "assistant", "content": "SELECT g.genre, COUNT(gs.session_id) AS session_count, COUNT(DISTINCT gs.player_id) AS player_count FROM gaming_technology.game_sessions AS gs JOIN gaming_technology.games AS g ON gs.game_id = g.game_id WHERE g.genre IS NOT NULL AND g.release_date >= '2021-01-01' GROUP BY g.genre ORDER BY g.genre;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player username character varying(100) NOT NULL UNIQUE, -- player's chosen display name email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery password_hash text NOT NULL, -- securely hashed password registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created last_login timestamp with time zone, -- timestamp of the last successful login country_code character(2), -- player's country (ISO 3166-1 alpha-2) status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended) profile_data jsonb, -- flexible field for avatar url, bio, preferences etc. PRIMARY KEY (player_id) ) CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game title character varying(200) NOT NULL, -- official title of the game developer_id uuid NOT NULL, -- FK linking to the developers table publisher_id uuid, -- FK linking to a potential publishers table (optional) genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy) release_date date, -- official release date description text, -- short description or synopsis of the game platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile) engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity) website character varying(255), -- official website URL PRIMARY KEY (game_id) -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint ) CREATE TABLE gaming_technology.game_sessions ( session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session player_id uuid NOT NULL, -- FK linking to the players table game_id uuid NOT NULL, -- FK linking to the games table server_id uuid, -- FK linking to the servers table (nullable for single-player) start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began end_time timestamp with time zone, -- when the session ended (null if ongoing) duration_seconds integer, -- calculated duration of the session in seconds score integer, -- player's score for the session, if applicable session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used) PRIMARY KEY (session_id) -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id), -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id), -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id) ) CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance game_id uuid NOT NULL, -- FK linking to the game this server hosts server_name character varying(150), -- display name for the server region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2) ip_address character varying(45), -- IP address (IPv4 or IPv6) port integer, -- network port number current_players integer NOT NULL DEFAULT 0, -- number of players currently connected max_players integer NOT NULL, -- maximum player capacity status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance) last_heartbeat timestamp with time zone, -- last time the server reported its status PRIMARY KEY (server_id) -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id) ) CREATE TABLE gaming_technology.achievements ( achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to name character varying(150) NOT NULL, -- name of the achievement description text NOT NULL, -- how to unlock the achievement icon_url character varying(255), -- URL for the achievement's icon points integer DEFAULT 0, -- points awarded for unlocking (optional) hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked PRIMARY KEY (achievement_id) -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id) ) CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance player_id uuid NOT NULL, -- FK linking to the player who unlocked it achievement_id uuid NOT NULL, -- FK linking to the achievement definition unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id), -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id) )
[ { "role": "user", "content": "Show the name of each agency and whether it operates at least one service location marked as accessible." }, { "role": "assistant", "content": "SELECT T1.agency_name FROM government_services.agencies AS T1 JOIN government_services.service_locations AS T2 ON T1.agency_id = T2.agency_id WHERE T2.is_accessible = TRUE GROUP BY T1.agency_name;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, -- unique identifier for the agency agency_name character varying(255) NOT NULL, -- full name of the government agency jurisdiction_level character varying(50) NOT NULL, -- e.g., Federal, State, County, City primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), -- FK to self for hierarchical structure PRIMARY KEY (agency_id) ) CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, -- unique identifier for the service agency_id character varying(64) NOT NULL, -- FK to agencies table service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal) description text, category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits eligibility_criteria text, -- description of who is eligible standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service average_processing_time_days integer, -- estimated processing time is_active boolean DEFAULT true, -- whether the service is currently offered online_application_url character varying(255), PRIMARY KEY (service_id) ) CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, -- unique identifier for the physical location agency_id character varying(64) NOT NULL, -- FK to agencies table location_name character varying(200), -- e.g., Downtown DMV Office address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, -- description of opening times contact_phone character varying(32), is_accessible boolean, -- accessibility information (e.g., wheelchair access) PRIMARY KEY (location_id) )
[ { "role": "user", "content": "List the reference number and status for applications where the notes contain the keyword 'urgent'." }, { "role": "assistant", "content": "SELECT reference_number, status FROM government_services.applications WHERE notes ILIKE '%urgent%';" }, { "role": "user", "content": "Among those, show only the applications with a status of 'Pending'." }, { "role": "assistant", "content": "SELECT reference_number, status FROM government_services.applications WHERE notes ILIKE '%urgent%' AND status = 'Pending';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
[ { "role": "user", "content": "List all users whose email contains the word 'block', along with their username and registration timestamp." }, { "role": "assistant", "content": "SELECT user_id, username, email, created_at\nFROM web3.users\nWHERE email ILIKE '%block%';" }, { "role": "user", "content": "Can you also include the total number of such users in the result?" }, { "role": "assistant", "content": "SELECT user_id, username, email, created_at, COUNT(*) OVER() AS total_matching_users\nFROM web3.users\nWHERE email ILIKE '%block%';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
[ { "role": "user", "content": "Show the full names and contact emails of all citizens who have applied for services with a standard fee greater than 100." }, { "role": "assistant", "content": "SELECT c.first_name || ' ' || c.last_name AS full_name, c.contact_email\nFROM government_services.citizens c\nJOIN government_services.services s ON c.citizen_id IS NOT NULL -- Replace with actual application linking table if exists\nWHERE s.standard_fee > 100;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) ) CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
[ { "role": "user", "content": "For all NFT collections on the Ethereum blockchain, show me the collection name and the current floor price. Sort by floor price descending." }, { "role": "assistant", "content": "SELECT name, floor_price FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;" }, { "role": "user", "content": "Include also the collection symbol and the number of tokens in each collection." }, { "role": "assistant", "content": "SELECT name, symbol, floor_price, token_count FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;" }, { "role": "user", "content": "Can you also show the owner of each collection in the result?" }, { "role": "assistant", "content": "SELECT name, symbol, floor_price, token_count, owner FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;" }, { "role": "user", "content": "Now only include collections whose floor price is greater than 1 ETH." }, { "role": "assistant", "content": "SELECT name, symbol, floor_price, token_count, owner FROM nft_collections WHERE blockchain = 'Ethereum' AND CAST(floor_price AS FLOAT) > 1 AND floor_price_symbol = 'ETH' ORDER BY CAST(floor_price AS FLOAT) DESC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL ) CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL ) CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL ) CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL ) CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL ) CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL ) CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL ) CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL ) CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL ) CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL ) CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL ) CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL ) CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL ) CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL ) CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )
[ { "role": "user", "content": "What are the maintenance costs for a specific aircraft model like the Airbus A320?" }, { "role": "assistant", "content": "I'm sorry, but I don't have access to data regarding maintenance costs for specific aircraft models such as the Airbus A320. The information in the database is limited to details like model name, manufacturer, passenger capacity, and technical specifications. For maintenance cost information, you may need to consult with the manufacturer or a maintenance service provider." } ]
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE manufacturing.aircraft_models ( model_id character varying(64) NOT NULL, model_name character varying(128) NOT NULL, manufacturer character varying(128) NOT NULL, passenger_capacity integer, max_range_km integer, engine_type character varying(100), wingspan_m numeric(6,2), status character varying(50) NOT NULL, first_flight_date date, PRIMARY KEY (model_id) )
[ { "role": "user", "content": "Count the number of events for each hour of the day based on the emitted_at timestamp." }, { "role": "assistant", "content": "SELECT EXTRACT(HOUR FROM emitted_at) AS event_hour, COUNT(*) AS event_count FROM web3.events GROUP BY event_hour ORDER BY event_hour;" }, { "role": "user", "content": "Actually, only show hours with more than 100 events." }, { "role": "assistant", "content": "SELECT EXTRACT(HOUR FROM emitted_at) AS event_hour, COUNT(*) AS event_count FROM web3.events GROUP BY event_hour HAVING COUNT(*) > 100 ORDER BY event_hour;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
[ { "role": "user", "content": "Show me all insurance plans where the website includes 'secure'." }, { "role": "assistant", "content": "SELECT * FROM healthcare.insurance_plans WHERE website ILIKE '%secure%';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp ) CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp ) CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text ) CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
[ { "role": "user", "content": "Show me the top 5 buyers by total trade volume (quantity * price) in the last 30 days, along with their trade count." }, { "role": "assistant", "content": "SELECT buyer_id, COUNT(trade_id) AS trade_count, SUM(quantity * price) AS total_volume FROM trading_platform.trades WHERE traded_at >= NOW() - INTERVAL '30 days' GROUP BY buyer_id ORDER BY total_volume DESC LIMIT 5" }, { "role": "user", "content": "Now modify the query to also include the average trade price for each buyer." }, { "role": "assistant", "content": "SELECT buyer_id, COUNT(trade_id) AS trade_count, SUM(quantity * price) AS total_volume, AVG(price) AS avg_price FROM trading_platform.trades WHERE traded_at >= NOW() - INTERVAL '30 days' GROUP BY buyer_id ORDER BY total_volume DESC LIMIT 5" }, { "role": "user", "content": "Actually, I want to see the results for sellers instead of buyers, and include the distinct asset count they traded." }, { "role": "assistant", "content": "SELECT seller_id, COUNT(trade_id) AS trade_count, COUNT(DISTINCT asset_id) AS distinct_assets, SUM(quantity * price) AS total_volume, AVG(price) AS avg_price FROM trading_platform.trades WHERE traded_at >= NOW() - INTERVAL '30 days' GROUP BY seller_id ORDER BY total_volume DESC LIMIT 5" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
[ { "role": "user", "content": "Find the total amount paid for all premium payments made in the last 30 days." }, { "role": "assistant", "content": "SELECT SUM(amount_paid) FROM insurance.premium_payments WHERE payment_date >= CURRENT_DATE - INTERVAL '30 day';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, -- unique identifier for the policy customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers) product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products) agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents) policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number start_date date NOT NULL, -- date the policy coverage begins end_date date NOT NULL, -- date the policy coverage ends premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) ) CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, -- unique identifier for the insurance product product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance') product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel' description text, -- detailed description of the product base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments coverage_details text, -- details about what is covered (could be JSON or structured text) underwriting_rules text, -- rules used for assessing risk and eligibility is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) ) CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, -- unique identifier for the payment policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies) customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers) payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received amount_paid numeric(12, 2) NOT NULL, -- amount of the payment payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check transaction_reference character varying(128) UNIQUE, -- reference from payment processor due_date date, -- due date for this payment installment payment_period_start date, -- start date of the period this payment covers payment_period_end date, -- end date of the period this payment covers status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded PRIMARY KEY (payment_id) )
[ { "role": "user", "content": "Find all pairs of contracts deployed by the same deployer on the same day, showing the deployer_address, the deployment date, and both contract IDs." }, { "role": "assistant", "content": "SELECT c1.deployer_address,\n DATE(c1.deployed_at) AS deploy_date,\n c1.contract_id AS contract_id_1,\n c2.contract_id AS contract_id_2\nFROM web3.contracts c1\nJOIN web3.contracts c2\n ON c1.deployer_address = c2.deployer_address\n AND DATE(c1.deployed_at) = DATE(c2.deployed_at)\n AND c1.contract_id < c2.contract_id;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
[ { "role": "user", "content": "What is the detailed repair history of the equipment used by the staff with staff_id 'STAFF123' during maintenance tasks?" }, { "role": "assistant", "content": "I'm sorry, but I can't provide information on the detailed repair history of equipment used by staff members. The data in the maintenance_records table only includes information about maintenance tasks, such as record_id, asset_id, maintenance type, and staff_id, but does not cover equipment repair histories." } ]
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE train_station_management.maintenance_records ( record_id.text, asset_id.text, asset_type.text, maintenance_type.text, staff_id.text, start_datetime.timestamp, end_datetime.timestamp, description.text, cost.numeric, status.text )
[ { "role": "user", "content": "What are the environmental impact assessments for the production of the Airbus A350 model?" }, { "role": "assistant", "content": "I'm sorry, but I don't have access to data regarding the environmental impact assessments for the production of specific aircraft models like the Airbus A350. My information is limited to the technical specifications and basic details stored in the database, such as model name, manufacturer, and capacity. If you have a question related to the available data, I'd be happy to assist." } ]
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE manufacturing.aircraft_models ( model_id text PRIMARY KEY, model_name text, manufacturer text, passenger_capacity int, max_range_km int, engine_type text, wingspan_m numeric, status text, first_flight_date date )
[ { "role": "user", "content": "Which room types offer both 'Sea View' and 'Balcony' amenities? Show their type names, property IDs, and base rates." }, { "role": "assistant", "content": "SELECT type_name, property_id, base_rate FROM hospitality_technology.room_types WHERE amenities LIKE '%Sea View%' AND amenities LIKE '%Balcony%';" }, { "role": "user", "content": "Can you also include the max occupancy and only return results with a base rate of at least 150?" }, { "role": "assistant", "content": "SELECT type_name, property_id, base_rate, max_occupancy FROM hospitality_technology.room_types WHERE amenities LIKE '%Sea View%' AND amenities LIKE '%Balcony%' AND base_rate >= 150;" }, { "role": "user", "content": "Sort the results by max_occupancy descending, and if there's a tie, by base_rate ascending." }, { "role": "assistant", "content": "SELECT type_name, property_id, base_rate, max_occupancy FROM hospitality_technology.room_types WHERE amenities LIKE '%Sea View%' AND amenities LIKE '%Balcony%' AND base_rate >= 150 ORDER BY max_occupancy DESC, base_rate ASC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
[ { "role": "user", "content": "List the latest version of each document (identified by case_id and document_name), showing the version number and its upload_timestamp." }, { "role": "assistant", "content": "SELECT d.case_id,\n d.document_name,\n d.version AS latest_version,\n d.upload_timestamp\nFROM legal_services.documents d\nJOIN (\n SELECT case_id, document_name, MAX(version) AS max_version\n FROM legal_services.documents\n GROUP BY case_id, document_name\n) m ON d.case_id = m.case_id\n AND d.document_name = m.document_name\n AND d.version = m.max_version;" }, { "role": "user", "content": "Actually, I also want to see the upload_timestamp of the previous version for each document." }, { "role": "assistant", "content": "SELECT m.case_id,\n m.document_name,\n m.max_version AS latest_version,\n d_latest.upload_timestamp AS latest_timestamp,\n d_prev.upload_timestamp AS previous_timestamp\nFROM (\n SELECT case_id, document_name, MAX(version) AS max_version\n FROM legal_services.documents\n GROUP BY case_id, document_name\n) m\nJOIN legal_services.documents d_latest\n ON d_latest.case_id = m.case_id\n AND d_latest.document_name = m.document_name\n AND d_latest.version = m.max_version\nLEFT JOIN legal_services.documents d_prev\n ON d_prev.case_id = m.case_id\n AND d_prev.document_name = m.document_name\n AND d_prev.version = m.max_version - 1;" }, { "role": "user", "content": "Also, only include documents whose first version (version = 1) was uploaded in 2024." }, { "role": "assistant", "content": "SELECT m.case_id,\n m.document_name,\n m.max_version AS latest_version,\n d_latest.upload_timestamp AS latest_timestamp,\n d_prev.upload_timestamp AS previous_timestamp\nFROM (\n SELECT case_id, document_name, MAX(version) AS max_version\n FROM legal_services.documents\n GROUP BY case_id, document_name\n) m\nJOIN legal_services.documents d_first\n ON d_first.case_id = m.case_id\n AND d_first.document_name = m.document_name\n AND d_first.version = 1\n AND d_first.upload_timestamp >= '2024-01-01'\n AND d_first.upload_timestamp < '2025-01-01'\nJOIN legal_services.documents d_latest\n ON d_latest.case_id = m.case_id\n AND d_latest.document_name = m.document_name\n AND d_latest.version = m.max_version\nLEFT JOIN legal_services.documents d_prev\n ON d_prev.case_id = m.case_id\n AND d_prev.document_name = m.document_name\n AND d_prev.version = m.max_version - 1;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
[ { "role": "user", "content": "List all rooms, including their room number, the name of the property they belong to, and their room type name, specifically for rooms with 'Maintenance' status." }, { "role": "assistant", "content": "SELECT T1.room_number, T2.property_name, T3.type_name FROM rooms AS T1 JOIN properties AS T2 ON T1.property_id = T2.property_id JOIN room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.status = 'Maintenance'" }, { "role": "user", "content": "Also include the floor number and filter to only show rooms located on floors 5 or higher. Sort the results by property name and then by floor." }, { "role": "assistant", "content": "SELECT T1.room_number, T2.property_name, T3.type_name, T1.floor FROM rooms AS T1 JOIN properties AS T2 ON T1.property_id = T2.property_id JOIN room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.status = 'Maintenance' AND T1.floor >= 5 ORDER BY T2.property_name, T1.floor" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, -- unique identifier for the room property_id character varying(64) NOT NULL, -- FK to properties table room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B') room_type_id character varying(64) NOT NULL, -- FK to room_types table floor integer, -- floor number the room is on status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi) current_condition text, -- notes on room condition last_cleaned_at timestamp with time zone, -- timestamp of last cleaning PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
[ { "role": "user", "content": "List all customers who have two policies with overlapping coverage periods and show both policy numbers along with the overlap start and end dates." }, { "role": "assistant", "content": "SELECT p1.customer_id, p1.policy_number AS policy_number1, p2.policy_number AS policy_number2, GREATEST(p1.start_date, p2.start_date) AS overlap_start, LEAST(p1.end_date, p2.end_date) AS overlap_end FROM insurance.policies p1 JOIN insurance.policies p2 ON p1.customer_id = p2.customer_id AND p1.policy_id < p2.policy_id WHERE p1.start_date <= p2.end_date AND p2.start_date <= p1.end_date;" }, { "role": "user", "content": "Actually, I only want overlapping policies where both policies are currently active." }, { "role": "assistant", "content": "SELECT p1.customer_id, p1.policy_number AS policy_number1, p2.policy_number AS policy_number2, GREATEST(p1.start_date, p2.start_date) AS overlap_start, LEAST(p1.end_date, p2.end_date) AS overlap_end FROM insurance.policies p1 JOIN insurance.policies p2 ON p1.customer_id = p2.customer_id AND p1.policy_id < p2.policy_id WHERE p1.status = 'active' AND p2.status = 'active' AND p1.start_date <= p2.end_date AND p2.start_date <= p1.end_date;" }, { "role": "user", "content": "Also include the number of days of overlap as overlap_days." }, { "role": "assistant", "content": "SELECT p1.customer_id, p1.policy_number AS policy_number1, p2.policy_number AS policy_number2, GREATEST(p1.start_date, p2.start_date) AS overlap_start, LEAST(p1.end_date, p2.end_date) AS overlap_end, (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days FROM insurance.policies p1 JOIN insurance.policies p2 ON p1.customer_id = p2.customer_id AND p1.policy_id < p2.policy_id WHERE p1.status = 'active' AND p2.status = 'active' AND p1.start_date <= p2.end_date AND p2.start_date <= p1.end_date;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
[ { "role": "user", "content": "For wallet address '0xWalletA', list the ERC20 tokens held, showing contract address and amount." }, { "role": "assistant", "content": "SELECT contract_address, amount FROM erc20_balances WHERE wallet_address = '0xWalletA';" }, { "role": "user", "content": "Add the token symbol and name for these tokens." }, { "role": "assistant", "content": "SELECT eb.contract_address, CAST(eb.amount AS DECIMAL) AS raw_amount, tm.symbol, tm.name FROM erc20_balances AS eb JOIN token_metas AS tm ON eb.contract_address = tm.contract_address WHERE eb.wallet_address = '0xWalletA';" }, { "role": "user", "content": "Show the latest USD price for each token and calculate the total USD value for each holding. Order by USD value descending." }, { "role": "assistant", "content": "SELECT eb.contract_address, CAST(eb.amount AS DECIMAL) AS raw_amount, tm.symbol, tm.name, tpl.price, (CAST(eb.amount AS DECIMAL) / POWER(10, tm.decimals) * tpl.price) AS usd_value FROM erc20_balances AS eb JOIN token_metas AS tm ON eb.contract_address = tm.contract_address JOIN token_prices_latest AS tpl ON tm.contract_address = tpl.address WHERE eb.wallet_address = '0xWalletA' ORDER BY usd_value DESC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL ) CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL ) CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL ) CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL ) CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL ) CREATE TABLE sui_coins_metadata ( object_id varchar NOT NULL, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL ) CREATE TABLE sui_nfts ( object_id varchar NOT NULL, status varchar NOT NULL, collection_type varchar NOT NULL, package_id varchar NOT NULL, previous_transaction varchar NOT NULL, display varchar NOT NULL, owner varchar NOT NULL, name varchar NOT NULL ) CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL ) CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL ) CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL ) CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL ) CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL ) CREATE TABLE token_balances ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL ) CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL ) CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL ) CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL ) CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL ) CREATE TABLE token_info_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(255) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL ) CREATE TABLE token_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL ) CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )
[ { "role": "user", "content": "Show me all maintenance logs for 'Oil Change' services performed in the last 3 months, including the vehicle ID, service date, and cost." }, { "role": "assistant", "content": "SELECT vehicle_id, service_date, cost FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '3 months';" }, { "role": "user", "content": "Can you also include the mechanic name and filter to only show services that cost more than $100?" }, { "role": "assistant", "content": "SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '3 months' AND cost > 100;" }, { "role": "user", "content": "Now order these results by service date with the most recent first and limit to 10 records." }, { "role": "assistant", "content": "SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '3 months' AND cost > 100 ORDER BY service_date DESC LIMIT 10;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, -- unique identifier for the maintenance record vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced service_date date NOT NULL, -- date the service was performed odometer_reading integer, -- vehicle mileage at time of service service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair) description text NOT NULL, -- detailed description of work done cost numeric(10, 2), -- cost of the service mechanic_name character varying(128), -- name or ID of the mechanic/shop next_service_due_date date, -- recommended date for next service PRIMARY KEY (log_id) )
[ { "role": "user", "content": "List all auto loans (loan_id, principal_amount, interest_rate) where the current principal balance is less than 40% of the original principal amount, along with the account_id and the difference between principal_amount and current_principal_balance." }, { "role": "assistant", "content": "SELECT loan_id, principal_amount, interest_rate, account_id, (principal_amount - current_principal_balance) AS amount_paid FROM financial_services.loans WHERE loan_type = 'Auto' AND current_principal_balance < (0.4 * principal_amount);" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE financial_services.loans ( loan_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL UNIQUE, loan_type character varying(50) NOT NULL, principal_amount numeric(19, 4) NOT NULL, current_principal_balance numeric(19, 4) NOT NULL, interest_rate numeric(6, 4) NOT NULL, term_months integer NOT NULL, origination_date date NOT NULL, maturity_date date NOT NULL, monthly_payment numeric(12, 4), collateral_description text, status character varying(32) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id) )
[ { "role": "user", "content": "For each relationship type among policy beneficiaries, count how many beneficiaries exist of that type. Provide relationship and count, ordered by count descending." }, { "role": "assistant", "content": "SELECT relationship,\n COUNT(*) AS beneficiary_count\nFROM insurance.policy_beneficiaries\nGROUP BY relationship\nORDER BY beneficiary_count DESC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text ) CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text ) CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text ) CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp ) CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text ) CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text ) CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
[ { "role": "user", "content": "Find all in-game items that have a 'mana_cost' attribute in their attributes JSON. Show the item ID, item name, and the value of the 'mana_cost'." }, { "role": "assistant", "content": "SELECT item_id, item_name, attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items WHERE attributes ? 'mana_cost'" }, { "role": "user", "content": "Now, only include items where the 'mana_cost' is greater than 50." }, { "role": "assistant", "content": "SELECT item_id, item_name, attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items WHERE attributes ? 'mana_cost' AND (attributes ->> 'mana_cost')::int > 50" }, { "role": "user", "content": "Add the item's rarity and the title of the game it belongs to in the output." }, { "role": "assistant", "content": "SELECT t1.item_id, t1.item_name, t1.rarity, t2.title, t1.attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items AS t1 JOIN gaming_technology.games AS t2 ON t1.game_id = t2.game_id WHERE t1.attributes ? 'mana_cost' AND (t1.attributes ->> 'mana_cost')::int > 50" }, { "role": "user", "content": "Filter the results to only include items from games in the 'Fantasy' genre." }, { "role": "assistant", "content": "SELECT t1.item_id, t1.item_name, t1.rarity, t2.title, t1.attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items AS t1 JOIN gaming_technology.games AS t2 ON t1.game_id = t2.game_id WHERE t1.attributes ? 'mana_cost' AND (t1.attributes ->> 'mana_cost')::int > 50 AND t2.genre = 'Fantasy'" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text ) CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz ) CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb ) CREATE TABLE gaming_technology.servers ( server_id uuid PRIMARY KEY, game_id uuid, server_name text, region text, ip_address text, port int, current_players int, max_players int, status text, last_heartbeat timestamptz ) CREATE TABLE gaming_technology.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean ) CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid PRIMARY KEY, player_id uuid, achievement_id uuid, unlocked_at timestamptz ) CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb ) CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )
[ { "role": "user", "content": "List the citizen IDs for individuals who have both uploaded documents and made payments." }, { "role": "assistant", "content": "SELECT DISTINCT T1.citizen_id FROM documents AS T1 JOIN payments AS T2 ON T1.citizen_id = T2.citizen_id" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) ) CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
[ { "role": "user", "content": "List claims along with the name of the insurance product associated with the policy under which the claim was filed. Show claim_id, incident_date, and product_name." }, { "role": "assistant", "content": "SELECT T1.claim_id, T1.incident_date, T3.product_name FROM insurance.claims AS T1 JOIN policies AS T2 ON T1.policy_id = T2.policy_id JOIN insurance.insurance_products AS T3 ON T2.product_id = T3.product_id;" }, { "role": "user", "content": "Only show claims related to 'auto' insurance products." }, { "role": "assistant", "content": "SELECT T1.claim_id, T1.incident_date, T3.product_name FROM insurance.claims AS T1 JOIN policies AS T2 ON T1.policy_id = T2.policy_id JOIN insurance.insurance_products AS T3 ON T2.product_id = T3.product_id WHERE T3.product_type = 'Auto';" }, { "role": "user", "content": "Further filter the results to only include claims with status 'Settled' or 'Closed'." }, { "role": "assistant", "content": "SELECT T1.claim_id, T1.incident_date, T3.product_name FROM insurance.claims AS T1 JOIN policies AS T2 ON T1.policy_id = T2.policy_id JOIN insurance.insurance_products AS T3 ON T2.product_id = T3.product_id WHERE T3.product_type = 'Auto' AND T1.status IN ('Settled', 'Closed');" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, -- unique identifier for the claim policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies) customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers) incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported description text NOT NULL, -- detailed description of the incident and claim estimated_loss numeric(15, 2), -- initial estimated cost of the loss status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled settlement_amount numeric(15, 2), -- final amount paid out settlement_date date, claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters) police_report_number character varying(100), PRIMARY KEY (claim_id) ) CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, -- unique identifier for the insurance product product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance') product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel' description text, -- detailed description of the product base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments coverage_details text, -- details about what is covered (could be JSON or structured text) underwriting_rules text, -- rules used for assessing risk and eligibility is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) ) CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, -- unique identifier for the payment policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies) customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers) payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received amount_paid numeric(12, 2) NOT NULL, -- amount of the payment payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check transaction_reference character varying(128) UNIQUE, -- reference from payment processor due_date date, -- due date for this payment installment payment_period_start date, -- start date of the period this payment covers payment_period_end date, -- end date of the period this payment covers status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded PRIMARY KEY (payment_id) ) CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies) customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly) first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table) last_name character varying(100) NOT NULL, -- beneficiary last name relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent) percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout contact_info text, -- contact details for the beneficiary added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy )
[ { "role": "user", "content": "Which service locations are not accessible and belong to agencies with a jurisdiction level of 'Local'? Show the location name and city." }, { "role": "assistant", "content": "SELECT sl.location_name, sl.city\nFROM government_services.service_locations sl\nINNER JOIN government_services.agencies a ON sl.agency_id = a.agency_id\nWHERE sl.is_accessible = FALSE\n AND a.jurisdiction_level = 'Local';" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text ) CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp ) CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, -- unique identifier for the physical location agency_id character varying(64) NOT NULL, -- FK to agencies table location_name character varying(200), -- e.g., Downtown DMV Office address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, -- description of opening times contact_phone character varying(32), is_accessible boolean, -- accessibility information (e.g., wheelchair access) PRIMARY KEY (location_id) )
[ { "role": "user", "content": "Can you help me fetch the inventory details for components associated with a specific aircraft build, including the batch number, quantity, and warehouse location?" }, { "role": "assistant", "content": "MATCH (ab:AircraftBuild {build_id: 'specific_build_id'})-[:IS_MODEL]->(am:AircraftModel),\n(ib:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)\nRETURN ib.inventory_record_id, ib.batch_number, ib.quantity, ib.location_warehouse" }, { "role": "user", "content": "Can you modify this to show only inventory batches received after a specific date, say June 1, 2023?" }, { "role": "assistant", "content": "MATCH (ab:AircraftBuild {build_id: 'specific_build_id'})-[:IS_MODEL]->(am:AircraftModel),\n(ib:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)\nWHERE ib.received_date > datetime('2023-06-01')\nRETURN ib.inventory_record_id, ib.batch_number, ib.quantity, ib.location_warehouse" }, { "role": "user", "content": "What if I also want to exclude batches with quantities less than 10?" }, { "role": "assistant", "content": "MATCH (ab:AircraftBuild {build_id: 'specific_build_id'})-[:IS_MODEL]->(am:AircraftModel),\n(ib:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)\nWHERE ib.received_date > datetime('2023-06-01') AND ib.quantity >= 10\nRETURN ib.inventory_record_id, ib.batch_number, ib.quantity, ib.location_warehouse" } ]
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure Node Label ':AircraftModel'. Properties: { model_id: String (Constraint: UNIQUE), model_name: String, manufacturer: String, passenger_capacity: Integer, max_range_km: Integer, engine_type: String, wingspan_m: Float, status: String, first_flight_date: Date }. Index on model_id. Node Label ':Material'. Properties: { material_id: String (Constraint: UNIQUE), material_name: String, specification: String, description: String, density_kg_m3: Float, tensile_strength_mpa: Integer }. Index on material_id. Node Label ':AssemblyLine'. Properties: { line_id: String (Constraint: UNIQUE), line_name: String, location_building: String, location_area: String, capacity_units_per_month: Integer, status: String }. Relationship: (:AssemblyLine)-[:BUILDS_MODEL]->(:AircraftModel {model_id}). Index on line_id. Node Label ':AssemblyStep'. Properties: { step_id: String (Constraint: UNIQUE), step_number: Integer, step_name: String, description: String, standard_duration_hours: Float, required_skill_level: String, workstation: String }. Relationship: (:AssemblyLine {line_id})-[:HAS_STEP {sequence: <step_number>}]->(:AssemblyStep). Index on step_id. Node Label ':AircraftBuild'. Properties: { build_id: String (Constraint: UNIQUE), serial_number: String (Constraint: UNIQUE), build_start_date: Datetime, estimated_completion_date: Date, actual_completion_date: Datetime, current_status: String, customer_order_id: String }. Relationships: (:AircraftBuild)-[:IS_MODEL]->(:AircraftModel {model_id}), (:AircraftBuild)-[:ASSEMBLED_ON]->(:AssemblyLine {line_id}). Index on build_id, serial_number, current_status. Node Label ':Employee'. Properties: { employee_id: String (Constraint: UNIQUE), first_name: String, last_name: String, job_title: String, skill_certifications: String[], hire_date: Date, employment_status: String }. Relationships: (:Employee)-[:ASSIGNED_TO]->(:AssemblyLine {line_id}), (:Employee)-[:REPORTS_TO]->(:Employee {employee_id as supervisor_id}). Index on employee_id. Node Label ':InventoryBatch'. Properties: { inventory_record_id: String (Constraint: UNIQUE), quantity: Integer, location_warehouse: String, location_bin: String, received_date: Datetime, expiry_date: Date, batch_number: String, last_updated: Datetime }. Relationship: (:InventoryBatch)-[:IS_INSTANCE_OF]->(:Component {component_id}). Index on inventory_record_id, component_id.
[ { "role": "user", "content": "Show me each product_type along with the count of products for that type, but only include types where the average base_premium exceeds 500. Order the results by the product count in descending order." }, { "role": "assistant", "content": "SELECT product_type,\n COUNT(*) AS product_count\nFROM insurance.insurance_products\nGROUP BY product_type\nHAVING AVG(base_premium) > 500\nORDER BY product_count DESC;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
[ { "role": "user", "content": "For each employee who has verified documents, show their full name and the total number of documents they have verified with a status of 'Verified'." }, { "role": "assistant", "content": "SELECT e.full_name, COUNT(d.document_id) FROM government_services.documents d JOIN employees e ON d.verified_by_employee_id = e.employee_id WHERE d.verification_status = 'Verified' GROUP BY e.full_name;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
[ { "role": "user", "content": "List pairs of citizens who share the same email domain." }, { "role": "assistant", "content": "SELECT c1.first_name AS first1,\n c1.last_name AS last1,\n c2.first_name AS first2,\n c2.last_name AS last2,\n SPLIT_PART(c1.contact_email, '@', 2) AS domain\nFROM government_services.citizens c1\nJOIN government_services.citizens c2\n ON SPLIT_PART(c1.contact_email, '@', 2) = SPLIT_PART(c2.contact_email, '@', 2)\n AND c1.citizen_id < c2.citizen_id\nWHERE c1.contact_email IS NOT NULL\n AND c2.contact_email IS NOT NULL;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, -- unique identifier for the citizen national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, -- full primary residential address contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, -- when the citizen profile was created is_verified boolean DEFAULT false, -- whether identity has been officially verified PRIMARY KEY (citizen_id) )
[ { "role": "user", "content": "Find all patients who have been prescribed medications with dosage greater than 50mg, along with their medication details and prescribing doctor's name." }, { "role": "assistant", "content": "SELECT p.patient_id, p.first_name, p.last_name, pr.dosage, pr.medication_id, pr.start_date, doc.first_name AS doctor_first_name, doc.last_name AS doctor_last_name FROM healthcare.patients p JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id JOIN healthcare.doctors doc ON pr.doctor_id = doc.doctor_id WHERE CAST(SUBSTRING_INDEX(pr.dosage, 'mg', 1) AS UNSIGNED) > 50;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE healthcare.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp ) CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp ) CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean ) CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp ) CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
[ { "role": "user", "content": "What is the average ROI and average realized_ratio for each chain?" }, { "role": "assistant", "content": "SELECT chain,\n AVG(roi) AS avg_roi,\n AVG(realized_ratio) AS avg_realized_ratio\nFROM smart_money_token_performance\nGROUP BY chain;" }, { "role": "user", "content": "Now filter to only include chains where average ROI is above 0.5." }, { "role": "assistant", "content": "WITH stats AS (\n SELECT chain,\n AVG(roi) AS avg_roi,\n AVG(realized_ratio) AS avg_realized_ratio\n FROM smart_money_token_performance\n GROUP BY chain\n)\nSELECT chain, avg_roi, avg_realized_ratio\nFROM stats\nWHERE avg_roi > 0.5;" } ]
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question. ##Table Structure CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
-