[User] Show me all insurance plans that have more than 5 patients enrolled as their primary insurance, along with the provider name and count of patients.

[Assistant] SELECT ip.plan_id, ip.plan_name, ip.insurance_provider, COUNT(pi.patient_id) AS patient_count FROM healthcare.insurance_plans ip JOIN healthcare.patient_insurance pi ON ip.plan_id = pi.plan_id WHERE pi.is_primary = true GROUP BY ip.plan_id, ip.plan_name, ip.insurance_provider HAVING COUNT(pi.patient_id) > 5 ORDER BY patient_count DESC;

System:
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 character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_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 (doctor_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, 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, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )


[User] List pairs of distinct routes that originate from the same location but go to different destinations. Show the route ID and route number for both routes and the common origin location ID.

[Assistant]
SELECT
  r1.route_id AS route1_id,
  r1.route_number AS route1_number,
  r2.route_id AS route2_id,
  r2.route_number AS route2_number,
  r1.origin_location_id AS shared_origin_location_id
FROM transportation.routes AS r1
JOIN transportation.routes AS r2
  ON r1.origin_location_id = r2.origin_location_id
  AND r1.route_id < r2.route_id
WHERE
  r1.destination_location_id != r2.destination_location_id;

System:
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.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )


[User] Show me all wallet addresses and their private keys for users who have more than 3 wallets.

[Assistant] SELECT w.address_id, w.private_key FROM blockchain.wallets w WHERE w.user_id IN (SELECT user_id FROM blockchain.wallets GROUP BY user_id HAVING COUNT(*) > 3);

[User] Now, filter these results to only show wallets where the private_key starts with '0x1'.

[Assistant] SELECT w.address_id, w.private_key FROM blockchain.wallets w WHERE w.user_id IN (SELECT user_id FROM blockchain.wallets GROUP BY user_id HAVING COUNT(*) > 3) AND w.private_key LIKE '0x1%';

System:
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.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_id character varying(128) NOT NULL, -- identifier of the address associated with the wallet
    private_key text NOT NULL, -- private key of the wallet
    PRIMARY KEY (wallet_id)
)


[User] Show me all users who have wallets but have never placed any orders, along with their wallet addresses and creation dates.

[Assistant] SELECT u.user_id, u.email, w.address AS wallet_address, w.created_at FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id LEFT JOIN trading_platform.orders o ON u.user_id = o.user_id WHERE o.order_id IS NULL;

System:
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.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) )
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.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.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.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
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 character varying(64) NOT NULL, user_id character varying(64) NOT NULL, message text NOT NULL, sent_at timestamp NOT NULL, read_at timestamp, PRIMARY KEY (notification_id) )


[User] Show each user and the count of users who registered before them.

[Assistant]
SELECT u.username,
       COUNT(prev.user_id) AS earlier_count
FROM trading_platform.users u
LEFT JOIN trading_platform.users prev
  ON prev.created_at < u.created_at
GROUP BY u.username;

[User] Filter to only include users who have at least 5 earlier users.

[Assistant]
SELECT u.username,
       COUNT(prev.user_id) AS earlier_count
FROM trading_platform.users u
LEFT JOIN trading_platform.users prev
  ON prev.created_at < u.created_at
GROUP BY u.username
HAVING COUNT(prev.user_id) >= 5;

[User] Also include their email and the earliest registration date among the earlier users.

[Assistant]
SELECT u.username,
       u.email,
       COUNT(prev.user_id) AS earlier_count,
       MIN(prev.created_at) AS earliest_prev_created
FROM trading_platform.users u
LEFT JOIN trading_platform.users prev
  ON prev.created_at < u.created_at
GROUP BY u.username, u.email
HAVING COUNT(prev.user_id) >= 5;

[User] Finally, order the results by the earliest_prev_created ascending and limit to the top 10.

[Assistant]
SELECT u.username,
       u.email,
       COUNT(prev.user_id) AS earlier_count,
       MIN(prev.created_at) AS earliest_prev_created
FROM trading_platform.users u
LEFT JOIN trading_platform.users prev
  ON prev.created_at < u.created_at
GROUP BY u.username, u.email
HAVING COUNT(prev.user_id) >= 5
ORDER BY earliest_prev_created ASC
LIMIT 10;

