[User] I want to find the top 5 wallets by USD value of their ERC20 holdings. Show wallet_address, token symbol, and USD value based on the latest price.

[Assistant]
SELECT b.wallet_address, p.symbol, SUM(CAST(b.amount AS numeric) * p.price) AS usd_value
FROM erc20_balances b
JOIN token_prices_latest p ON b.contract_address = p.address
GROUP BY b.wallet_address, p.symbol
ORDER BY usd_value DESC
LIMIT 5;

[User] Include the decimals from the price table in the output.

[Assistant]
SELECT b.wallet_address, p.symbol, p.decimals,
       SUM(CAST(b.amount AS numeric) * p.price) AS usd_value
FROM erc20_balances b
JOIN token_prices_latest p ON b.contract_address = p.address
GROUP BY b.wallet_address, p.symbol, p.decimals
ORDER BY usd_value DESC
LIMIT 5;

[User] Only consider wallets where the USD value is greater than 1000 and limit to top 3 entries.

[Assistant]
SELECT b.wallet_address, p.symbol, p.decimals,
       SUM(CAST(b.amount AS numeric) * p.price) AS usd_value
FROM erc20_balances b
JOIN token_prices_latest p ON b.contract_address = p.address
GROUP BY b.wallet_address, p.symbol, p.decimals
HAVING SUM(CAST(b.amount AS numeric) * p.price) > 1000
ORDER BY usd_value DESC
LIMIT 3;

[User] Group the total USD value per wallet across all tokens instead of per token, then list top 3 wallets.

[Assistant]
SELECT b.wallet_address,
       SUM(CAST(b.amount AS numeric) * p.price) AS total_usd_value
FROM erc20_balances b
JOIN token_prices_latest p ON b.contract_address = p.address
GROUP BY b.wallet_address
HAVING SUM(CAST(b.amount AS numeric) * p.price) > 1000
ORDER BY total_usd_value DESC
LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_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_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


[User] Show me the user who received the most notifications in the last 30 days, along with the count of notifications they received.

[Assistant] SELECT user_id, COUNT(*) AS notification_count FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '30 days' GROUP BY user_id ORDER BY notification_count DESC LIMIT 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] Retrieve each agent's ID, full name, and the count of 'Pending' policies they have sold with a premium_amount greater than 2000. Order the results by the policy count descending.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       COUNT(p.policy_id) AS pending_policy_count
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE p.status = 'Pending'
  AND p.premium_amount > 2000
GROUP BY a.agent_id, agent_name
ORDER BY pending_policy_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[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] Show me all users whose email address contains the word 'test', along with their user IDs and the date they registered.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE email ILIKE '%test%';

[User] Actually, only include users who registered after January 1, 2024, and sort them by newest registration date first.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE email ILIKE '%test%' AND created_at > '2024-01-01' ORDER BY created_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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)
)


[User] List all agents who have a commission rate above 0.1, showing their full names and agency names.

[Assistant] SELECT agent_id, first_name, last_name, agency_name, commission_rate FROM insurance.agents WHERE commission_rate > 0.1 AND status = 'Active';

[User] Now include only agents who were hired in the last 2 years.

