[User] Show me all loans (loan_id, loan_type, principal_amount) where the current principal balance is less than 30% of the original principal amount, along with their account_id and status.

[Assistant] SELECT loan_id, loan_type, principal_amount, account_id, status FROM financial_services.loans WHERE current_principal_balance < 0.3 * principal_amount;

[User] Now modify the query to only include active loans (status = 'Active') and sort them by principal_amount in descending order.

[Assistant] SELECT loan_id, loan_type, principal_amount, account_id, status FROM financial_services.loans WHERE current_principal_balance < 0.3 * principal_amount AND status = 'Active' ORDER BY principal_amount 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 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] List all beneficiaries who have a percentage share greater than 75%. Show their first name, last name, and percentage share.

[Assistant] SELECT T1.first_name, T1.last_name, T1.percentage_share FROM insurance.policy_beneficiaries AS T1 WHERE T1.percentage_share > 75;

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.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
CREATE TABLE insurance.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)


[User] List the username and email of users whose first wallet creation date is the same day as their user registration date.

[Assistant] SELECT u.username, u.email FROM web3.users u JOIN (SELECT user_id, MIN(created_at) as first_wallet_created_at FROM web3.wallets GROUP BY user_id) w ON u.user_id = w.user_id WHERE DATE(u.created_at) = DATE(w.first_wallet_created_at);

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.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
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)
)
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE web3.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)


[User] Find all wallets created by users in the last 7 days along with any tokens that have a total supply greater than 10 million, showing the wallet address and token details.

[Assistant] SELECT w.address AS wallet_address, t.token_name, t.token_symbol, t.total_supply, t.contract_address FROM web3.wallets w JOIN web3.tokens t ON t.total_supply > 10000000 WHERE w.created_at >= CURRENT_DATE - INTERVAL '7 days';

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) )
CREATE TABLE web3.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )


[User] Show me all wallet addresses that belong to user_id 'U1001', along with their private keys.

[Assistant] SELECT address_id, private_key FROM blockchain.wallets WHERE user_id = 'U1001';

[User] Now join this with another table to show the count of transactions for each of these wallet addresses.

[Assistant] Note: The schema only includes the wallets table. Without a transactions table in the schema, this query cannot be executed. Please provide the transactions table structure if you need this analysis.

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 text, user_id text, address_id text, private_key text )


[User] What is the total estimated_loss and average settlement_amount for all claims with status 'Approved'?

[Assistant]
SELECT SUM(estimated_loss) AS total_estimated_loss,
       AVG(settlement_amount) AS average_settlement
FROM insurance.claims
WHERE status = 'Approved';

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 text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )


[User] For each open case, find the latest document uploaded: include case_number, document_name, and upload_timestamp.

[Assistant]
SELECT c.case_number,
       d.document_name,
       d.upload_timestamp
FROM legal_services.cases c
JOIN (
  SELECT case_id,
         document_name,
         upload_timestamp,
         ROW_NUMBER() OVER (PARTITION BY case_id ORDER BY upload_timestamp DESC) AS rn
  FROM legal_services.documents
) d ON c.case_id = d.case_id AND d.rn = 1
WHERE c.status = 'Open';

[User] Only include document types 'Brief' or 'Evidence' and order by upload_timestamp descending.

[Assistant]
SELECT c.case_number,
       d.document_name,
       d.upload_timestamp
FROM legal_services.cases c
JOIN (
  SELECT case_id,
         document_name,
         upload_timestamp,
         document_type,
         ROW_NUMBER() OVER (PARTITION BY case_id ORDER BY upload_timestamp DESC) AS rn
  FROM legal_services.documents
  WHERE document_type IN ('Brief', 'Evidence')
) d ON c.case_id = d.case_id AND d.rn = 1
WHERE c.status = 'Open'
ORDER BY d.upload_timestamp 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.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
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] For each claim, show the corresponding product_type of the insurance product for the related policy.

[Assistant]
SELECT cl.claim_id, ip.product_type
FROM insurance.claims cl
JOIN insurance.policies p ON cl.policy_id = p.policy_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id;

[User] Sorry, there is no policies table, I got an error. Can you try joining claims to insurance_products another way?

[Assistant]
-- Unable to join directly since there is no 'policies' table connecting claims to insurance_products. If policy_id equals product_id, you may try:
SELECT claim_id, policy_id, product_type
FROM insurance.claims
JOIN insurance.insurance_products ON claims.policy_id = insurance_products.product_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.customers ( customer_id.text, 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.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )


[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] 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] Show me the total traded volume and the average price per security for trades executed last month.

[Assistant]
SELECT s.ticker_symbol,
       SUM(t.quantity) AS total_volume,
       AVG(t.price_per_unit) AS avg_price
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month')
  AND t.trade_timestamp < date_trunc('month', CURRENT_DATE)
GROUP BY s.ticker_symbol;

[User] Filter to only include those trades with status 'SETTLED' and execution_venue 'NYSE'.

[Assistant]
SELECT s.ticker_symbol,
       SUM(t.quantity) AS total_volume,
       AVG(t.price_per_unit) AS avg_price
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month')
  AND t.trade_timestamp < date_trunc('month', CURRENT_DATE)
  AND t.status = 'SETTLED'
  AND t.execution_venue = 'NYSE'
GROUP BY s.ticker_symbol;

[User] Now exclude any securities where the summed quantity is less than 1000.

[Assistant]
SELECT s.ticker_symbol,
       SUM(t.quantity) AS total_volume,
       AVG(t.price_per_unit) AS avg_price
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month')
  AND t.trade_timestamp < date_trunc('month', CURRENT_DATE)
  AND t.status = 'SETTLED'
  AND t.execution_venue = 'NYSE'
GROUP BY s.ticker_symbol
HAVING SUM(t.quantity) >= 1000;

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.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)
CREATE TABLE financial_services.trades ( trade_id.text, account_id.text, security_id.text, order_id.text, trade_type.text, quantity.numeric, price_per_unit.numeric, total_amount.numeric, commission.numeric, trade_timestamp.timestamp, settlement_date.date, status.text, execution_venue.text )
CREATE TABLE financial_services.market_data ( data_point_id bigint, security_id text, data_timestamp timestamp, open_price numeric, high_price numeric, low_price numeric, close_price numeric, adjusted_close_price numeric, volume bigint, source text )
CREATE TABLE financial_services.employees ( employee_id text, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )


[User] Find pairs of wallet IDs that belong to the same user, showing the user ID and the two wallet IDs.

[Assistant] SELECT w1.user_id, w1.wallet_id AS wallet1_id, w2.wallet_id AS wallet2_id FROM web3.wallets w1 JOIN web3.wallets w2 ON w1.user_id = w2.user_id AND w1.wallet_id < w2.wallet_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.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )


[User] How many unique patient records are there for each gender?

[Assistant] SELECT gender, COUNT(DISTINCT patient_id) AS patient_count FROM healthcare.patients GROUP BY gender;

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.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )


[User] List all managers (employees who have other employees reporting to them) along with the count of their direct reports, showing only those with more than 5 reports.

[Assistant] SELECT e.employee_id, e.first_name, e.last_name, COUNT(r.employee_id) as direct_reports_count FROM financial_services.employees e JOIN financial_services.employees r ON e.employee_id = r.manager_id WHERE e.status = 'Active' GROUP BY e.employee_id, e.first_name, e.last_name HAVING COUNT(r.employee_id) > 5 ORDER BY direct_reports_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 financial_services.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )


[User] List all Sui NFT collections where the owner is not null, including their name and collection_type.

[Assistant] SELECT name, collection_type FROM sui_nfts WHERE owner IS NOT NULL;

[User] Can you also include the display field and filter to only show collections with a package_id starting with '0x'?

[Assistant] SELECT name, collection_type, display FROM sui_nfts WHERE owner IS NOT NULL AND package_id LIKE '0x%';

[User] Now sort these results by name in ascending order and limit to 10.

[Assistant] SELECT name, collection_type, display FROM sui_nfts WHERE owner IS NOT NULL AND package_id LIKE '0x%' ORDER BY name 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 token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
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_metadata ( object_id varchar NOT NULL, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
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_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, 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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_bitcoin (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(255) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities_bitcoin (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(62) NOT NULL, -- Address sending the inscription
    to_address varchar(62) NOT NULL  -- Address receiving the inscription
)
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )


[User] Can you provide the total number of maintenance records for a specific train with train_id 'train_789'?

[Assistant]
MATCH (t:Train {train_id: 'train_789'})<-[:PERFORMED_ON]-(mr:MaintenanceRecord)
RETURN COUNT(mr) AS total_maintenance_records

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
// Node Label: :Platform
// Properties:
//   platform_id: String (Constraint: UNIQUE)
//   platform_number: String
//   track_number: String
//   status: String
//   length_meters: Float
//   accessible: Boolean
// Relationship: (:Platform)-[:LOCATED_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (s:Station {station_id: 'station_xyz'})
// CREATE (p:Platform {platform_id: 'plat_123', ...})-[:LOCATED_AT]->(s)
// Node Label: :Train
// Properties:
//   train_id: String (Constraint: UNIQUE)
//   train_number: String (Constraint: UNIQUE)
//   model: String
//   manufacturer: String
//   year_manufactured: Integer
//   capacity: Integer
//   status: String
//   last_maintenance_date: Date
//   next_maintenance_date: Date
// Example Cypher CREATE:
// CREATE (:Train {train_id: 'train_789', train_number: 'Acela 2151', ...})
// Node Label: :TrainCar
// Properties:
//   car_id: String (Constraint: UNIQUE)
//   car_number: String
//   car_type: String
//   class: String
//   capacity: Integer
//   features: String (Or List<String> if driver supports)
// Relationship: (:TrainCar)-[:PART_OF_TRAIN]->(:Train)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'})
// CREATE (c:TrainCar {car_id: 'car_abc', ...})-[:PART_OF_TRAIN]->(t)
// Node Label: :Route
// Properties:
//   route_id: String (Constraint: UNIQUE)
//   route_name: String
//   description: String
//   is_active: Boolean
// Relationships:
//   (:Route)-[:STARTS_AT]->(:Station)
//   (:Route)-[:ENDS_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (origin:Station {station_id: 'station_bos'}), (dest:Station {station_id: 'station_was'})
// CREATE (r:Route {route_id: 'route_ne_corr', ...})-[:STARTS_AT]->(origin), (r)-[:ENDS_AT]->(dest)
// Relationship: (:Route)-[rel:HAS_STOP]->(:Station)
// Relationship Properties on :HAS_STOP:
//   sequence_order: Integer
//   distance_from_previous_km: Float
//   typical_stop_duration_minutes: Integer
// Example Cypher CREATE:
// MATCH (r:Route {route_id: 'route_ne_corr'}), (s:Station {station_id: 'station_pvd'})
// CREATE (r)-[:HAS_STOP {sequence_order: 2, distance_from_previous_km: 70.5, ...}]->(s)
// Node Label: :ScheduledTrip (or just :Trip)
// Properties:
//   schedule_id: String (Constraint: UNIQUE)
//   departure_datetime: DateTime
//   arrival_datetime: DateTime
//   status: String
//   notes: String
// Relationships:
//   (:ScheduledTrip)-[:USES_TRAIN]->(:Train)
//   (:ScheduledTrip)-[:FOLLOWS_ROUTE]->(:Route)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'}), (r:Route {route_id: 'route_ne_corr'})
// CREATE (sched:ScheduledTrip {schedule_id: 'sched_1122', ...})-[:USES_TRAIN]->(t), (sched)-[:FOLLOWS_ROUTE]->(r)
// Relationship: (:ScheduledTrip)-[rel:SCHEDULED_STOP]->(:Station)
// Relationship Properties on :SCHEDULED_STOP:
//   sequence_order: Integer
//   platform_id: String (references Platform node if modeled, or just store ID)
//   scheduled_arrival_time: DateTime
//   scheduled_departure_time: DateTime
//   actual_arrival_time: DateTime
//   actual_departure_time: DateTime
//   status: String
// Example Cypher CREATE:
// MATCH (sched:ScheduledTrip {schedule_id: 'sched_1122'}), (s:Station {station_id: 'station_pvd'})
// CREATE (sched)-[:SCHEDULED_STOP {sequence_order: 2, platform_id: 'plat_pvd_1', ...}]->(s)
// Node Label: :Passenger
// Properties:
//   passenger_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   email: String (Constraint: UNIQUE, if not null)
//   phone_number: String (Constraint: UNIQUE, if not null)
//   date_of_birth: Date
//   loyalty_program_id: String
//   created_at: DateTime
// Example Cypher CREATE:
// CREATE (:Passenger {passenger_id: 'pass_pqr', first_name: 'Alice', ...})
// Node Label: :Booking
// Properties:
//   booking_id: String (Constraint: UNIQUE)
//   booking_datetime: DateTime
//   status: String
//   total_price: Float
//   currency_code: String
//   special_requests: String
// Relationships:
//   (:Passenger)-[:MADE_BOOKING]->(:Booking)
//   (:Booking)-[:FOR_TRIP]->(:ScheduledTrip)
// Example Cypher CREATE:
// MATCH (p:Passenger {passenger_id: 'pass_pqr'}), (sched:ScheduledTrip {schedule_id: 'sched_1122'})
// CREATE (p)-[:MADE_BOOKING]->(b:Booking {booking_id: 'book_zyx', ...})-[:FOR_TRIP]->(sched)
// Node Label: :Ticket
// Properties:
//   ticket_id: String (Constraint: UNIQUE)
//   seat_number: String
//   ticket_type: String
//   price: Float
//   is_checked_in: Boolean
//   qr_code_data: String
// Relationships:
//   (:Ticket)-[:PART_OF_BOOKING]->(:Booking)
//   (:Ticket)-[:ASSIGNED_TO_CAR]->(:TrainCar)
// Example Cypher CREATE:
// MATCH (b:Booking {booking_id: 'book_zyx'}), (c:TrainCar {car_id: 'car_abc'})
// CREATE (t:Ticket {ticket_id: 'tkt_1a2b', ...})-[:PART_OF_BOOKING]->(b), (t)-[:ASSIGNED_TO_CAR]->(c)
// Node Label: :Staff
// Properties:
//   staff_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   role: String
//   employee_number: String (Constraint: UNIQUE)
//   hire_date: Date
//   contact_email: String (Constraint: UNIQUE, if not null)
//   contact_phone: String
//   is_active: Boolean
// Relationship (Optional):
//   (:Staff)-[:BASED_AT]->(:Station)
// Example Cypher CREATE:
// CREATE (:Staff {staff_id: 'staff_mno', first_name: 'Bob', ...})
// OPTIONAL MATCH (s:Station {station_id: 'station_xyz'}) // If primary_station_id exists
// WITH s, staff_mno // Need to get the created staff node reference
// WHERE s IS NOT NULL
// CREATE (staff_mno)-[:BASED_AT]->(s)
// Node Label: :MaintenanceRecord
// Properties:
//   record_id: String (Constraint: UNIQUE)
//   asset_type: String // Store type here for easier querying if assets are different labels
//   maintenance_type: String
//   start_datetime: DateTime
//   end_datetime: DateTime
//   description: String
//   cost: Float
//   status: String
// Relationships:
//   (:MaintenanceRecord)-[:PERFORMED_ON]->(:Train or :TrainCar or :Platform) // Polymorphic or separate relationships
//   (:MaintenanceRecord)-[:PERFORMED_BY]->(:Staff)
// Example Cypher CREATE:
// MATCH (asset:Train {train_id: 'train_789'}), (st:Staff {staff_id: 'staff_xyz'})
// CREATE (mr:MaintenanceRecord {record_id: 'maint_rec_001', asset_type: 'Train', ...})
// CREATE (mr)-[:PERFORMED_ON]->(asset)
// CREATE (mr)-[:PERFORMED_BY]->(st)


[User] List each citizen's first and last name alongside the first and last name of another citizen born in the same year but with a different national ID number.

[Assistant]
SELECT c1.first_name  AS first_name_1,
       c1.last_name   AS last_name_1,
       c2.first_name  AS first_name_2,
       c2.last_name   AS last_name_2,
       EXTRACT(YEAR FROM c1.date_of_birth) AS birth_year
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON EXTRACT(YEAR FROM c1.date_of_birth) = EXTRACT(YEAR FROM c2.date_of_birth)
 AND c1.national_id_number <> c2.national_id_number
 AND c1.citizen_id < c2.citizen_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 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 )


[User] How many 'ApprovalForAll' events are recorded for each ERC1155 contract address in the `erc1155_approval_for_all` table?

[Assistant] SELECT contract_address, COUNT(*) AS approval_count FROM erc1155_approval_for_all GROUP BY contract_address;

[User] For these contracts, can you include the collection name from the `nft_collections` table and filter to only show collections on the 'Ethereum' blockchain that have more than 100 approval events?

[Assistant] SELECT a.contract_address, c.name, COUNT(a.contract_address) AS approval_count FROM erc1155_approval_for_all AS a JOIN nft_collections AS c ON a.contract_address = c.contract_address WHERE c.blockchain = 'Ethereum' GROUP BY a.contract_address, c.name HAVING COUNT(a.contract_address) > 100 ORDER BY approval_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 erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE erc20_balances_historical ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.integer )
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_collections (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    name varchar NOT NULL, -- name fields for the functionType  in contract
    symbol varchar NOT NULL, -- symbol fields for the functionType  in contract
    deploy_block_number bigint NOT NULL, -- deploy_block_number fields for the functionType  in contract
    deploy_block_time bigint NOT NULL, -- deploy_block_time fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    description varchar NOT NULL, -- description fields for the functionType  in contract
    slug varchar NOT NULL, -- slug fields for the functionType  in contract
    media_info varchar NOT NULL, -- media_info fields for the functionType  in contract
    image_url varchar NOT NULL, -- image_url fields for the functionType  in contract
    banner_image_url varchar NOT NULL, -- banner_image_url fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    banner varchar NOT NULL, -- banner fields for the functionType  in contract
    token_count bigint NOT NULL, -- token_count fields for the functionType  in contract
    floor_price varchar NOT NULL, -- floor_price fields for the functionType  in contract
    floor_price_symbol varchar NOT NULL, -- floor_price_symbol fields for the functionType  in contract
    floor_price_contract varchar NOT NULL, -- floor_price_contract fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(deploy_block_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, 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 varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info_avalanche (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(20) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL, -- Address originating the inscription (matches from_address in transactions table)
    minted decimal(38,0) NOT NULL, -- Sum of minted amount
    holders decimal(38,0) NOT NULL, -- Count of holders
    txs decimal(38,0) NOT NULL, -- Count of transactions
    updated_timestamp timestamp(3) NOT NULL, -- Timestamp of update
    completed_timestamp timestamp(3) NOT NULL, -- Timestamp of minted completed
    id varchar(255) NOT NULL  -- id fields for the functionType  in contract asc20
)


[User] List all clients along with their case_number and case_type for cases that are currently 'Open'.

[Assistant]
SELECT c.first_name, c.last_name, c.email, cs.case_number, cs.case_type
FROM legal_services.clients AS c
JOIN legal_services.cases AS cs
  ON c.client_id = cs.client_id
WHERE cs.status = 'Open';

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.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )
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) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.documents ( document_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, document_name character varying(255) NOT NULL, document_type character varying(100), storage_path text NOT NULL, uploaded_by_lawyer_id character varying(64), upload_timestamp timestamp NOT NULL, version integer DEFAULT 1, description text, PRIMARY KEY (document_id) )
CREATE TABLE legal_services.time_entries ( entry_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, date_worked date NOT NULL, hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), billing_rate numeric(10, 2) NOT NULL, description text NOT NULL, is_billable boolean DEFAULT true, is_billed boolean DEFAULT false, invoice_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (entry_id) )
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )


[User] List all patients who have insurance plans with group numbers, showing their patient IDs and the count of such plans per patient.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id;

[User] Actually, I only need patients who have more than 2 such plans.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;

[User] Can you also include the earliest effective date among these plans for each patient?

[Assistant] SELECT patient_id, COUNT(*) AS plan_count, MIN(effective_date) AS earliest_effective_date FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;

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.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] Show me the number of distinct room types offered by each property, including the property name and the count.

[Assistant] SELECT T1.property_name, COUNT(DISTINCT T2.room_type_id) FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id = T2.property_id GROUP BY T1.property_id;

[User] Now, only show properties that offer more than 5 distinct room types.

[Assistant] SELECT T1.property_name, COUNT(DISTINCT T2.room_type_id) FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id = T2.property_id GROUP BY T1.property_id HAVING COUNT(DISTINCT T2.room_type_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 hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
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 PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
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) )
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults int, num_children int, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


[User] For each vehicle, show the first and last fueling events including their timestamps and the quantities refueled.

[Assistant]
WITH first_last AS (
  SELECT
    vehicle_id,
    MIN(log_timestamp) AS first_time,
    MAX(log_timestamp) AS last_time
  FROM transportation.fuel_logs
  GROUP BY vehicle_id
)
SELECT
  f1.vehicle_id,
  f1.log_timestamp AS first_refuel_time,
  f1.quantity AS first_quantity,
  f2.log_timestamp AS last_refuel_time,
  f2.quantity AS last_quantity
FROM first_last fl
JOIN transportation.fuel_logs f1
  ON fl.vehicle_id = f1.vehicle_id
  AND fl.first_time = f1.log_timestamp
JOIN transportation.fuel_logs f2
  ON fl.vehicle_id = f2.vehicle_id
  AND fl.last_time = f2.log_timestamp;

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.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)


[User] Show me all rooms that were last cleaned more than 3 days ago, along with their room numbers and cleaning status.

[Assistant] SELECT room_number, current_condition FROM hospitality_technology.rooms WHERE last_cleaned_at < CURRENT_DATE - INTERVAL '3 days';

[User] Now, join this with another query to show only rooms that are currently 'Available' and have a 'Jacuzzi' in their features.

[Assistant] SELECT r.room_number, r.current_condition FROM hospitality_technology.rooms r WHERE r.last_cleaned_at < CURRENT_DATE - INTERVAL '3 days' AND r.status = 'available' AND r.features LIKE '%Jacuzzi%';

[User] The query is missing the floor information. Can you include that as well?

[Assistant] SELECT r.room_number, r.current_condition, r.floor FROM hospitality_technology.rooms r WHERE r.last_cleaned_at < CURRENT_DATE - INTERVAL '3 days' AND r.status = 'available' AND r.features LIKE '%Jacuzzi%';

[User] Actually, I need to see the results ordered by floor in descending order, then by room_number.

[Assistant] SELECT r.room_number, r.current_condition, r.floor FROM hospitality_technology.rooms r WHERE r.last_cleaned_at < CURRENT_DATE - INTERVAL '3 days' AND r.status = 'available' AND r.features LIKE '%Jacuzzi%' ORDER BY r.floor DESC, r.room_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 hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )


[User] Find all pairs of transactions that occurred in the same block and were sent to the same address. Show both transaction IDs, the shared recipient address, and the block number.

[Assistant]
SELECT t1.transaction_id AS tx1,
       t2.transaction_id AS tx2,
       t1.to_address,
       t1.block_number
FROM transactions t1
JOIN transactions t2
  ON t1.to_address = t2.to_address
 AND t1.block_number = t2.block_number
 AND t1.transaction_id < t2.transaction_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.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )


[User] What is the current salary of employee with ID 'EMP123'?

[Assistant] I'm sorry, but I can't provide information about an employee's salary as it is not included in the data available in the 'employees' table.

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.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(128) NOT NULL, -- e.g., 'Aircraft Mechanic', 'Quality Inspector', 'Assembly Technician'
    skill_certifications text, -- comma-separated list or JSON of certifications
    hire_date date NOT NULL,
    assigned_line_id character varying(64), -- FK to the assembly line the employee is currently assigned to (can be null)
    employment_status character varying(50) NOT NULL, -- e.g., 'Active', 'On Leave', 'Terminated'
    supervisor_employee_id character varying(64), -- FK to the employee's supervisor (self-reference, nullable)
    PRIMARY KEY (employee_id)
)


[User] Show me the total number of sessions and the total duration in seconds for each server, including the server name and the game title.

[Assistant]
SELECT
  s.server_name,
  g.game_title,
  COUNT(gs.session_id) AS total_sessions,
  SUM(gs.duration_seconds) AS total_duration_seconds
FROM gaming_technology.game_sessions AS gs
JOIN gaming_technology.servers AS s
  ON gs.server_id = s.server_id
JOIN gaming_technology.games AS g
  ON gs.game_id = g.game_id
GROUP BY
  s.server_id,
  s.server_name,
  g.game_title;

[User] Actually, I got an error that the table 'games' does not exist. Can you provide the same information but without using the 'games' table? Just show the server name and its game_id.

[Assistant]
SELECT
  s.server_name,
  s.game_id,
  COUNT(gs.session_id) AS total_sessions,
  SUM(gs.duration_seconds) AS total_duration_seconds
FROM gaming_technology.game_sessions AS gs
JOIN gaming_technology.servers AS s
  ON gs.server_id = s.server_id
GROUP BY
  s.server_id,
  s.server_name,
  s.game_id;

[User] Only include servers where the total session duration is greater than 1 day (86400 seconds).

[Assistant]
SELECT
  s.server_name,
  s.game_id,
  COUNT(gs.session_id) AS total_sessions,
  SUM(gs.duration_seconds) AS total_duration_seconds
FROM gaming_technology.game_sessions AS gs
JOIN gaming_technology.servers AS s
  ON gs.server_id = s.server_id
GROUP BY
  s.server_id,
  s.server_name,
  s.game_id
HAVING
  SUM(gs.duration_seconds) > 86400;

[User] Order the results by total session duration in descending order.

[Assistant]
SELECT
  s.server_name,
  s.game_id,
  COUNT(gs.session_id) AS total_sessions,
  SUM(gs.duration_seconds) AS total_duration_seconds
FROM gaming_technology.game_sessions AS gs
JOIN gaming_technology.servers AS s
  ON gs.server_id = s.server_id
GROUP BY
  s.server_id,
  s.server_name,
  s.game_id
HAVING
  SUM(gs.duration_seconds) > 86400
ORDER BY
  total_duration_seconds 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.game_sessions ( session_id.uuid, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, session_data.jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )


[User] Show me all cryptocurrency assets that have been traded more than 50 times but have never been traded in quantities greater than 100, along with their average trade price.

[Assistant] SELECT a.asset_id, a.name, a.symbol, COUNT(t.trade_id) AS trade_count, AVG(t.price) AS avg_price FROM trading_platform.assets a JOIN trading_platform.trades t ON a.asset_id = t.asset_id WHERE a.type = 'cryptocurrency' GROUP BY a.asset_id, a.name, a.symbol HAVING COUNT(t.trade_id) > 50 AND MAX(t.quantity) <= 100;

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.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
CREATE TABLE trading_platform.utxos ( utxo_id character varying(64) NOT NULL, transaction_id character varying(64) NOT NULL, output_index integer NOT NULL, address character varying(128) NOT NULL, amount numeric(38,14) NOT NULL, spent boolean NOT NULL, PRIMARY KEY (utxo_id) )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_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.kyc_audit ( kyc_audit_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, status character varying(32) NOT NULL, reviewed_at timestamp NOT NULL, PRIMARY KEY (kyc_audit_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] For each agency, list the agency name and the count of distinct service categories they offer.

[Assistant]
SELECT ag.agency_name, COUNT(DISTINCT s.category) AS category_count
FROM government_services.agencies ag
JOIN government_services.services s ON ag.agency_id = s.agency_id
GROUP BY ag.agency_name;

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.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.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 )
CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )
CREATE TABLE government_services.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )


[User] List all users with private profiles who have disabled push notifications, including their user_id and email_notifications_enabled status.

[Assistant]
SELECT user_id,
       email_notifications_enabled
FROM social_media.user_settings
WHERE private_profile = true
  AND push_notifications_enabled = false;

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.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )


[User] Calculate the average number of days between when an incident occurred and when the claim was reported, but only for claims that were settled in the year 2023.

[Assistant]
SELECT
  AVG(EXTRACT(EPOCH FROM (reported_date - incident_date)) / 86400.0)::numeric(10, 2)
FROM
  insurance.claims
WHERE
  settlement_date IS NOT NULL AND EXTRACT(YEAR FROM settlement_date) = 2023;

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


[User] Please show me all locations that do not have a state or province recorded. Include the location name, city, and country.

[Assistant]
SELECT name, city, country
FROM transportation.locations
WHERE state_province IS NULL OR state_province = '';

[User] For these locations, also include their location_id and type.

[Assistant]
SELECT location_id, name, type, city, country
FROM transportation.locations
WHERE state_province IS NULL OR state_province = '';

[User] Could you additionally list any routes for which these locations are either the origin or the destination? Show the location name, route number, and specify if the location is origin or destination.

[Assistant]
SELECT l.name, r.route_number,
  CASE
    WHEN r.origin_location_id = l.location_id THEN 'origin'
    WHEN r.destination_location_id = l.location_id THEN 'destination'
  END AS role
FROM transportation.locations l
JOIN transportation.routes r
  ON r.origin_location_id = l.location_id OR r.destination_location_id = l.location_id
WHERE l.state_province IS NULL OR l.state_province = '';

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 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.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
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 )


[User] Show me the invoice number and total amount for each invoice, along with the number and name of the case it belongs to.

[Assistant] SELECT T1.invoice_number, T1.total_amount, T2.case_number, T2.case_name FROM invoices AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id;

[User] Refine this to only include invoices with a status of 'Overdue' or 'Unpaid'.

[Assistant] SELECT T1.invoice_number, T1.total_amount, T2.case_number, T2.case_name FROM invoices AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T1.status = 'Overdue' OR T1.status = 'Unpaid';

[User] Also include the invoice due date and order the results by due date ascending.

[Assistant] SELECT T1.invoice_number, T1.total_amount, T1.due_date, T2.case_number, T2.case_name FROM invoices AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T1.status = 'Overdue' OR T1.status = 'Unpaid' ORDER BY T1.due_date 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 legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
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 )


[User] Retrieve the username and email for every user, along with the wallet ID and associated address ID for any wallets they own.

[Assistant]
SELECT
    u.username,
    u.email,
    w.wallet_id,
    w.address_id
FROM
    blockchain.users AS u
LEFT JOIN
    blockchain.wallets AS w ON u.user_id = w.user_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 blockchain.blocks ( block_id.text, previous_block_id.text, timestamp.timestamp, nonce.integer, merkle_root.text, difficulty.integer )
CREATE TABLE blockchain.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    block_id character varying(64) NOT NULL, -- identifier of the block containing the transaction
    sender_address character varying(128) NOT NULL, -- address of the sender
    receiver_address character varying(128) NOT NULL, -- address of the receiver
    amount numeric(38,14) NOT NULL, -- amount transferred
    timestamp timestamp NOT NULL, -- time when the transaction was created
    signature text NOT NULL, -- digital signature of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE blockchain.addresses ( address_id character varying(128) NOT NULL, public_key text NOT NULL, balance numeric(38,14) NOT NULL, PRIMARY KEY (address_id) )
CREATE TABLE blockchain.wallets ( wallet_id.text, user_id.text, address_id.text, private_key.text )
CREATE TABLE blockchain.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, PRIMARY KEY (user_id) )
CREATE TABLE blockchain.smart_contracts ( contract_id character varying(64) NOT NULL, creator_address character varying(128) NOT NULL, code text NOT NULL, timestamp timestamp NOT NULL, PRIMARY KEY (contract_id) )


[User] List all claim documents that are police reports and were uploaded in the last 30 days, along with their file sizes.

[Assistant] SELECT cd.document_id, cd.claim_id, cd.file_size_bytes FROM insurance.claim_documents cd WHERE cd.document_type = 'Police Report' AND cd.uploaded_at >= CURRENT_DATE - INTERVAL '30 days';

[User] Now include only documents that are larger than 1MB and sort them by file size in descending order.

[Assistant] SELECT cd.document_id, cd.claim_id, cd.file_size_bytes FROM insurance.claim_documents cd WHERE cd.document_type = 'Police Report' AND cd.uploaded_at >= CURRENT_DATE - INTERVAL '30 days' AND cd.file_size_bytes > 1000000 ORDER BY cd.file_size_bytes 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.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), 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) )
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', 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) )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )


[User] List the full names and dates of birth for all patients who do not have a phone number on record.

[Assistant] SELECT first_name, last_name, date_of_birth FROM healthcare.patients WHERE phone_number IS NULL OR TRIM(phone_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 healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.diagnoses (
    diagnosis_id 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)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )


[User] Show me the top 5 users who have created the most wallets, along with their email addresses and the creation date of their first wallet.

[Assistant] SELECT u.user_id, u.email, MIN(w.created_at) AS first_wallet_date, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.user_id, u.email ORDER BY wallet_count DESC LIMIT 5;

[User] Now modify the query to only include wallets created in the last 6 months.

[Assistant] SELECT u.user_id, u.email, MIN(w.created_at) AS first_wallet_date, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id WHERE w.created_at >= NOW() - INTERVAL '6 months' GROUP BY u.user_id, u.email ORDER BY wallet_count DESC LIMIT 5;

[User] Actually, I want to see the total balance across all wallets for each of these users, calculated from unspent UTXOs.

[Assistant] SELECT u.user_id, u.email, MIN(w.created_at) AS first_wallet_date, COUNT(w.wallet_id) AS wallet_count, COALESCE(SUM(ut.amount), 0) AS total_balance FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id LEFT JOIN trading_platform.utxos ut ON w.address = ut.address AND ut.spent = false WHERE w.created_at >= NOW() - INTERVAL '6 months' GROUP BY u.user_id, u.email ORDER BY wallet_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 trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
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.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- 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)
)


[User] What is the average speed of train number T9876 during its last journey?

[Assistant] I'm sorry, but I can't provide information on the average speed of train number T9876 during its last journey. The data in the trains table does not include details about travel speed or journey-specific performance metrics.

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, train_number.text, model.text, manufacturer.text, year_manufactured.integer, capacity.integer, status.text, last_maintenance_date.date, next_maintenance_date.date )