System:
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 text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )


[User] List the names of employees and the names of the cities where their agency operates service locations.

[Assistant]
SELECT e.first_name, e.last_name, sl.city
FROM government_services.employees e
JOIN government_services.service_locations sl ON e.agency_id = sl.agency_id;

[User] Only show employees who work in locations that are accessible.

[Assistant]
SELECT e.first_name, e.last_name, sl.city
FROM government_services.employees e
JOIN government_services.service_locations sl ON e.agency_id = sl.agency_id
WHERE sl.is_accessible = true;

System:
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.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.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 )


[User] List all pairs of diagnoses that belong to the same medical record. Show record_id, diagnosis_id from the first entry as diag1_id, and diagnosis_id from the second entry as diag2_id.

[Assistant]
SELECT d1.record_id,
       d1.diagnosis_id AS diag1_id,
       d2.diagnosis_id AS diag2_id
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.record_id = d2.record_id
 AND d1.diagnosis_id < d2.diagnosis_id;

[User] Only include pairs where both diagnoses are chronic.

[Assistant]
SELECT d1.record_id,
       d1.diagnosis_id AS diag1_id,
       d2.diagnosis_id AS diag2_id
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.record_id = d2.record_id
 AND d1.diagnosis_id < d2.diagnosis_id
WHERE d1.is_chronic = TRUE
  AND d2.is_chronic = TRUE;

System:
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)
)


[User] What is the number of guests per country, grouped by country_code?

[Assistant]
SELECT country_code,
       COUNT(*) AS guest_count
FROM hospitality_technology.guests
GROUP BY country_code;

[User] Only include countries that have at least 5 guests.

[Assistant]
SELECT country_code,
       COUNT(*) AS guest_count
FROM hospitality_technology.guests
GROUP BY country_code
HAVING COUNT(*) >= 5;

[User] Also include the most recently registered guest in each of those countries, showing their full name and created_at.

[Assistant]
WITH country_counts AS (
  SELECT country_code,
         COUNT(*) AS guest_count,
         MAX(created_at) AS last_reg
  FROM hospitality_technology.guests
  GROUP BY country_code
  HAVING COUNT(*) >= 5
)
SELECT cc.country_code,
       cc.guest_count,
       g.first_name || ' ' || g.last_name AS last_guest_name,
       g.created_at          AS last_registration
FROM country_counts cc
JOIN hospitality_technology.guests g
  ON g.country_code = cc.country_code
 AND g.created_at = cc.last_reg;

System:
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 character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )


[User] List pairs of citizens who share the same email domain.

[Assistant]
SELECT c1.first_name AS first1,
       c1.last_name AS last1,
       c2.first_name AS first2,
       c2.last_name AS last2,
       SPLIT_PART(c1.contact_email, '@', 2) AS domain
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON SPLIT_PART(c1.contact_email, '@', 2) = SPLIT_PART(c2.contact_email, '@', 2)
 AND c1.citizen_id < c2.citizen_id
WHERE c1.contact_email IS NOT NULL
  AND c2.contact_email IS NOT NULL;

System:
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)
)


[User] List all ERC20 tokens where the price is between $1 and $10, including their names, symbols, and contract addresses.

[Assistant] SELECT t.name, t.symbol, t.address FROM token_prices_latest t WHERE t.price BETWEEN 1 AND 10;

[User] I think there's an error in your query - it should be joining with sui_coins_metadata on coin_type not address. Also, can you add the current price to the results?

[Assistant] SELECT scm.name, scm.symbol, tpl.address, tpl.price FROM token_prices_latest tpl JOIN sui_coins_metadata scm ON tpl.address = scm.coin_type WHERE tpl.price BETWEEN 1 AND 10;

[User] Now filter these results to only show tokens with decimals equal to 18 and sort by name alphabetically.

[Assistant] SELECT scm.name, scm.symbol, tpl.address, tpl.price FROM token_prices_latest tpl JOIN sui_coins_metadata scm ON tpl.address = scm.coin_type WHERE tpl.price BETWEEN 1 AND 10 AND scm.decimals = 18 ORDER BY scm.name ASC;