[Assistant] SELECT agent_id, first_name, last_name, agency_name, commission_rate, hire_date FROM insurance.agents WHERE commission_rate > 0.1 AND status = 'Active' AND hire_date >= CURRENT_DATE - INTERVAL '2 years';

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, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.agents (
    agent_id character varying(64) NOT NULL, -- unique identifier for the agent
    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, -- state insurance license number
    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', -- e.g., Active, Terminated, On Leave
    commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, -- percentage commission
    manager_id character varying(64), -- identifier for the agent's manager (FK to agents or employees)
    PRIMARY KEY (agent_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.claim_documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document
    claim_id character varying(64) NOT NULL, -- identifier of the claim this document relates to (FK to claims)
    document_type character varying(50) NOT NULL, -- e.g., Police Report, Photo, Invoice, Medical Bill
    file_name character varying(255) NOT NULL, -- original name of the uploaded file
    file_path character varying(512) NOT NULL, -- storage path (e.g., S3 URL, network path)
    file_size_bytes integer, -- size of the file in bytes
    mime_type character varying(100), -- MIME type of the file (e.g., 'image/jpeg', 'application/pdf')
    uploaded_by character varying(64), -- identifier of the user/system who uploaded (FK to users/customers)
    uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- time of upload
    description text, -- optional description of the document
    PRIMARY KEY (document_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] Retrieve the distinct generic_name values and the number of medications for each generic_name, sorted by the count descending.

[Assistant]
SELECT generic_name,
       COUNT(*) AS medication_count
FROM healthcare.medications
GROUP BY generic_name
ORDER BY medication_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )


[User] Show me all intercity routes with their origin and destination locations, including the city and country for each location.

[Assistant] SELECT r.route_id, r.route_number, r.type, orig.name AS origin_name, orig.city AS origin_city, orig.country AS origin_country, dest.name AS destination_name, dest.city AS destination_city, dest.country AS destination_country FROM transportation.routes r JOIN transportation.locations orig ON r.origin_location_id = orig.location_id JOIN transportation.locations dest ON r.destination_location_id = dest.location_id WHERE r.type = 'Intercity Train';

[User] Now filter these results to only show routes where both origin and destination are in the same country, and include the distance in kilometers.

[Assistant] SELECT r.route_id, r.route_number, r.distance_km, orig.city AS origin_city, dest.city AS destination_city, orig.country FROM transportation.routes r JOIN transportation.locations orig ON r.origin_location_id = orig.location_id JOIN transportation.locations dest ON r.destination_location_id = dest.location_id WHERE r.type = 'Intercity Train' AND orig.country = dest.country;

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 character varying(64) NOT NULL,  -- unique identifier for the route
    route_number character varying(32) NOT NULL UNIQUE, -- public-facing route number/name
    description text, -- description of the route
    origin_location_id character varying(64) NOT NULL, -- identifier of the starting location
    destination_location_id character varying(64) NOT NULL, -- identifier of the ending location
    distance_km numeric(10, 2), -- estimated distance in kilometers
    estimated_duration_minutes integer, -- estimated travel time in minutes
    type character varying(32) NOT NULL, -- e.g., City Bus, Intercity Train, Cargo Delivery
    PRIMARY KEY (route_id)
)
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )
CREATE TABLE transportation.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )


[User] Show me the top 5 projects by valuation that completed fundraising rounds in the last 12 months, along with their token symbol and price from the token_basic_info table.

[Assistant] SELECT pfr.project_name, pfr.valuation, tbi.token_symbol, tbi.price FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) ORDER BY pfr.valuation DESC LIMIT 5;

[User] Can you also include the 24-hour trading volume for these projects' tokens and filter to only include projects with valuation over $100 million?

[Assistant] SELECT pfr.project_name, pfr.valuation, tbi.token_symbol, tbi.price, tbi.total_volume FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) AND pfr.valuation > 100000000 ORDER BY pfr.valuation DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
 "CREATE TABLE project_fundraising_record (",
    "id character varying(32) NOT NULL,  -- fundraising record id",
    "project_id character varying(32) NOT NULL, -- the invested project's id",
    "project_name character varying(128) NOT NULL, -- name of the invested project",
    "rounds_name character varying(32), -- name of the fundraising round",
    "investment_value numeric(38,14), -- amount of the fundraising in USD",
    "investment_date character varying(128), -- the date of the investment happened",
    "introduction character varying(128), -- the introduction of the invested project",
    "valuation numeric(38,14), -- the valuation of the project in USD when invested",

CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_6h double precision, price_change_percentage_24h double precision, makers_24h double precision, volume_24h double precision, liquidity double precision, market_cap double precision, trend_rank bigint )
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )
  "CREATE TABLE smart_money_token_performance (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "pnl numeric(38,2), -- the profit users made on this token",
    "net_flow numeric(38,2), -- the netflow of the token, means the money user spent minus the the money user sold of this token",
    "avg_cost numeric(38,16), -- the average cost price of user spent on this token",
    "price double precision, -- the current price of the token",
    "realized_ratio numeric(10,2), -- the ratio user sold of the token",
    "roi numeric(10,2), -- the roi users made of this token",
    "chain character varying(100), -- the chain that the token resides",
    "PRIMARY KEY (token_address, chain));",

  "CREATE TABLE smart_money_token_inflow (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token",
    "usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token",
    "avg_price numeric(38,6), -- the average cost price of user spent on this token",
    "type int, -- the direction of the trade on this token. 1 means buying, 2 means selling",
    "address_amount integer, -- the amount of the user bought this token",
    "narrative character varying(100), -- the category or narrative of the token",
    "chain character varying(100), -- the chain that the token resides",
    ",PRIMARY KEY (token_address, chain)",


[User] List the first name, last name, and firm name for all lawyers who are partners.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T2.firm_name FROM legal_services.lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id  =  T2.firm_id WHERE T1.is_partner  =  TRUE

[User] Only show partners from law firms founded before 2010.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T2.firm_name FROM legal_services.lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id  =  T2.firm_id WHERE T1.is_partner  =  TRUE AND T2.founded_date < '2010-01-01'

[User] Sort the results by firm name and then by the lawyer's last name.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T2.firm_name FROM legal_services.lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id  =  T2.firm_id WHERE T1.is_partner  =  TRUE AND T2.founded_date < '2010-01-01' ORDER BY T2.firm_name ,  T1.last_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 legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)


[User] Show the full name of each manager and the average commission rate of the agents who report directly to them. Only include managers who have at least one reporting agent.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, AVG(T1.commission_rate) AS average_agent_commission_rate FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id GROUP BY T2.agent_id, T2.first_name, T2.last_name

[User] Filter the results to only show managers whose average agent commission rate is above 0.12.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, AVG(T1.commission_rate) AS average_agent_commission_rate FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id GROUP BY T2.agent_id, T2.first_name, T2.last_name HAVING AVG(T1.commission_rate) > 0.12

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.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )


[User] Show the full names and contact emails of all citizens who have made a payment for an application that is currently in 'Pending' status.

[Assistant]
SELECT DISTINCT c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.applications a ON p.application_id = a.application_id
WHERE a.status = 'Pending';

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 PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, 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.service_locations ( location_id text PRIMARY KEY, 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 PRIMARY KEY, 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 PRIMARY KEY, 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] For each service location, find its nearest accessible location by geographic distance.

[Assistant]
SELECT sl.location_id,
       sl.location_name,
       nearest.location_id   AS nearest_location_id,
       nearest.location_name AS nearest_location_name
FROM government_services.service_locations sl
JOIN LATERAL (
  SELECT sl2.location_id,
         sl2.location_name
  FROM government_services.service_locations sl2
  WHERE sl2.is_accessible = TRUE
    AND sl2.location_id <> sl.location_id
  ORDER BY ((sl.latitude - sl2.latitude)^2 + (sl.longitude - sl2.longitude)^2) ASC
  LIMIT 1
) AS nearest ON TRUE;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )


[User] Show me the top 5 users who have interacted with DApps, along with the count of distinct DApps they interacted with and their wallet addresses.

[Assistant] SELECT w.user_id, COUNT(DISTINCT d.dapp_id) AS dapp_count, w.address FROM trading_platform.wallets w JOIN trading_platform.dapps d ON 1=1 GROUP BY w.user_id, w.address ORDER BY dapp_count DESC LIMIT 5;

[User] This query doesn't properly show DApp interactions. Please modify it to correctly join with a table that records user-DApp interactions.

[Assistant] I notice there's no interaction table in the provided schema. Without a table recording user-DApp interactions, I cannot generate this query accurately. Would you like to see users who have wallets and DApps separately instead?

[User] You're right. Instead, show me users who have wallets but have never interacted with any DApps, along with their wallet addresses.

[Assistant] SELECT w.user_id, w.address FROM trading_platform.wallets w WHERE NOT EXISTS (SELECT 1 FROM trading_platform.dapps d WHERE 1=1) GROUP BY w.user_id, w.address;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
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.text, name.text, symbol.text, type.text )
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.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) )


[User] Find employees who work in the same department as their manager. Display the employee's full name, the manager's full name, and the department they share.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_full_name, m.first_name || ' ' || m.last_name AS manager_full_name, e.department FROM government_services.employees AS e JOIN government_services.employees AS m ON e.manager_employee_id = m.employee_id WHERE e.department = m.department;

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.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)


[User] Provide the route_number, description, origin location name, and destination location name for all routes of type 'Express'.

[Assistant]
SELECT r.route_number,
       r.description,
       o.name AS origin_name,
       d.name AS destination_name
FROM transportation.routes AS r
JOIN transportation.locations AS o ON r.origin_location_id = o.location_id
JOIN transportation.locations AS d ON r.destination_location_id = d.location_id
WHERE r.type = 'Express';

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.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.locations (
    location_id character varying(64) NOT NULL,  -- unique identifier for the location
    name character varying(255) NOT NULL, -- name of the location (e.g., Central Station, Depot Alpha, Pier 7)
    type character varying(64) NOT NULL, -- e.g., Station, Stop, Depot, Port, Airport, Customer Address
    address_line1 character varying(255), -- street address
    city character varying(128), -- city name
    state_province character varying(128), -- state or province
    postal_code character varying(32), -- postal code
    country character varying(64) NOT NULL, -- country name
    latitude numeric(9, 6), -- geographic latitude
    longitude numeric(9, 6), -- geographic longitude
    timezone character varying(64), -- IANA timezone name (e.g., America/New_York)
    PRIMARY KEY (location_id)
)
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.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] List application IDs that have both documents and payments associated with them.

[Assistant] SELECT DISTINCT T1.application_id FROM documents AS T1 JOIN payments AS T2 ON T1.application_id = T2.application_id

[User] For those applications, also show the total payment amount.

[Assistant] SELECT T1.application_id, SUM(T2.amount) FROM documents AS T1 JOIN payments AS T2 ON T1.application_id = T2.application_id GROUP BY T1.application_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.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )


[User] Show me all customers who have missing contact information (either phone number or email is null), along with their state and city.

[Assistant] SELECT first_name, last_name, state, city FROM insurance.customers WHERE phone_number IS NULL OR email IS NULL;

[User] Now filter these to only show customers from Florida or New York who were created in the last year.

[Assistant] SELECT first_name, last_name, state, city FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '1 year';

[User] I also want to see when these customers were last updated (updated_at field).

[Assistant] SELECT first_name, last_name, state, city, updated_at FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '1 year';

[User] Finally, order the results by state first, then by the most recently updated customers first.

[Assistant] SELECT first_name, last_name, state, city, updated_at FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '1 year' ORDER BY state, updated_at DESC;

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 character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)


[User] Who are the top three users by total uploaded file size? Return uploaded_by and their cumulative file_size_bytes.

[Assistant]
SELECT uploaded_by,
       SUM(file_size_bytes) AS total_size
FROM insurance.claim_documents
WHERE file_size_bytes IS NOT NULL
GROUP BY uploaded_by
ORDER BY total_size DESC
LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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 all ERC20 token transfers where the amount is over 5000, including the sender and receiver addresses.

[Assistant] SELECT from_address, to_address, amt, tick, tx_hash FROM token_activities WHERE type = 'transfer' AND CAST(amt AS DECIMAL) > 5000;

[User] Add the token symbol and decimals for each transfer by joining to the latest token price table.

[Assistant] SELECT ta.from_address, ta.to_address, ta.amt, ta.tick, ta.tx_hash, tpl.symbol, tpl.decimals FROM token_activities ta JOIN token_prices_latest tpl ON ta.tick = tpl.symbol WHERE ta.type = 'transfer' AND CAST(ta.amt AS DECIMAL) > 5000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk integer )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk integer )
CREATE TABLE sui_coins ( object_id varchar, status varchar, coin_type varchar, balance varchar, owner varchar )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain varchar, contract_address varchar, name varchar, symbol varchar, deploy_block_number bigint, deploy_block_time bigint, erc_type varchar, owner varchar, traits varchar, description varchar, slug varchar, media_info varchar, image_url varchar, banner_image_url varchar, updated_at bigint, banner varchar, token_count bigint, floor_price varchar, floor_price_symbol varchar, floor_price_contract varchar, pk integer )
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )


[User] Can you list all the room types and their base rates along with the maximum occupancy for each property?

[Assistant] SELECT property_id, type_name, base_rate, max_occupancy FROM hospitality_technology.room_types;

[User] Show only those room types that can accommodate more than 4 people and have a base rate above 200. Order the results by base rate.

[Assistant] SELECT property_id, type_name, base_rate, max_occupancy FROM hospitality_technology.room_types WHERE max_occupancy > 4 AND base_rate > 200 ORDER BY base_rate;

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


[User] Show the number of active agents in each license state.

[Assistant]
SELECT license_state,
       COUNT(*) AS active_agent_count
FROM insurance.agents
WHERE status = 'active'
GROUP BY license_state;

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.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )


[User] Show me wallet addresses that hold more than 1000 of any ERC20 token, along with the token symbol and amount, sorted by amount in descending order.

[Assistant] SELECT b.wallet_address, t.symbol, b.amount FROM erc20_balances b JOIN sui_coins_metadata t ON b.contract_address = t.coin_type WHERE CAST(b.amount AS decimal) > 1000 ORDER BY CAST(b.amount AS decimal) DESC;

[User] Can you also include the current price of each token from the token_prices_latest table?

[Assistant] SELECT b.wallet_address, t.symbol, b.amount, p.price FROM erc20_balances b JOIN sui_coins_metadata t ON b.contract_address = t.coin_type JOIN token_prices_latest p ON b.contract_address = p.address WHERE CAST(b.amount AS decimal) > 1000 ORDER BY CAST(b.amount AS decimal) 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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE nft_metadata (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    token_id varchar NOT NULL, -- The number of the token
    contract_name varchar NOT NULL, -- contract_name fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    amount bigint NOT NULL, -- amount fields for the functionType  in contract
    minter varchar NOT NULL, -- minter fields for the functionType  in contract
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    mint_block_number bigint NOT NULL, -- mint_block_number fields for the functionType  in contract
    mint_time bigint NOT NULL, -- mint_time fields for the functionType  in contract
    mint_transaction_hash varchar NOT NULL, -- mint_transaction_hash fields for the functionType  in contract
    mint_price varchar NOT NULL, -- mint_price fields for the functionType  in contract
    token_uri varchar NOT NULL, -- token_uri fields for the functionType  in contract
    metadata varchar NOT NULL, -- metadata fields for the functionType  in contract
    name varchar NOT NULL, -- name fields for the functionType  in contract
    image_uri varchar NOT NULL, -- image_uri fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    status varchar NOT NULL, -- status fields for the functionType  in contract
    rarity_score real NOT NULL, -- rarity_score fields for the functionType  in contract
    rarity_rank integer NOT NULL, -- rarity_rank fields for the functionType  in contract
    unique_attribute_count integer NOT NULL, -- unique_attribute_count fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(mint_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
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 mud_holesky_redstone (
    address varchar NOT NULL, -- address fields for the functionType  in contract
    table_id varchar NOT NULL, -- table_id fields for the functionType  in contract
    key_bytes varchar NOT NULL, -- key_bytes fields for the functionType  in contract
    key0 varchar NOT NULL, -- key0 fields for the functionType  in contract
    key1 varchar NOT NULL, -- key1 fields for the functionType  in contract
    static_data varchar NOT NULL, -- static_data fields for the functionType  in contract
    encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType  in contract
    dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType  in contract
    is_deleted boolean NOT NULL, -- is_deleted fields for the functionType  in contract
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    log_index bigint NOT NULL  -- Index of the log within the transaction
)
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_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, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] Show me all insurance plans that cover more than 10 patients as their primary insurance, along with the provider name and contact information.

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- 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.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions (
    prescription_id character varying(64) NOT NULL, -- unique identifier for the prescription
    record_id character varying(64) NOT NULL, -- FK linking to the medical record where it was prescribed
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to prescribing doctor
    medication_id character varying(64) NOT NULL, -- FK to medications table
    dosage character varying(100) NOT NULL, -- e.g., '100mg', '1 tablet'
    frequency character varying(100) NOT NULL, -- e.g., 'Once daily', 'Twice a day with meals'
    route character varying(50), -- e.g., 'Oral', 'Topical', 'Intravenous'
    start_date date NOT NULL, -- date prescription begins
    end_date date, -- date prescription ends (if applicable)
    quantity_dispensed numeric(10,2), -- amount dispensed (e.g., number of tablets)
    refills_allowed integer NOT NULL DEFAULT 0, -- number of allowed refills
    prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (prescription_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] Find all nodes that were last seen in the last 7 days, along with their IP addresses and ports.

[Assistant] SELECT node_id, ip_address, port FROM blockchain.nodes WHERE last_seen >= NOW() - INTERVAL '7 days';

[User] Now filter these results to only show nodes with port numbers between 8000 and 9000.

[Assistant] SELECT node_id, ip_address, port FROM blockchain.nodes WHERE last_seen >= NOW() - INTERVAL '7 days' AND port BETWEEN 8000 AND 9000;

[User] How many unique IP addresses are there among these active nodes?

[Assistant] SELECT COUNT(DISTINCT ip_address) FROM blockchain.nodes WHERE last_seen >= NOW() - INTERVAL '7 days' AND port BETWEEN 8000 AND 9000;

[User] Can you show me the count of nodes for each unique IP address?

[Assistant] SELECT ip_address, COUNT(node_id) AS node_count FROM blockchain.nodes WHERE last_seen >= NOW() - INTERVAL '7 days' AND port BETWEEN 8000 AND 9000 GROUP BY ip_address;

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 text PRIMARY KEY, public_key text, balance numeric )
CREATE TABLE blockchain.nodes (
    node_id character varying(64) NOT NULL,  -- unique identifier for the node
    ip_address character varying(15) NOT NULL, -- IP address of the node
    port integer NOT NULL, -- port number of the node
    last_seen timestamp NOT NULL, -- last time the node was active
    PRIMARY KEY (node_id)
)
CREATE TABLE blockchain.smart_contracts ( contract_id text PRIMARY KEY, creator_address text, code text, timestamp timestamp )


[User] List all wallets that were created during the hour of the day which saw the highest number of wallet creations. Show the wallet ID, user ID, address, and creation timestamp.

[Assistant]
WITH HourlyCounts AS (
    SELECT EXTRACT(HOUR FROM created_at) AS hour, COUNT(*) AS wallet_count
    FROM web3.wallets
    GROUP BY 1
),
MaxHour AS (
    SELECT hour
    FROM HourlyCounts
    ORDER BY wallet_count DESC
    LIMIT 1
)
SELECT wallet_id, user_id, address, created_at
FROM web3.wallets
WHERE EXTRACT(HOUR FROM created_at) = (SELECT hour FROM MaxHour);

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 PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )


[User] Show me all home loans (loan_id, principal_amount, interest_rate) where the current principal balance is more than 75% of the original principal amount, along with the account_id and employee details (first_name, last_name) of the employee who processed the loan application.

[Assistant] SELECT l.loan_id, l.principal_amount, l.interest_rate, l.account_id, e.first_name, e.last_name FROM financial_services.loans l JOIN financial_services.employees e ON l.account_id = e.employee_id WHERE l.loan_type = 'Home' AND l.current_principal_balance > (l.principal_amount * 0.75)

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.transactions ( transaction_id.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees ( employee_id.text, first_name.text, last_name.text, job_title.text, department.text, branch_id.text, email.text, phone_extension.text, hire_date.date, termination_date.date, manager_id.text, status.text )
CREATE TABLE financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )


[User] Retrieve each agency’s name along with the count of accessible service locations it has in California.

[Assistant]
SELECT
  a.agency_name,
  COUNT(l.location_id) AS accessible_location_count
FROM government_services.agencies a
JOIN government_services.service_locations l
  ON a.agency_id = l.agency_id
WHERE l.is_accessible = TRUE
  AND l.state = 'California'
GROUP BY a.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.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, 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 PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, 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 PRIMARY KEY, 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 PRIMARY KEY, 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 PRIMARY KEY, 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] Show the symbol, name, and total supply for all SUI coins with status 'active'.

[Assistant]
SELECT scm.symbol, scm.name, scm.coin_type, scm.total_supply
FROM sui_coins_metadata scm
WHERE scm.status = 'active';

[User] I received an error that column 'total_supply' doesn't exist in sui_coins_metadata.

[Assistant]
SELECT scm.symbol, scm.name, scm.coin_type
FROM sui_coins_metadata scm
WHERE scm.status = 'active';

[User] Now, join with sui_coins to add up the total balance across all owners for each coin_type.

[Assistant]
SELECT scm.symbol, scm.name, scm.coin_type, SUM(CAST(sc.balance AS NUMERIC)) AS total_balance
FROM sui_coins_metadata scm
JOIN sui_coins sc ON scm.coin_type = sc.coin_type
WHERE scm.status = 'active'
GROUP BY scm.symbol, scm.name, scm.coin_type;

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 erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )


[User] Find all pairs of different insurance records that share the same group_number, and show group_number, the patient_insurance_id of both records, and their corresponding patient_ids.

[Assistant]
SELECT a.group_number,
       a.patient_insurance_id AS pi_id1,
       a.patient_id            AS patient1_id,
       b.patient_insurance_id AS pi_id2,
       b.patient_id            AS patient2_id
FROM healthcare.patient_insurance a
JOIN healthcare.patient_insurance b
  ON a.group_number = b.group_number
 AND a.patient_insurance_id < b.patient_insurance_id
WHERE a.group_number IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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] List all fuel refueling events with the refueled vehicle's make and model, the fuel type used, and the fueling location ID.

[Assistant]
SELECT fl.fuel_log_id, fl.log_timestamp, v.make, v.model, fl.fuel_type, fl.quantity, fl.unit, fl.total_cost, fl.location_id
FROM transportation.fuel_logs fl
JOIN transportation.vehicles v ON fl.vehicle_id = v.vehicle_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)
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)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )


[User] List all medical records created in the last 7 days, including patient_id, doctor_id, and record_date.

[Assistant] SELECT patient_id, doctor_id, record_date FROM healthcare.medical_records WHERE created_at >= CURRENT_DATE - INTERVAL '7 days';

[User] Actually, I only need records where the treatment_plan is not empty.

[Assistant] SELECT patient_id, doctor_id, record_date FROM healthcare.medical_records WHERE created_at >= CURRENT_DATE - INTERVAL '7 days' AND treatment_plan IS NOT NULL AND treatment_plan != '';

[User] Can you also sort them by record_date in descending order?

[Assistant] SELECT patient_id, doctor_id, record_date FROM healthcare.medical_records WHERE created_at >= CURRENT_DATE - INTERVAL '7 days' AND treatment_plan IS NOT NULL AND treatment_plan != '' ORDER BY record_date DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.medical_records ( record_id.text, patient_id.text, appointment_id.text, doctor_id.text, record_date.timestamp, chief_complaint.text, present_illness_history.text, past_medical_history.text, physical_examination_notes.text, assessment.text, treatment_plan.text, vitals.json, created_at.timestamp )


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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )


[User] Show all ERC20 token approvals that happened between block numbers 18000000 and 18500000, including the contract address and number of approvals per contract.

[Assistant] SELECT contract_address, COUNT(*) AS approval_count FROM erc20_approval WHERE block_number BETWEEN 18000000 AND 18500000 GROUP BY contract_address;

[User] Include the symbol and name for each ERC20 token by joining with token_metas.

[Assistant] SELECT ea.contract_address, COUNT(*) AS approval_count, tm.symbol, tm.name FROM erc20_approval ea LEFT JOIN token_metas tm ON ea.contract_address = tm.contract_address WHERE ea.block_number BETWEEN 18000000 AND 18500000 GROUP BY ea.contract_address, tm.symbol, tm.name;

[User] Now only show tokens which have more than 100 approvals in this block range.

[Assistant] SELECT ea.contract_address, COUNT(*) AS approval_count, tm.symbol, tm.name FROM erc20_approval ea LEFT JOIN token_metas tm ON ea.contract_address = tm.contract_address WHERE ea.block_number BETWEEN 18000000 AND 18500000 GROUP BY ea.contract_address, tm.symbol, tm.name HAVING COUNT(*) > 100;

[User] Order the results by approval_count descending and limit to the top 5.

[Assistant] SELECT ea.contract_address, COUNT(*) AS approval_count, tm.symbol, tm.name FROM erc20_approval ea LEFT JOIN token_metas tm ON ea.contract_address = tm.contract_address WHERE ea.block_number BETWEEN 18000000 AND 18500000 GROUP BY ea.contract_address, tm.symbol, tm.name HAVING COUNT(*) > 100 ORDER BY approval_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 varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
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 nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk integer )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )