[User] Show me all active customers from California who were born before 1980, along with their contact information.

[Assistant] SELECT first_name, last_name, phone_number, email, address_line1, city, zip_code FROM insurance.customers WHERE state = 'California' AND date_of_birth < '1980-01-01' AND status = 'Active';

[User] Now filter these results to only show customers who have provided both a phone number and an email address.

[Assistant] SELECT first_name, last_name, phone_number, email, address_line1, city, zip_code FROM insurance.customers WHERE state = 'California' AND date_of_birth < '1980-01-01' AND status = 'Active' AND phone_number IS NOT NULL AND email IS NOT NULL;

[User] I also want to see how long these customers have been in our system (difference between current date and created_at in years).

[Assistant] SELECT first_name, last_name, phone_number, email, address_line1, city, zip_code, EXTRACT(YEAR FROM AGE(CURRENT_DATE, created_at)) AS years_in_system FROM insurance.customers WHERE state = 'California' AND date_of_birth < '1980-01-01' AND status = 'Active' AND phone_number IS NOT NULL AND email IS NOT NULL;

[User] Finally, order the results by the longest tenure in our system first, then by last name alphabetically.

[Assistant] SELECT first_name, last_name, phone_number, email, address_line1, city, zip_code, EXTRACT(YEAR FROM AGE(CURRENT_DATE, created_at)) AS years_in_system FROM insurance.customers WHERE state = 'California' AND date_of_birth < '1980-01-01' AND status = 'Active' AND phone_number IS NOT NULL AND email IS NOT NULL ORDER BY years_in_system DESC, last_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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] List all wallet addresses that have unspent UTXOs with amounts greater than 100, along with the total unspent amount for each address.

[Assistant] SELECT w.address, SUM(u.amount) AS total_unspent FROM trading_platform.wallets w JOIN trading_platform.utxos u ON w.address = u.address WHERE u.spent = false AND u.amount > 100 GROUP BY w.address;

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

[Assistant] SELECT w.address, SUM(u.amount) AS total_unspent FROM trading_platform.wallets w JOIN trading_platform.utxos u ON w.address = u.address WHERE u.spent = false AND u.amount > 100 AND w.created_at >= NOW() - INTERVAL '1 year' GROUP BY w.address;

[User] I notice the query has a typo in 'INTERVAL'. Also, can you include the user's email address in the results?

[Assistant] SELECT w.address, u.email, SUM(ut.amount) AS total_unspent FROM trading_platform.wallets w JOIN trading_platform.users u ON w.user_id = u.user_id JOIN trading_platform.utxos ut ON w.address = ut.address WHERE ut.spent = false AND ut.amount > 100 AND w.created_at >= NOW() - INTERVAL '1 year' GROUP BY w.address, u.email;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] List all pairs of tokens where the absolute difference in their decimals is exactly 2, showing both token_ids and their decimals.

[Assistant]
SELECT t1.token_id AS token_id1,
       t1.decimals AS decimals1,
       t2.token_id AS token_id2,
       t2.decimals AS decimals2
FROM web3.tokens t1
JOIN web3.tokens t2
  ON ABS(t1.decimals - t2.decimals) = 2
 AND t1.token_id < t2.token_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )


[User] List the latest version of each document (identified by case_id and document_name), showing the version number and its upload_timestamp.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version   AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m ON d.case_id = m.case_id
    AND d.document_name = m.document_name
    AND d.version = m.max_version;

[User] Actually, I also want to see the upload_timestamp of the previous version for each document.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version         AS latest_version,
       d_latest.upload_timestamp  AS latest_timestamp,
       d_prev.upload_timestamp    AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] Also, only include documents whose first version (version = 1) was uploaded in 2024.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version          AS latest_version,
       d_latest.upload_timestamp   AS latest_timestamp,
       d_prev.upload_timestamp     AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_first
  ON d_first.case_id = m.case_id
 AND d_first.document_name = m.document_name
 AND d_first.version = 1
 AND d_first.upload_timestamp >= '2024-01-01'
 AND d_first.upload_timestamp < '2025-01-01'
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 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.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )


[User] List each achievement with the very next achievement unlocked by the same player using a self-join. Show player_id, current_ach, current_unlocked_at, next_ach, and next_unlocked_at.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS current_ach,
       pa1.unlocked_at AS current_unlocked_at,
       pa2.achievement_id AS next_ach,
       pa2.unlocked_at AS next_unlocked_at
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa2.unlocked_at = (
     SELECT MIN(pa3.unlocked_at)
     FROM gaming_technology.player_achievements pa3
     WHERE pa3.player_id = pa1.player_id
       AND pa3.unlocked_at > pa1.unlocked_at
 );

[User] Now restrict to pairs where the time difference between current_unlocked_at and next_unlocked_at is less than 48 hours.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS current_ach,
       pa1.unlocked_at AS current_unlocked_at,
       pa2.achievement_id AS next_ach,
       pa2.unlocked_at AS next_unlocked_at
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa2.unlocked_at = (
     SELECT MIN(pa3.unlocked_at)
     FROM gaming_technology.player_achievements pa3
     WHERE pa3.player_id = pa1.player_id
       AND pa3.unlocked_at > pa1.unlocked_at
 )
WHERE pa2.unlocked_at - pa1.unlocked_at < INTERVAL '48 hours';

[User] Order the results by player_id and current_unlocked_at ascending.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS current_ach,
       pa1.unlocked_at AS current_unlocked_at,
       pa2.achievement_id AS next_ach,
       pa2.unlocked_at AS next_unlocked_at
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa2.unlocked_at = (
     SELECT MIN(pa3.unlocked_at)
     FROM gaming_technology.player_achievements pa3
     WHERE pa3.player_id = pa1.player_id
       AND pa3.unlocked_at > pa1.unlocked_at
 )
WHERE pa2.unlocked_at - pa1.unlocked_at < INTERVAL '48 hours'
ORDER BY pa1.player_id ASC, pa1.unlocked_at ASC;

[User] Finally, limit to 20 rows.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS current_ach,
       pa1.unlocked_at AS current_unlocked_at,
       pa2.achievement_id AS next_ach,
       pa2.unlocked_at AS next_unlocked_at
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa2.unlocked_at = (
     SELECT MIN(pa3.unlocked_at)
     FROM gaming_technology.player_achievements pa3
     WHERE pa3.player_id = pa1.player_id
       AND pa3.unlocked_at > pa1.unlocked_at
 )
WHERE pa2.unlocked_at - pa1.unlocked_at < INTERVAL '48 hours'
ORDER BY pa1.player_id ASC, pa1.unlocked_at ASC
LIMIT 20;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )


[User] What is the average, minimum, and maximum interest_rate for each loan_type among active loans?

[Assistant]
SELECT loan_type,
       AVG(interest_rate) AS avg_interest_rate,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate
FROM financial_services.loans
WHERE status = 'Active'
GROUP BY loan_type;

[User] Exclude loan types with fewer than 5 active loans.

[Assistant]
SELECT loan_type,
       AVG(interest_rate) AS avg_interest_rate,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate
FROM financial_services.loans
WHERE status = 'Active'
GROUP BY loan_type
HAVING COUNT(*) >= 5;

[User] Sort the result by average_interest_rate descending and only return the top 5 loan types.

[Assistant]
SELECT loan_type,
       AVG(interest_rate) AS avg_interest_rate,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate
FROM financial_services.loans
WHERE status = 'Active'
GROUP BY loan_type
HAVING COUNT(*) >= 5
ORDER BY avg_interest_rate 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 financial_services.loans (
    loan_id character varying(64) NOT NULL, -- unique identifier for the loan, could be same as account_id
    account_id character varying(64) NOT NULL UNIQUE, -- link to the general account record
    loan_type character varying(50) NOT NULL, -- e.g., Mortgage, Personal, Auto, Student
    principal_amount numeric(19, 4) NOT NULL, -- original loan amount
    current_principal_balance numeric(19, 4) NOT NULL, -- remaining principal
    interest_rate numeric(6, 4) NOT NULL, -- annual interest rate
    term_months integer NOT NULL, -- loan term in months
    origination_date date NOT NULL, -- date the loan was disbursed
    maturity_date date NOT NULL, -- date the loan is due to be fully repaid
    monthly_payment numeric(12, 4), -- scheduled monthly payment amount
    collateral_description text, -- description of collateral, if secured loan
    status character varying(32) NOT NULL, -- e.g., Active, Paid Off, Defaulted
    PRIMARY KEY (loan_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id)
)


[User] For each user, how many wallets have they created?

[Assistant] SELECT user_id, COUNT(*) AS wallet_count FROM trading_platform.wallets GROUP BY user_id;

[User] Actually, I want to see only users with more than one wallet.

[Assistant] SELECT user_id, COUNT(*) AS wallet_count FROM trading_platform.wallets GROUP BY user_id HAVING COUNT(*) > 1;

[User] I also want to know the earliest wallet creation date for each user in this list.

[Assistant] SELECT user_id, COUNT(*) AS wallet_count, MIN(created_at) AS first_wallet_created_at FROM trading_platform.wallets GROUP BY user_id HAVING COUNT(*) > 1;

[User] Can you order the results by the earliest wallet creation date, oldest first?

[Assistant] SELECT user_id, COUNT(*) AS wallet_count, MIN(created_at) AS first_wallet_created_at FROM trading_platform.wallets GROUP BY user_id HAVING COUNT(*) > 1 ORDER BY first_wallet_created_at ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )


[User] List all reservations where the number of adults is greater than 2, showing reservation_id, guest_id, and the total_amount.

[Assistant]
SELECT reservation_id, guest_id, total_amount
FROM hospitality_technology.reservations
WHERE num_adults > 2;

[User] Can you also include the room_type_id and the status for each reservation?

[Assistant]
SELECT reservation_id, guest_id, room_type_id, status, total_amount
FROM hospitality_technology.reservations
WHERE num_adults > 2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] What is the average ROI and average realized_ratio for each chain?

[Assistant]
SELECT chain,
       AVG(roi) AS avg_roi,
       AVG(realized_ratio) AS avg_realized_ratio
FROM smart_money_token_performance
GROUP BY chain;

[User] Now filter to only include chains where average ROI is above 0.5.

[Assistant]
WITH stats AS (
  SELECT chain,
         AVG(roi) AS avg_roi,
         AVG(realized_ratio) AS avg_realized_ratio
  FROM smart_money_token_performance
  GROUP BY chain
)
SELECT chain, avg_roi, avg_realized_ratio
FROM stats
WHERE avg_roi > 0.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 smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )


[User] Show all SUI coins with 'exists' status and more than 8 decimal places. Display coin_type, symbol, name, and decimals.

[Assistant]
SELECT coin_type, symbol, name, decimals
FROM sui_coins_metadata
WHERE status = 'exists' AND decimals > 8;

[User] Add the total balance for each coin_type by joining with sui_coins.

[Assistant]
SELECT scm.coin_type, scm.symbol, scm.name, scm.decimals, SUM(sc.balance::numeric) AS total_balance
FROM sui_coins_metadata scm
JOIN sui_coins sc ON scm.coin_type = sc.coin_type
WHERE scm.status = 'exists' AND scm.decimals > 8
GROUP BY scm.coin_type, scm.symbol, scm.name, scm.decimals;

[User] Can you also include only coins where the total_balance is greater than 1,000,000 and show the description?

[Assistant]
SELECT scm.coin_type, scm.symbol, scm.name, scm.decimals, scm.description, SUM(sc.balance::numeric) AS total_balance
FROM sui_coins_metadata scm
JOIN sui_coins sc ON scm.coin_type = sc.coin_type
WHERE scm.status = 'exists' AND scm.decimals > 8
GROUP BY scm.coin_type, scm.symbol, scm.name, scm.decimals, scm.description
HAVING SUM(sc.balance::numeric) > 1000000;

[User] Actually, only show the top 5 coins with the highest total_balance.

[Assistant]
SELECT scm.coin_type, scm.symbol, scm.name, scm.decimals, scm.description, SUM(sc.balance::numeric) AS total_balance
FROM sui_coins_metadata scm
JOIN sui_coins sc ON scm.coin_type = sc.coin_type
WHERE scm.status = 'exists' AND scm.decimals > 8
GROUP BY scm.coin_type, scm.symbol, scm.name, scm.decimals, scm.description
HAVING SUM(sc.balance::numeric) > 1000000
ORDER BY total_balance 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 nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE 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 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 varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE 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_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_avalanche (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(42) NOT NULL, -- Address sending the inscription
    to_address varchar(42) NOT NULL  -- Address receiving the inscription
)
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )


[User] What is the total revenue generated for each department from delivered service orders? Return department and total_revenue.

[Assistant]
SELECT s.department,
       SUM(so.total_price) AS total_revenue
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
WHERE so.status = 'Delivered'
GROUP BY s.department;

[User] Now limit to service orders delivered in the last month and only include departments with total_revenue > 1000.

[Assistant]
SELECT s.department,
       SUM(so.total_price) AS total_revenue
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
WHERE so.status = 'Delivered'
  AND so.delivery_timestamp >= date_trunc('month', current_date - INTERVAL '1 month')
  AND so.delivery_timestamp < date_trunc('month', current_date)
GROUP BY s.department
HAVING SUM(so.total_price) > 1000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


[User] Can you show me all developers along with the year they were founded and their website, grouped by country?

[Assistant] SELECT country, array_agg(name) AS developers, array_agg(founded_year) AS founded_years, array_agg(website) AS websites FROM gaming_technology.developers GROUP BY country;

[User] Can you add the number of developers per country to the result?

[Assistant] SELECT country, COUNT(*) AS developer_count, array_agg(name) AS developers, array_agg(founded_year) AS founded_years, array_agg(website) AS websites FROM gaming_technology.developers GROUP BY country;

[User] I'd like to see only countries with at least two developers. Can you modify the query?

[Assistant] SELECT country, COUNT(*) AS developer_count, array_agg(name) AS developers, array_agg(founded_year) AS founded_years, array_agg(website) AS websites FROM gaming_technology.developers GROUP BY country HAVING COUNT(*) >= 2;

[User] Actually, could you also include the earliest founded year of a developer in each country?

[Assistant] SELECT country, COUNT(*) AS developer_count, MIN(founded_year) AS earliest_founded_year, array_agg(name) AS developers, array_agg(founded_year) AS founded_years, array_agg(website) AS websites FROM gaming_technology.developers GROUP BY country HAVING COUNT(*) >= 2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )


[User] List all insurance products that have 'auto' in their product type and are currently active, showing their product name and base premium.

[Assistant] SELECT product_name, base_premium FROM insurance.insurance_products WHERE product_type LIKE '%auto%' AND is_active = true;

[User] Now order these results by base premium in descending order and include the coverage details.

[Assistant] SELECT product_name, base_premium, coverage_details FROM insurance.insurance_products WHERE product_type LIKE '%auto%' AND is_active = true ORDER BY base_premium 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.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )


[User] List all unique pairs of routes that share the same destination location, and show the route numbers and their type for both routes.

[Assistant]
SELECT r1.route_number AS route_number_1, r1.type AS type_1, r2.route_number AS route_number_2, r2.type AS type_2, r1.destination_location_id
FROM transportation.routes r1
JOIN transportation.routes r2
  ON r1.destination_location_id = r2.destination_location_id
  AND r1.route_id < r2.route_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )


[User] Show me all available spa services (category = 'Wellness') with their names and prices, ordered by price in descending order.

[Assistant] SELECT service_name, price FROM hospitality_technology.services WHERE category = 'Wellness' AND is_available = true ORDER BY price DESC;

[User] Now, include only services from properties with ID starting with 'PROP1' and show their property IDs as well.

[Assistant] SELECT service_name, price, property_id FROM hospitality_technology.services WHERE category = 'Wellness' AND is_available = true AND property_id LIKE 'PROP1%' ORDER BY price 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 hospitality_technology.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)


[User] Find the contract ID, address, and deployer address for all contracts that have not emitted any events.

[Assistant] SELECT c.contract_id, c.address, c.deployer_address FROM web3.contracts AS c LEFT JOIN web3.events AS e ON c.contract_id = e.contract_id WHERE e.event_id IS NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
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 text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


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

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

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

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

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

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

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


[User] Retrieve the count of active insurance products for each product_type and order the results by the count descending.

[Assistant]
SELECT product_type,
       COUNT(*) AS active_count
FROM insurance.insurance_products
WHERE is_active = TRUE
GROUP BY product_type
ORDER BY active_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )


[User] Show all routes including their number, type, and description.

[Assistant] SELECT route_number ,  type ,  description FROM transportation.routes

[User] Only show routes of type 'City Bus'.

[Assistant] SELECT route_number ,  type ,  description FROM transportation.routes WHERE type  =  'City Bus'

[User] For these 'City Bus' routes, include the origin and destination city names.

[Assistant] SELECT T1.route_number ,  T1.type ,  T1.description ,  T2.city AS origin_city ,  T3.city AS destination_city FROM transportation.routes AS T1 JOIN transportation.locations AS T2 ON T1.origin_location_id  =  T2.location_id JOIN transportation.locations AS T3 ON T1.destination_location_id  =  T3.location_id WHERE T1.type  =  'City Bus'

[User] Order the results by route number in ascending order and limit to the first 10.

[Assistant] SELECT T1.route_number ,  T1.type ,  T1.description ,  T2.city AS origin_city ,  T3.city AS destination_city FROM transportation.routes AS T1 JOIN transportation.locations AS T2 ON T1.origin_location_id  =  T2.location_id JOIN transportation.locations AS T3 ON T1.destination_location_id  =  T3.location_id WHERE T1.type  =  'City Bus' ORDER BY T1.route_number ASC LIMIT 10

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.drivers (
    driver_id character varying(64) NOT NULL,  -- unique identifier for the driver
    employee_id character varying(64) NOT NULL UNIQUE, -- employee reference number
    first_name character varying(128) NOT NULL, -- driver's first name
    last_name character varying(128) NOT NULL, -- driver's last name
    license_number character varying(64) NOT NULL UNIQUE, -- driving license number
    license_expiry_date date NOT NULL, -- expiry date of the license
    contact_number character varying(32), -- phone number
    email character varying(128) UNIQUE, -- email address
    hire_date date NOT NULL, -- date the driver was hired
    status character varying(32) NOT NULL, -- e.g., Active, On Leave, Terminated
    PRIMARY KEY (driver_id)
)
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.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.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] Give me the total billed amount for each invoice in 2024.

[Assistant] SELECT invoice_id, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE AND EXTRACT(YEAR FROM date_worked) = 2024 GROUP BY invoice_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 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 )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )


[User] Which chain has the highest total USD inflow from buy transactions (type=1), and how many distinct tokens were involved in that inflow?

[Assistant]
SELECT chain, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY chain
ORDER BY total_inflow DESC
LIMIT 1;

[User] I also want to see the average price at which those tokens were bought for that chain.

[Assistant]
WITH inflow AS (
  SELECT chain, SUM(usd_value) AS total_inflow
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY chain
), top_chain AS (
  SELECT chain FROM inflow ORDER BY total_inflow DESC LIMIT 1
)
SELECT i.chain, AVG(i.avg_price) AS avg_buy_price
FROM smart_money_token_inflow i
JOIN top_chain t ON i.chain = t.chain
WHERE i.type = 1;

[User] Actually, filter to narratives where the total USD inflow is above 50000.

[Assistant]
SELECT narrative, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY narrative
HAVING SUM(usd_value) > 50000;

[User] Please order the results by average price descending and show the top 2 chains.

[Assistant]
SELECT chain, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens, AVG(avg_price) AS avg_buy_price
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY chain
ORDER BY avg_buy_price DESC
LIMIT 2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )


[User] Could you list each game title along with its developer's name and the total number of servers hosting it?

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
LEFT JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
LEFT JOIN gaming_technology.servers s ON g.game_id = s.game_id
GROUP BY g.title, d.name;

[User] Actually, please include only servers with status = 'online' and exclude games with zero online servers.

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
JOIN gaming_technology.servers s ON g.game_id = s.game_id
WHERE s.status = 'online'
GROUP BY g.title, d.name;

[User] I want to see only developers based in 'USA'.

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
JOIN gaming_technology.servers s ON g.game_id = s.game_id AND s.status = 'online'
WHERE d.country = 'USA'
GROUP BY g.title, d.name;

[User] Finally, sort the results by server_count in descending order.

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
JOIN gaming_technology.servers s ON g.game_id = s.game_id AND s.status = 'online'
WHERE d.country = 'USA'
GROUP BY g.title, d.name
ORDER BY server_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 gaming_technology.games ( game_id uuid, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid, player_id uuid, item_id uuid, quantity integer, acquired_at timestamp with time zone, instance_data jsonb )


[User] For each user with at least two wallets, calculate the average time difference in hours between consecutive wallet creations. Return user_id and avg_diff_hours.

[Assistant] SELECT user_id, AVG(EXTRACT(EPOCH FROM (created_at - prev_created)) / 3600) AS avg_diff_hours FROM (SELECT user_id, created_at, LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at) AS prev_created FROM web3.wallets) t WHERE prev_created IS NOT NULL GROUP BY user_id;

[User] Actually, restrict the results to users whose avg_diff_hours is less than 24 hours and sort by avg_diff_hours ascending.

[Assistant] WITH diffs AS (SELECT user_id, EXTRACT(EPOCH FROM (created_at - prev_created)) / 3600 AS diff_hours FROM (SELECT user_id, created_at, LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at) AS prev_created FROM web3.wallets) sub WHERE prev_created IS NOT NULL) SELECT user_id, AVG(diff_hours) AS avg_diff_hours FROM diffs GROUP BY user_id HAVING AVG(diff_hours) < 24 ORDER BY avg_diff_hours;

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.contracts (
    contract_id character varying(64) NOT NULL,  -- unique identifier for the contract
    address character varying(128) NOT NULL, -- address of the deployed contract
    abi text NOT NULL, -- application binary interface of the contract
    bytecode text NOT NULL, -- bytecode of the contract
    deployer_address character varying(128) NOT NULL, -- address of the deployer
    deployed_at timestamp NOT NULL, -- time when the contract was deployed
    network_id character varying(64) NOT NULL, -- identifier of the network where the contract is deployed
    status character varying(32) NOT NULL, -- status of the contract (e.g., active, deprecated)
    PRIMARY KEY (contract_id)
)
CREATE TABLE web3.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_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)
)


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

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.contract_address WHERE tm.is_erc20 = 1 AND tpl.price BETWEEN 1 AND 10;

[User] I think there's an error in your query - the token_prices_latest table isn't in the schema. Can you modify it to use the token_balances table instead?

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address FROM token_metas tm JOIN token_balances tb ON tm.contract_address = tb.wallet_address WHERE tm.is_erc20 = 1 AND CAST(tb.amount AS decimal) BETWEEN 1 AND 10;

[User] That doesn't seem right either. Let's just get the basic ERC20 token information without price filtering for now.

[Assistant] SELECT name, symbol, contract_address FROM token_metas WHERE is_erc20 = 1 LIMIT 100;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint, 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_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities ( 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 NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
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_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 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 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 all patients who have been diagnosed with chronic conditions, including their diagnosis descriptions and dates.

[Assistant] SELECT p.first_name, p.last_name, d.description, d.diagnosis_date FROM healthcare.patients p JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id WHERE d.is_chronic = true ORDER BY d.diagnosis_date DESC;

[User] Actually, I only need patients who were diagnosed in the last year.

[Assistant] SELECT p.first_name, p.last_name, d.description, d.diagnosis_date FROM healthcare.patients p JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id WHERE d.is_chronic = true AND d.diagnosis_date >= CURRENT_DATE - INTERVAL '1 year' ORDER BY d.diagnosis_date DESC;

[User] Can you also include the diagnosing doctor's last name?

[Assistant] SELECT p.first_name, p.last_name, d.description, d.diagnosis_date, doc.last_name AS doctor_last_name FROM healthcare.patients p JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id JOIN healthcare.doctors doc ON d.doctor_id = doc.doctor_id WHERE d.is_chronic = true AND d.diagnosis_date >= CURRENT_DATE - INTERVAL '1 year' ORDER BY d.diagnosis_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.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.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_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.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] For each asset, show its name and symbol, and the total number of completed orders that have resulted in at least one trade.

[Assistant]
SELECT a.name, a.symbol, COUNT(DISTINCT o.order_id) AS completed_order_count
FROM trading_platform.assets a
JOIN trading_platform.orders o ON o.asset_id = a.asset_id AND o.status = 'filled'
JOIN trading_platform.trades t ON t.order_id = o.order_id
GROUP BY a.asset_id, a.name, a.symbol;

[User] Only include assets where the total number of completed orders with trades is greater than 5, and sort the results by completed_order_count descending.

[Assistant]
SELECT a.name, a.symbol, COUNT(DISTINCT o.order_id) AS completed_order_count
FROM trading_platform.assets a
JOIN trading_platform.orders o ON o.asset_id = a.asset_id AND o.status = 'filled'
JOIN trading_platform.trades t ON t.order_id = o.order_id
GROUP BY a.asset_id, a.name, a.symbol
HAVING COUNT(DISTINCT o.order_id) > 5
ORDER BY completed_order_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 trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] For each trip, show the trip ID, scheduled departure, and the last name of the driver.

[Assistant]
SELECT t.trip_id, t.scheduled_departure, d.last_name
FROM transportation.trips t
JOIN transportation.drivers d ON t.driver_id = d.driver_id;

[User] I see some trip IDs are repeated. Only show distinct pairs of trip ID and driver last name.

[Assistant]
SELECT DISTINCT t.trip_id, d.last_name
FROM transportation.trips t
JOIN transportation.drivers d ON t.driver_id = d.driver_id;

[User] Also, for these trips, include the name of the destination location.

[Assistant]
SELECT DISTINCT t.trip_id, d.last_name, l.name AS destination_location_name
FROM transportation.trips t
JOIN transportation.drivers d ON t.driver_id = d.driver_id
JOIN transportation.locations l ON t.destination_location_id = l.location_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.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.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 character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )


[User] For each token, show its token_id, decimals, and the average total_supply of all tokens with the same decimals.

[Assistant]
SELECT t.token_id,
       t.decimals,
       avg_data.avg_total_supply
FROM web3.tokens t
JOIN (
  SELECT decimals,
         AVG(total_supply) AS avg_total_supply
  FROM web3.tokens
  GROUP BY decimals
) AS avg_data
  ON t.decimals = avg_data.decimals;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)


[User] Show the number of achievements unlocked by each player per month. Display player_id, month (as YYYY-MM), and achievement_count.

[Assistant]
SELECT player_id,
       TO_CHAR(unlocked_at, 'YYYY-MM') AS year_month,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, TO_CHAR(unlocked_at, 'YYYY-MM');

[User] Filter to months where players unlocked at least 5 achievements.

[Assistant]
SELECT player_id,
       TO_CHAR(unlocked_at, 'YYYY-MM') AS year_month,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, TO_CHAR(unlocked_at, 'YYYY-MM')
HAVING COUNT(*) >= 5;

[User] Sort the results by year_month ascending and then by achievement_count descending.

[Assistant]
SELECT player_id,
       TO_CHAR(unlocked_at, 'YYYY-MM') AS year_month,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, TO_CHAR(unlocked_at, 'YYYY-MM')
HAVING COUNT(*) >= 5
ORDER BY year_month ASC, achievement_count DESC;

[User] Limit the results to 10 rows.

[Assistant]
SELECT player_id,
       TO_CHAR(unlocked_at, 'YYYY-MM') AS year_month,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, TO_CHAR(unlocked_at, 'YYYY-MM')
HAVING COUNT(*) >= 5
ORDER BY year_month ASC, achievement_count DESC
LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )


[User] Show me the top 5 ERC20 tokens with the highest total supply, along with their names and contract addresses, but only include tokens where the price is greater than $0.1.

[Assistant] SELECT tm.name, tm.contract_address, tm.total_supply, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price > 0.1 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] I think there's an error in your query - it should be 'tpl.symbol' not 'tm.symbol'. Also, can you add the decimals to the results?

[Assistant] SELECT tm.name, tm.contract_address, tm.decimals, tm.total_supply, tpl.symbol, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price > 0.1 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] Now filter these results to only show tokens with decimals equal to 18.

[Assistant] SELECT tm.name, tm.contract_address, tm.decimals, tm.total_supply, tpl.symbol, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price > 0.1 AND tm.decimals = 18 ORDER BY CAST(tm.total_supply AS decimal) 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 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_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 sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner 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 token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
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_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_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )


[User] Could you list the top 5 narratives by their 7-day price change percentage, including the number of tokens and their top 3 coins?

[Assistant] SELECT narrative, price_change_percentage_7d, token_num, top_3_coins FROM narrative_info ORDER BY price_change_percentage_7d DESC LIMIT 5;

[User] Now, for these narratives, show the token with the highest current price from token_basic_info. Return narrative, token_symbol, and max price.

[Assistant] SELECT n.narrative, t.token_symbol, t.price FROM token_basic_info t JOIN narrative_info n ON t.narrative = n.narrative WHERE t.price = (SELECT MAX(price) FROM token_basic_info WHERE narrative = n.narrative);

[User] Filter to only include narratives where token_num > 10 and volume_24h > 1000000.

[Assistant] SELECT n.narrative, t.token_symbol, t.price FROM token_basic_info t JOIN narrative_info n ON t.narrative = n.narrative WHERE t.price = (SELECT MAX(price) FROM token_basic_info WHERE narrative = n.narrative) AND n.token_num > 10 AND n.volume_24h > 1000000;

[User] Finally, limit to the top 3 narratives by 7-day price change and include volume_24h.

[Assistant] SELECT n.narrative, n.price_change_percentage_7d, n.volume_24h, t.token_symbol, t.price FROM token_basic_info t JOIN narrative_info n ON t.narrative = n.narrative WHERE t.price = (SELECT MAX(price) FROM token_basic_info WHERE narrative = n.narrative) AND n.token_num > 10 AND n.volume_24h > 1000000 ORDER BY n.price_change_percentage_7d 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 project_fundraising_record ( id character varying(32) NOT NULL, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, token_address character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, highest_price_24h double precision, lowest_price_24h double precision, market_cap double precision, market_cap_rank bigint, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank bigint )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, top_3_coins text, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, market_cap double precision, volume_24h double precision, trend_rank bigint, token_num bigint )
CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL, chain character varying(128) NOT NULL, address character varying(128) NOT NULL, exchange character varying(512) NOT NULL, token_address character varying(128) NOT NULL, token_symbol character varying(512), balance numeric(38,10), usd_value numeric(38,14), price double precision )
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, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, token_symbol character varying(100), token_amount numeric(38,2), usd_value numeric(38,2), avg_price numeric(38,6), type int, address_amount integer, narrative character varying(100), chain character varying(100) )


[User] List all trips that were completed and experienced a significant delay in actual arrival compared to the scheduled arrival (more than 45 minutes).

[Assistant]
SELECT
  trip_id,
  vehicle_id,
  driver_id,
  scheduled_arrival,
  actual_arrival,
  (actual_arrival - scheduled_arrival) AS arrival_delay
FROM transportation.trips
WHERE
  status = 'Completed'
  AND actual_arrival IS NOT NULL
  AND actual_arrival > scheduled_arrival + INTERVAL '45 minutes';

[User] For those completed trips with significant arrival delays, provide a count of how many fall into different delay duration categories: '45-90 mins', '>90 mins'.

[Assistant]
SELECT
  CASE
    WHEN (actual_arrival - scheduled_arrival) > INTERVAL '45 minutes' AND (actual_arrival - scheduled_arrival) <= INTERVAL '90 minutes' THEN '45-90 mins'
    WHEN (actual_arrival - scheduled_arrival) > INTERVAL '90 minutes' THEN '>90 mins'
    ELSE 'Other Delays' -- Should not be reached based on previous filter, but good practice
  END AS delay_category,
  COUNT(*)
FROM transportation.trips
WHERE
  status = 'Completed'
  AND actual_arrival IS NOT NULL
  AND actual_arrival > scheduled_arrival + INTERVAL '45 minutes'
GROUP BY
  delay_category;

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.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)