System:
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, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text )
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 sui_coins ( object_id.text, status.text, coin_type.text, balance.text, owner.text )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
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 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 erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
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 token_balances_bitcoin ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.text, amount.text )
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
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.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_avalanche ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )


[User] What is the ticket price for a journey on train number T4321?

[Assistant] I'm sorry, but I don't have access to information about ticket prices for specific trains. The data I have is limited to train details such as model, manufacturer, capacity, and maintenance schedules. For ticket pricing, please consult the ticketing office or the official website.

System:
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.trains ( train_id text PRIMARY KEY, train_number text UNIQUE, model text, manufacturer text, year_manufactured int, capacity int, status text, last_maintenance_date date, next_maintenance_date date )


[User] Find all pairs of overlapping payment periods for the same customer. Return customer_id, first payment_id as payment1_id, second payment_id as payment2_id, and both periods' start and end dates.

[Assistant]
SELECT p1.customer_id,
       p1.payment_id AS payment1_id,
       p2.payment_id AS payment2_id,
       p1.payment_period_start AS start1,
       p1.payment_period_end   AS end1,
       p2.payment_period_start AS start2,
       p2.payment_period_end   AS end2
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.customer_id = p2.customer_id
 AND p1.payment_id < p2.payment_id
 -- periods overlap
 AND p1.payment_period_start <= p2.payment_period_end
 AND p2.payment_period_start <= p1.payment_period_end;

System:
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.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)
)


[User] List all pairs of token IDs that share the same decimals value, and show the shared decimals.

[Assistant]
SELECT t1.token_id AS token1_id,
       t2.token_id AS token2_id,
       t1.decimals
FROM web3.tokens t1
JOIN web3.tokens t2
  ON t1.decimals = t2.decimals
 AND t1.token_id < t2.token_id;

System:
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,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)


[User] Show me the top 5 NFT collections with the highest token count on Ethereum, along with their names, symbols, and floor prices.

[Assistant] SELECT n.name, n.symbol, n.floor_price, n.token_count FROM nft_collections n WHERE n.blockchain = 'ethereum' ORDER BY n.token_count DESC LIMIT 5;

[User] Now, join this with the nft_metadata table to include the average rarity score for each collection.

[Assistant] SELECT n.name, n.symbol, n.floor_price, n.token_count, AVG(m.rarity_score) as avg_rarity_score FROM nft_collections n JOIN nft_metadata m ON n.contract_address = m.contract_address WHERE n.blockchain = 'ethereum' GROUP BY n.name, n.symbol, n.floor_price, n.token_count ORDER BY n.token_count DESC LIMIT 5;

[User] Can you filter these results to only show collections with an average rarity score greater than 80?

[Assistant] SELECT n.name, n.symbol, n.floor_price, n.token_count, AVG(m.rarity_score) as avg_rarity_score FROM nft_collections n JOIN nft_metadata m ON n.contract_address = m.contract_address WHERE n.blockchain = 'ethereum' GROUP BY n.name, n.symbol, n.floor_price, n.token_count HAVING AVG(m.rarity_score) > 80 ORDER BY n.token_count DESC LIMIT 5;

System:
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, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
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 text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
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, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
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, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_activities_avalanche ( 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_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] Show all rooms that are on floor 3.

[Assistant] SELECT room_id, property_id, room_number FROM hospitality_technology.rooms WHERE floor = 3;

[User] For these rooms, include the property name and room number.

[Assistant] SELECT r.room_number, p.property_name FROM hospitality_technology.rooms AS r JOIN hospitality_technology.properties AS p ON r.property_id = p.property_id WHERE r.floor = 3;

[User] Also, include the type name and current status for each room.

[Assistant] SELECT r.room_number, p.property_name, rt.type_name, r.status FROM hospitality_technology.rooms AS r JOIN hospitality_technology.properties AS p ON r.property_id = p.property_id JOIN hospitality_technology.room_types AS rt ON r.room_type_id = rt.room_type_id AND r.property_id = rt.property_id WHERE r.floor = 3;

System:
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, 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 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 )


[User] For each vehicle, list its vehicle_id, license_plate, and any older vehicle of the same type (showing older_vehicle_id and older year).

[Assistant]
SELECT cur.vehicle_id,
       cur.license_plate,
       old.vehicle_id AS older_vehicle_id,
       old.year       AS older_vehicle_year
FROM transportation.vehicles cur
JOIN transportation.vehicles old
  ON cur.type = old.type
 AND old.year < cur.year
ORDER BY cur.vehicle_id, old.year DESC;

System:
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 character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)


[User] Find appointments that are longer than 30 minutes.

[Assistant] SELECT * FROM legal_services.appointments WHERE end_time IS NOT NULL AND start_time IS NOT NULL AND end_time > start_time + INTERVAL '30 minutes'

System:
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, 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 )


[User] Show me all pairs of time entries that are associated with the same invoice, including their entry IDs, lawyer IDs, and the shared invoice ID.

[Assistant]
SELECT te1.entry_id AS entry1_id,
       te2.entry_id AS entry2_id,
       te1.lawyer_id,
       te1.invoice_id
FROM legal_services.time_entries te1
JOIN legal_services.time_entries te2
  ON te1.invoice_id = te2.invoice_id
 AND te1.entry_id < te2.entry_id
WHERE te1.invoice_id IS NOT NULL;

System:
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.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)


[User] Which employees have verified more than 5 documents in the last 30 days? Return the employee's full name, department, and the number of verifications.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS full_name, e.department, COUNT(d.document_id) AS verification_count
FROM government_services.documents d
JOIN government_services.employees e ON d.verified_by_employee_id = e.employee_id
WHERE d.verification_status = 'Verified'
  AND d.verification_timestamp >= now() - interval '30 days'
GROUP BY e.first_name, e.last_name, e.department
HAVING COUNT(d.document_id) > 5;

System:
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 character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
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) )
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.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, 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, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )


[User] Can you help me retrieve the list of components made of a specific material along with their supplier details?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id

[User] Can you also include the part number for each component in the result?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
HGET component:<component_id> part_number

[User] If I want to filter out components from a specific supplier, how can I modify the query?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
HGET component:<component_id> part_number
IF HGET component:<component_id> supplier_id != 'sup:ACME_AERO' THEN INCLUDE

[User] Can you also sort the results based on the part number?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
HGET component:<component_id> part_number
IF HGET component:<component_id> supplier_id != 'sup:ACME_AERO' THEN INCLUDE
SORT BY part_number ASC

System:
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
Use Hashes. Key pattern: 'component:<component_id>'. Example: HSET component:LGSTRUT01 part_number "PN-5521-A" component_name "Landing Gear Strut" material_id "mat:TI64" supplier_id "sup:ACME_AERO" ... Consider Sets for reverse lookups (e.g., 'material_components:<material_id>' -> Set<component_id>).


[User] List all pairs of law firms that were founded on the same month and day, showing their names, and the shared founding date. Exclude firms founded on January 1st.

[Assistant] SELECT t1.firm_name AS firm1_name, t2.firm_name AS firm2_name, t1.founded_date FROM legal_services.law_firms AS t1 JOIN legal_services.law_firms AS t2 ON MONTH(t1.founded_date) = MONTH(t2.founded_date) AND DAY(t1.founded_date) = DAY(t2.founded_date) AND t1.firm_id < t2.firm_id WHERE MONTH(t1.founded_date) <> 1 OR DAY(t1.founded_date) <> 1;

System:
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.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )


[User] List all reviews where the cleanliness rating is 3 or below. Include the review comment and the full name of the guest who submitted it.

[Assistant] SELECT T1.comment, T2.first_name, T2.last_name FROM hospitality_technology.reviews AS T1 JOIN hospitality_technology.guests AS T2 ON T1.guest_id = T2.guest_id WHERE T1.rating_cleanliness <= 3;

System:
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,  -- unique identifier for the booking
    property_id character varying(64) NOT NULL, -- FK to properties table
    guest_id character varying(64) NOT NULL, -- FK to guests table (primary guest)
    room_id character varying(64), -- FK to rooms table (assigned room, might be null initially)
    room_type_id character varying(64) NOT NULL, -- FK to room_types table (booked room type)
    check_in_date date NOT NULL, -- scheduled check-in date
    check_out_date date NOT NULL, -- scheduled check-out date
    actual_check_in_ts timestamp with time zone, -- actual check-in time
    actual_check_out_ts timestamp with time zone, -- actual check-out time
    num_adults integer NOT NULL, -- number of adults
    num_children integer DEFAULT 0, -- number of children
    status character varying(50) NOT NULL, -- e.g., Pending, Confirmed, CheckedIn, CheckedOut, Cancelled, NoShow
    booking_source character varying(100), -- e.g., Website, OTA (Expedia, Booking.com), Phone, WalkIn
    rate_plan_id character varying(64), -- FK to rate_plans table (optional)
    total_amount numeric(12, 2), -- estimated or final total cost
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    special_requests text, -- specific guest requests for this booking
    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.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,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    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)
)


[User] Get all active SUI coins with their owner and balance.

[Assistant]
SELECT coin_type, owner, balance
FROM sui_coins
WHERE status = 'active';

[User] Join metadata to include the coin symbol and decimals.

[Assistant]
SELECT c.coin_type,
       m.symbol,
       m.decimals,
       c.owner,
       c.balance
FROM sui_coins c
JOIN sui_coins_metadata m
  ON c.coin_type = m.coin_type
WHERE c.status = 'active';

[User] Only include coins where balance is greater than 500 and add the description.

[Assistant]
SELECT c.coin_type,
       m.symbol,
       m.decimals,
       m.description,
       c.owner,
       c.balance
FROM sui_coins c
JOIN sui_coins_metadata m
  ON c.coin_type = m.coin_type
WHERE c.status = 'active'
  AND CAST(c.balance AS numeric) > 500;

System:
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, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
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, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
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 text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
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 erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
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, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
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 text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] Provide the count of diagnoses by status.

[Assistant]
SELECT status,
       COUNT(*) AS count
FROM healthcare.diagnoses
GROUP BY status;

[User] Now only include statuses with more than 10 diagnoses.

[Assistant]
SELECT status,
       COUNT(*) AS count
FROM healthcare.diagnoses
GROUP BY status
HAVING COUNT(*) > 10;

System:
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)
)


[User] Now, sort the results by the date opened, oldest first, and show only the top 10.

[Assistant] SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE lead_lawyer_id = 'lawyer_abc' AND status = 'Open' AND case_type = 'Criminal' ORDER BY date_opened ASC LIMIT 10;

System:
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.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )


[User] List all pairs of tokens (show token_id for both) that share the same contract address, excluding pairs where the token_id is the same.

[Assistant] SELECT t1.token_id AS token_id1, t2.token_id AS token_id2, t1.contract_address FROM web3.tokens AS t1 JOIN web3.tokens AS t2 ON t1.contract_address = t2.contract_address WHERE t1.token_id < t2.token_id;

System:
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) )


[User] Show me the top 5 projects by valuation that completed fundraising rounds in the last 6 months, along with their narrative information if available.

[Assistant]
SELECT pfr.project_name, pfr.rounds_name, pfr.valuation, pfr.investment_date, ni.narrative, ni.trend_rank
FROM project_fundraising_record pfr
LEFT JOIN narrative_info ni ON pfr.project_name = ni.narrative
WHERE pfr.investment_date >= date_sub(now(), interval 6 month)
ORDER BY pfr.valuation DESC
LIMIT 5;

[User] Can you filter these results to only include projects with valuation over $50 million and add their 24-hour trading volume from the narrative?

[Assistant]
SELECT pfr.project_name, pfr.rounds_name, pfr.valuation, ni.volume_24h
FROM project_fundraising_record pfr
LEFT JOIN narrative_info ni ON pfr.project_name = ni.narrative
WHERE pfr.investment_date >= date_sub(now(), interval 6 month)
AND pfr.valuation > 50000000
ORDER BY pfr.valuation DESC
LIMIT 5;

System:
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) )


[User] For each route that originates from a location of type 'Port', list the route number, the name of the origin location, and the total distance accumulated from all completed trips on this route.

[Assistant]
SELECT
  r.route_number,
  l_origin.name AS origin_location_name,
  SUM(t.distance_km) AS total_accumulated_distance
FROM transportation.routes AS r
JOIN transportation.locations AS l_origin
  ON r.origin_location_id = l_origin.location_id
JOIN transportation.trips AS t
  ON r.route_id = t.route_id
WHERE
  l_origin.type = 'Port' AND t.status = 'Completed'
GROUP BY
  r.route_id,
  r.route_number,
  l_origin.name;

[User] Now, only include routes where the accumulated distance is greater than 5000 kilometers and order the results by accumulated distance descending.

[Assistant]
SELECT
  r.route_number,
  l_origin.name AS origin_location_name,
  SUM(t.distance_km) AS total_accumulated_distance
FROM transportation.routes AS r
JOIN transportation.locations AS l_origin
  ON r.origin_location_id = l_origin.location_id
JOIN transportation.trips AS t
  ON r.route_id = t.route_id
WHERE
  l_origin.type = 'Port' AND t.status = 'Completed'
GROUP BY
  r.route_id,
  r.route_number,
  l_origin.name
HAVING
  SUM(t.distance_km) > 5000
ORDER BY
  total_accumulated_distance DESC;

[User] Also include the number of completed trips for each of these routes and filter further to only show routes that have had more than 5 completed trips.

[Assistant]
SELECT
  r.route_number,
  l_origin.name AS origin_location_name,
  SUM(t.distance_km) AS total_accumulated_distance,
  COUNT(t.trip_id) AS completed_trip_count
FROM transportation.routes AS r
JOIN transportation.locations AS l_origin
  ON r.origin_location_id = l_origin.location_id
JOIN transportation.trips AS t
  ON r.route_id = t.route_id
WHERE
  l_origin.type = 'Port' AND t.status = 'Completed'
GROUP BY
  r.route_id,
  r.route_number,
  l_origin.name
HAVING
  SUM(t.distance_km) > 5000 AND COUNT(t.trip_id) > 5
ORDER BY
  total_accumulated_distance DESC;

System:
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.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )


[User] For each player, count the total number of achievements they've unlocked.

[Assistant]
SELECT player_id,
       COUNT(*) AS total_achievements
FROM gaming_technology.player_achievements
GROUP BY player_id;

[User] Exclude players with fewer than 10 achievements.

[Assistant]
SELECT player_id,
       COUNT(*) AS total_achievements
FROM gaming_technology.player_achievements
GROUP BY player_id
HAVING COUNT(*) >= 10;

[User] Additionally, provide the month when they achieved their 10th achievement. Show player_id, total_achievements, and the month of the 10th unlock.

[Assistant]
WITH ranked AS (
  SELECT player_id,
         unlocked_at,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at) AS rn
  FROM gaming_technology.player_achievements
),
counts AS (
  SELECT player_id,
         COUNT(*) AS total_achievements
  FROM gaming_technology.player_achievements
  GROUP BY player_id
  HAVING COUNT(*) >= 10
)
SELECT c.player_id,
       c.total_achievements,
       EXTRACT(MONTH FROM r.unlocked_at) AS tenth_achievement_month
FROM counts c
JOIN ranked r
  ON c.player_id = r.player_id
 AND r.rn = 10;

[User] Finally, order by total_achievements descending.

[Assistant]
WITH ranked AS (
  SELECT player_id,
         unlocked_at,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at) AS rn
  FROM gaming_technology.player_achievements
),
counts AS (
  SELECT player_id,
         COUNT(*) AS total_achievements
  FROM gaming_technology.player_achievements
  GROUP BY player_id
  HAVING COUNT(*) >= 10
)
SELECT c.player_id,
       c.total_achievements,
       EXTRACT(MONTH FROM r.unlocked_at) AS tenth_achievement_month
FROM counts c
JOIN ranked r
  ON c.player_id = r.player_id
 AND r.rn = 10
ORDER BY c.total_achievements DESC;

System:
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.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)
)


[User] List all claims along with the first and last names of the agent who is currently handling each claim.

[Assistant]
SELECT c.claim_id, c.policy_id, c.incident_date, a.first_name AS agent_first_name, a.last_name AS agent_last_name
FROM insurance.claims c
JOIN insurance.agents a ON c.claim_handler_id = a.agent_id;

System:
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.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )


[User] List all loans (loan_id, loan_type, principal_amount) that have a current principal balance less than 25% of the original principal amount, along with their account_id and the difference between principal_amount and current_principal_balance.

[Assistant] SELECT loan_id, loan_type, principal_amount, account_id, (principal_amount - current_principal_balance) AS amount_paid FROM financial_services.loans WHERE current_principal_balance < (0.25 * principal_amount);

System:
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 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 )


[User] 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.

[Assistant]
SELECT product_type,
       COUNT(*) AS product_count
FROM insurance.insurance_products
GROUP BY product_type
HAVING AVG(base_premium) > 500
ORDER BY product_count DESC;

System:
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 )


[User] List tokens with trend rank 5 or better and a price below $1. Show symbol, price, and trend rank.

[Assistant] SELECT token_symbol, price, trend_rank FROM token_dexpool_info WHERE trend_rank IS NOT NULL AND trend_rank <= 5 AND price < 1;

System:
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_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )


[User] What is the current market price of a Boeing 737 MAX aircraft?

[Assistant] I'm sorry, but I don't have access to the current market price of aircraft models. The data I have is limited to technical specifications and general information about aircraft models such as passenger capacity, range, and status. For pricing information, you may need to consult with manufacturers or industry reports.

System:
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,  -- unique identifier for the aircraft model
    model_name character varying(128) NOT NULL, -- commercial name of the model (e.g., 737 MAX, A320neo)
    manufacturer character varying(128) NOT NULL, -- manufacturer name (e.g., Boeing, Airbus)
    passenger_capacity integer, -- typical passenger capacity
    max_range_km integer, -- maximum flight range in kilometers
    engine_type character varying(100), -- type of engines used
    wingspan_m numeric(6,2), -- wingspan in meters
    status character varying(50) NOT NULL, -- e.g., 'In Production', 'Development', 'Discontinued'
    first_flight_date date, -- date of the model's first flight
    PRIMARY KEY (model_id)
)


[User] Show me all messages sent after July 1, 2024, including the sender_user_id, content, and sent_at.

[Assistant]
SELECT message_id, sender_user_id, content, sent_at
FROM social_media.messages
WHERE sent_at > '2024-07-01';

[User] Can you also include the conversation_id and only show messages that have not been read yet?

[Assistant]
SELECT message_id, sender_user_id, conversation_id, content, sent_at
FROM social_media.messages
WHERE sent_at > '2024-07-01' AND read_at IS NULL;

[User] Now only show results where the message contains a media attachment and order the results by sent_at descending.

[Assistant]
SELECT message_id, sender_user_id, conversation_id, content, sent_at
FROM social_media.messages
WHERE sent_at > '2024-07-01' AND read_at IS NULL AND media_url IS NOT NULL AND media_url <> ''
ORDER BY sent_at DESC;

System:
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 )


[User] Provide a list of all vehicles and the total quantity of fuel refueled for each vehicle.

[Assistant] SELECT T1.license_plate, sum(T2.quantity) FROM transportation.vehicles AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id = T2.vehicle_id GROUP BY T1.license_plate

System:
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 )


[User] Find the service locations that are not accessible and located in the state of 'California'. List their name, address, and city.

[Assistant] SELECT location_name ,  address ,  city FROM government_services.service_locations WHERE is_accessible = false AND state = 'California'

System:
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.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 )


[User] List lawyers who have any unbilled time entries. Show their first name, last name, and the count of their unbilled entries.

[Assistant] SELECT T1.first_name, T1.last_name, COUNT(T2.entry_id) FROM lawyers AS T1 JOIN time_entries AS T2 ON T1.lawyer_id = T2.lawyer_id WHERE T2.is_billed = false GROUP BY T1.lawyer_id, T1.first_name, T1.last_name;

[User] Modify that query to only include entries marked as billable, and instead show the total hours spent rather than the count.

[Assistant] SELECT T1.first_name, T1.last_name, SUM(T2.hours_spent) FROM lawyers AS T1 JOIN time_entries AS T2 ON T1.lawyer_id = T2.lawyer_id WHERE T2.is_billed = false AND T2.is_billable = true GROUP BY T1.lawyer_id, T1.first_name, T1.last_name;

[User] Now, only show lawyers with more than 10 unbilled billable hours in total, and sort the results by the total hours descending.

[Assistant] SELECT T1.first_name, T1.last_name, SUM(T2.hours_spent) FROM lawyers AS T1 JOIN time_entries AS T2 ON T1.lawyer_id = T2.lawyer_id WHERE T2.is_billed = false AND T2.is_billable = true GROUP BY T1.lawyer_id, T1.first_name, T1.last_name HAVING SUM(T2.hours_spent) > 10 ORDER BY SUM(T2.hours_spent) DESC;

System:
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.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
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 )


[User] Show me all SUI coins with a balance greater than 1000, including their symbol and name.

[Assistant] SELECT sc.object_id, sc.coin_type, sc.balance, scm.symbol, scm.name FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE CAST(sc.balance AS DECIMAL) > 1000;

[User] Also, include the owner address for each coin in the result.

[Assistant] SELECT sc.object_id, sc.coin_type, sc.balance, sc.owner, scm.symbol, scm.name FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE CAST(sc.balance AS DECIMAL) > 1000;

[User] Only show coins which are currently 'active', and add the coin description.

[Assistant] SELECT sc.object_id, sc.coin_type, sc.balance, sc.owner, scm.symbol, scm.name, scm.description FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE CAST(sc.balance AS DECIMAL) > 1000 AND sc.status = 'active' AND scm.status = 'active';

[User] Actually, limit the result to just 10 coins and sort them by balance descending.

[Assistant] SELECT sc.object_id, sc.coin_type, sc.balance, sc.owner, scm.symbol, scm.name, scm.description FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE CAST(sc.balance AS DECIMAL) > 1000 AND sc.status = 'active' AND scm.status = 'active' ORDER BY CAST(sc.balance AS DECIMAL) DESC LIMIT 10;

System:
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 erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk integer )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk integer )
CREATE TABLE sui_coins ( object_id varchar, status varchar, coin_type varchar, balance varchar, owner varchar )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain varchar, contract_address varchar, name varchar, symbol varchar, deploy_block_number bigint, deploy_block_time bigint, erc_type varchar, owner varchar, traits varchar, description varchar, slug varchar, media_info varchar, image_url varchar, banner_image_url varchar, updated_at bigint, banner varchar, token_count bigint, floor_price varchar, floor_price_symbol varchar, floor_price_contract varchar, pk integer )
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_activities ( 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 )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


[User] Find all pairs of distinct routes that share the same origin location ID. List the route IDs and route numbers for both routes in each pair, along with the shared origin location ID.

[Assistant] SELECT r1.route_id AS route1_id, r1.route_number AS route1_number, r2.route_id AS route2_id, r2.route_number AS route2_number, r1.origin_location_id FROM transportation.routes AS r1 JOIN transportation.routes AS r2 ON r1.origin_location_id = r2.origin_location_id WHERE r1.route_id < r2.route_id;

System:
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.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )


[User] For each asset, calculate the total quantity and average price of orders that have status 'filled'.

[Assistant]
SELECT o.asset_id,
       SUM(o.quantity) AS total_quantity,
       AVG(o.price)     AS average_price
FROM trading_platform.orders o
WHERE o.status = 'filled'
GROUP BY o.asset_id;

System:
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.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)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
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 character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications (
    notification_id character varying(64) NOT NULL,  -- unique identifier for the notification
    user_id character varying(64) NOT NULL, -- identifier of the user receiving the notification
    message text NOT NULL, -- message of the notification
    sent_at timestamp NOT NULL, -- time when the notification was sent
    read_at timestamp, -- time when the notification was read
    PRIMARY KEY (notification_id)
)


[User] Show each policy number and the total amount paid for it across all premium payments received so far.

[Assistant] SELECT T1.policy_number, SUM(T2.amount_paid) FROM insurance.policies AS T1 JOIN insurance.premium_payments AS T2 ON T1.policy_id = T2.policy_id GROUP BY T1.policy_number;

System:
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, 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 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 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.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
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.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )


[User] Retrieve the first_name, last_name, and email of all passengers who have never made a booking.

[Assistant]
SELECT
  p.first_name,
  p.last_name,
  p.email
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
WHERE b.booking_id IS NULL;

System:
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.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )