[User] Show me wallet addresses that hold more than 1000 of any ERC1155 token, along with the token ID and contract address.

[Assistant] SELECT wallet_address, token_id, contract_address FROM erc20_balances WHERE CAST(amount AS decimal) > 1000;

[User] I think there's an error in your query - it should be using the nft_metadata table for ERC1155 tokens. Also, can you include the token name from the nft_metadata table?

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


[User] Show a list of all wallet addresses along with the user_id who owns them, sorted by the wallet creation time.

[Assistant] SELECT user_id, address FROM web3.wallets ORDER BY created_at;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.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] I want to see, for each guest, the total number of payments they have made and the timestamp of their latest payment.

[Assistant]
SELECT p.guest_id,
       COUNT(p.payment_id) AS payment_count,
       t.last_ts
FROM hospitality_technology.payments p
JOIN (
    SELECT guest_id,
           MAX(payment_timestamp) AS last_ts
    FROM hospitality_technology.payments
    GROUP BY guest_id
) t ON p.guest_id = t.guest_id
GROUP BY p.guest_id, t.last_ts;

[User] Only include guests whose latest payment status was 'Succeeded' and who have made at least 5 successful payments.

[Assistant]
SELECT p.guest_id,
       COUNT(p.payment_id) AS payment_count,
       t.last_ts
FROM hospitality_technology.payments p
JOIN (
    SELECT guest_id,
           MAX(payment_timestamp) AS last_ts,
           COUNT(*) AS cnt
    FROM hospitality_technology.payments
    WHERE status = 'Succeeded'
    GROUP BY guest_id
    HAVING COUNT(*) >= 5
) t ON p.guest_id = t.guest_id
GROUP BY p.guest_id, t.last_ts;

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.payments ( payment_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, bill_id character varying(64), amount numeric(12,2) NOT NULL, currency_code character varying(3) NOT NULL, payment_method character varying(50) NOT NULL, card_type character varying(50), card_last_four character varying(4), transaction_ref character varying(128), payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, status character varying(50) NOT NULL, staff_id_processed character varying(64), notes text, PRIMARY KEY (payment_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id) )


[User] Count the total number of chronic diagnoses for each code_type.

[Assistant]
SELECT
  code_type,
  COUNT(*) AS chronic_diagnosis_count
FROM healthcare.diagnoses
WHERE is_chronic = TRUE
GROUP BY code_type;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )


[User] List each guest’s full name and the total number of service orders they have placed, ordered by order count descending.

[Assistant]
SELECT g.guest_id,
       g.first_name || ' ' || g.last_name AS full_name,
       COUNT(so.order_id) AS order_count
FROM hospitality_technology.guests g
LEFT JOIN hospitality_technology.service_orders so
  ON g.guest_id = so.guest_id
GROUP BY g.guest_id, full_name
ORDER BY 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 hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] List the first name, last name, and hire date of all lawyers who are partners.

[Assistant] SELECT first_name ,  last_name ,  hire_date FROM legal_services.lawyers WHERE is_partner  =  TRUE

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)


[User] List all posts where the content mentions 'meeting'.

[Assistant] SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE content LIKE '%meeting%'

[User] Also, only include those posts that are public.

[Assistant] SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE content LIKE '%meeting%' AND visibility = 'public'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )


[User] Find all users who registered with a Yahoo email address, along with their registration dates.

[Assistant] SELECT user_id, username, email, password_hash FROM blockchain.users WHERE email LIKE '%@yahoo.com';

[User] This query doesn't show registration dates. Can you modify it to include the registration date?

[Assistant] I notice the users table doesn't have a registration date column. Would you like me to show other available information from the users table?

[User] Then just show me the count of Yahoo email users instead.

[Assistant] SELECT COUNT(*) as yahoo_user_count FROM blockchain.users WHERE email LIKE '%@yahoo.com';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id text, previous_block_id text, timestamp timestamp, nonce integer, merkle_root text, difficulty integer )
CREATE TABLE blockchain.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    block_id character varying(64) NOT NULL, -- identifier of the block containing the transaction
    sender_address character varying(128) NOT NULL, -- address of the sender
    receiver_address character varying(128) NOT NULL, -- address of the receiver
    amount numeric(38,14) NOT NULL, -- amount transferred
    timestamp timestamp NOT NULL, -- time when the transaction was created
    signature text NOT NULL, -- digital signature of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE blockchain.addresses ( address_id text PRIMARY KEY, public_key text, balance numeric )
CREATE TABLE blockchain.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, PRIMARY KEY (user_id) )


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

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

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

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

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

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

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

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

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


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

[Assistant] SELECT u.user_id, u.username, w.wallet_id, w.created_at FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id LEFT JOIN trading_platform.orders o ON u.user_id = o.user_id WHERE o.order_id IS NULL ORDER BY w.created_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)


[User] What is the total USD value held across all wallets for the ERC20 token with symbol 'DAI'?

[Assistant]
SELECT SUM((eb.amount::numeric / POWER(10, tm.decimals)) * tpl.price) AS total_usd
FROM erc20_balances eb
JOIN token_metas tm ON eb.contract_address = tm.contract_address AND tm.symbol = 'DAI'
JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tpl.blockchain = 'Ethereum';

[User] Could you break it down to show the top 5 wallets by USD value for this token?

[Assistant]
SELECT eb.wallet_address,
       SUM((eb.amount::numeric / POWER(10, tm.decimals)) * tpl.price) AS usd_value
FROM erc20_balances eb
JOIN token_metas tm ON eb.contract_address = tm.contract_address AND tm.symbol = 'DAI'
JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tpl.blockchain = 'Ethereum'
GROUP BY eb.wallet_address
ORDER BY usd_value DESC
LIMIT 5;

[User] I received a type error because amount is stored as text. Can you cast the fields to numeric explicitly in the query?

[Assistant]
SELECT eb.wallet_address,
       SUM((CAST(eb.amount AS numeric) / POWER(10, tm.decimals)) * CAST(tpl.price AS numeric)) AS usd_value
FROM erc20_balances eb
JOIN token_metas tm ON eb.contract_address = tm.contract_address AND tm.symbol = 'DAI'
JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tpl.blockchain = 'Ethereum'
GROUP BY eb.wallet_address
ORDER BY usd_value DESC
LIMIT 5;

[User] Also include the latest price timestamp alongside the USD value for each wallet.

[Assistant]
SELECT eb.wallet_address,
       SUM((CAST(eb.amount AS numeric) / POWER(10, tm.decimals)) * tpl.price) AS usd_value,
       MAX(tpl.timestamp) AS price_timestamp
FROM erc20_balances eb
JOIN token_metas tm ON eb.contract_address = tm.contract_address AND tm.symbol = 'DAI'
JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tpl.blockchain = 'Ethereum'
GROUP BY eb.wallet_address
ORDER BY usd_value DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint 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, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE erc20_balances_historical (
    block_number bigint NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract
    amount varchar NOT NULL, -- Wallet's on-chain balance at the corresponding block height
    pk integer NOT NULL  -- Partition key for the table(floor(block_number / 7200))
)
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
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, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    name varchar NOT NULL, -- name fields for the functionType  in contract
    symbol varchar NOT NULL, -- symbol fields for the functionType  in contract
    deploy_block_number bigint NOT NULL, -- deploy_block_number fields for the functionType  in contract
    deploy_block_time bigint NOT NULL, -- deploy_block_time fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    description varchar NOT NULL, -- description fields for the functionType  in contract
    slug varchar NOT NULL, -- slug fields for the functionType  in contract
    media_info varchar NOT NULL, -- media_info fields for the functionType  in contract
    image_url varchar NOT NULL, -- image_url fields for the functionType  in contract
    banner_image_url varchar NOT NULL, -- banner_image_url fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    banner varchar NOT NULL, -- banner fields for the functionType  in contract
    token_count bigint NOT NULL, -- token_count fields for the functionType  in contract
    floor_price varchar NOT NULL, -- floor_price fields for the functionType  in contract
    floor_price_symbol varchar NOT NULL, -- floor_price_symbol fields for the functionType  in contract
    floor_price_contract varchar NOT NULL, -- floor_price_contract fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(deploy_block_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, 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, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
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_info_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(255) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_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] List all active policies, showing the policy number, the customer's full name, and the agent's full name who sold the policy.

[Assistant] SELECT T1.policy_number, T2.first_name, T2.last_name, T3.first_name, T3.last_name FROM policies AS T1 JOIN customers AS T2 ON T1.customer_id = T2.customer_id JOIN agents AS T3 ON T1.agent_id = T3.agent_id WHERE T1.status = 'active'

[User] Can you also add the product name and the policy's premium amount to the results?

[Assistant] SELECT T1.policy_number, T2.first_name AS customer_first_name, T2.last_name AS customer_last_name, T3.first_name AS agent_first_name, T3.last_name AS agent_last_name, T4.product_name, T1.premium_amount FROM policies AS T1 JOIN customers AS T2 ON T1.customer_id = T2.customer_id JOIN agents AS T3 ON T1.agent_id = T3.agent_id JOIN insurance_products AS T4 ON T1.product_id = T4.product_id WHERE T1.status = 'active'

[User] Actually, filter those results to only include policies with a premium amount greater than 5000 and only sold by agents whose license state is 'CA'.

[Assistant] SELECT T1.policy_number, T2.first_name AS customer_first_name, T2.last_name AS customer_last_name, T3.first_name AS agent_first_name, T3.last_name AS agent_last_name, T4.product_name, T1.premium_amount FROM policies AS T1 JOIN customers AS T2 ON T1.customer_id = T2.customer_id JOIN agents AS T3 ON T1.agent_id = T3.agent_id JOIN insurance_products AS T4 ON T1.product_id = T4.product_id WHERE T1.status = 'active' AND T1.premium_amount > 5000 AND T3.license_state = 'CA'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )


[User] How many posts have a media file attached?

[Assistant] SELECT count(*) FROM social_media.posts WHERE media_url IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text PRIMARY KEY, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text PRIMARY KEY, post_id text, hashtag_id text )
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )


[User] Get the number of agents grouped by status. Return status and agent_count.

[Assistant]
SELECT status,
       COUNT(*) AS agent_count
  FROM insurance.agents
 GROUP BY status;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )


[User] Count the number of posts that have a media URL but no textual content.

[Assistant] SELECT COUNT(*) FROM social_media.posts AS T1 WHERE T1.media_url IS NOT NULL AND (T1.content IS NULL OR T1.content = '');

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_id)
)
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_id)
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)


[User] Show me all ERC20 token transfers where the amount is over 5000, including the sender and receiver addresses.

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

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

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


[User] For each claim, show the corresponding product_type of the insurance product for the related policy.

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

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

[Assistant]
-- Unable to join directly since there is no 'policies' table connecting claims to insurance_products. If policy_id equals product_id, you may try:
SELECT claim_id, policy_id, product_type
FROM insurance.claims
JOIN insurance.insurance_products ON claims.policy_id = insurance_products.product_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )


[User] 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] How many documents of each type exist in the system? Show the document type and the count.

[Assistant]
SELECT document_type, COUNT(*) AS document_count
FROM legal_services.documents
group BY document_type;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id 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 )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )


[User] For projects that have completed more than one fundraising round, calculate the average investment value across all their recorded rounds. Display the project name and this average value.

[Assistant] SELECT project_name, AVG(investment_value) AS average_investment FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1;

[User] Can you modify this to only show projects where the average investment value is greater than 10 million USD and order the results by average investment value descending?

[Assistant] SELECT project_name, AVG(investment_value) AS average_investment FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1 AND AVG(investment_value) > 10000000 ORDER BY average_investment 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 project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)


[User] What is the fuel consumption rate of train number T1234?

[Assistant] I'm sorry, but I don't have information on the fuel consumption rate of train number T1234. The data available in the system only includes details such as train ID, model, manufacturer, year manufactured, capacity, status, and maintenance dates.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.trains ( train_id character varying(64) NOT NULL, train_number character varying(32) NOT NULL, model character varying(128), manufacturer character varying(128), year_manufactured integer, capacity integer NOT NULL, status character varying(32) NOT NULL DEFAULT 'Active', last_maintenance_date date, next_maintenance_date date, PRIMARY KEY (train_id), UNIQUE (train_number) )


[User] How many hashtags have been created in March 2024?

[Assistant]
```sql
SELECT COUNT(*) AS march_2024_hashtag_count
FROM social_media.hashtags
WHERE created_at >= '2024-03-01'
  AND created_at <  '2024-04-01';
```

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )
CREATE TABLE social_media.hashtags ( hashtag_id text PRIMARY KEY, tag_name text, created_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )


[User] Show each player's username and the number of distinct games they have played sessions on.

[Assistant]
SELECT
  p.username,
  COUNT(DISTINCT gs.game_id) AS games_played
FROM gaming_technology.players p
JOIN gaming_technology.game_sessions gs
  ON p.player_id = gs.player_id
GROUP BY p.username;

[User] Now include each player's total number of achievements unlocked.

[Assistant]
SELECT
  p.username,
  COUNT(DISTINCT gs.game_id) AS games_played,
  COUNT(pa.achievement_id)      AS achievements_unlocked
FROM gaming_technology.players p
JOIN gaming_technology.game_sessions gs
  ON p.player_id = gs.player_id
LEFT JOIN gaming_technology.player_achievements pa
  ON p.player_id = pa.player_id
GROUP BY p.username;

[User] Exclude players who have played fewer than 3 games or have not unlocked any achievements.

[Assistant]
SELECT
  p.username,
  COUNT(DISTINCT gs.game_id) AS games_played,
  COUNT(pa.achievement_id)      AS achievements_unlocked
FROM gaming_technology.players p
JOIN gaming_technology.game_sessions gs
  ON p.player_id = gs.player_id
LEFT JOIN gaming_technology.player_achievements pa
  ON p.player_id = pa.player_id
GROUP BY p.username
HAVING COUNT(DISTINCT gs.game_id) >= 3
   AND COUNT(pa.achievement_id) > 0;

[User] Also include the first session start_time as first_play and the first achievement unlocked date as first_achievement.

[Assistant]
SELECT
  p.username,
  COUNT(DISTINCT gs.game_id)      AS games_played,
  COUNT(pa.achievement_id)         AS achievements_unlocked,
  MIN(gs.start_time)               AS first_play,
  MIN(pa.unlocked_at)              AS first_achievement
FROM gaming_technology.players p
JOIN gaming_technology.game_sessions gs
  ON p.player_id = gs.player_id
LEFT JOIN gaming_technology.player_achievements pa
  ON p.player_id = pa.player_id
GROUP BY p.username
HAVING COUNT(DISTINCT gs.game_id) >= 3
   AND COUNT(pa.achievement_id) > 0;

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.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, game_id uuid NOT NULL, server_id uuid, start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb, PRIMARY KEY (session_id) )
CREATE TABLE gaming_technology.servers ( server_id uuid PRIMARY KEY, game_id uuid, server_name text, region text, ip_address text, port int, current_players int, max_players int, status text, last_heartbeat timestamptz )
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid PRIMARY KEY, player_id uuid, achievement_id uuid, unlocked_at timestamptz )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )


[User] For the 'DeFi' narrative, what is the average ROI and the total net inflow (usd_value where type=1) from smart money token inflow?

[Assistant]
SELECT AVG(sm.roi) AS avg_roi, SUM(smt.usd_value) AS total_net_inflow
FROM smart_money_token_inflow smt
JOIN smart_money_profit sm ON smt.chain = sm.chain
WHERE smt.narrative = 'DeFi' AND smt.type = 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE narrative_info ( narrative text, top_3_coins text, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, market_cap numeric, volume_24h numeric, trend_rank numeric, token_num numeric )
CREATE TABLE cex_token_balance ( snapshot_time text, chain text, address text, exchange text, token_address text, token_symbol text, balance numeric, usd_value numeric, price numeric )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
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] List all rooms that have a 'Jacuzzi' feature, including the room_number, property_id, type_name, and base_rate.

[Assistant]
SELECT r.room_number,
       r.property_id,
       rt.type_name,
       rt.base_rate
FROM hospitality_technology.rooms AS r
JOIN hospitality_technology.room_types AS rt
  ON r.room_type_id = rt.room_type_id
 AND r.property_id = rt.property_id
WHERE r.features ILIKE '%Jacuzzi%';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )


[User] For each patient, show the total number of diagnoses they have received, along with their patient ID and the ID of their latest diagnosis. Join with the diagnoses table.

[Assistant]
SELECT patient_id, COUNT(diagnosis_id) AS diagnosis_count, MAX(diagnosis_id) AS latest_diagnosis_id
FROM healthcare.diagnoses
GROUP BY patient_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 healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] How many games are available in each genre? List genre and game_count.

[Assistant]
SELECT genre, COUNT(*) AS game_count
FROM gaming_technology.games
GROUP BY genre;

[User] Now only include genres with at least 5 games.

[Assistant]
SELECT genre, COUNT(*) AS game_count
FROM gaming_technology.games
GROUP BY genre
HAVING COUNT(*) >= 5;

[User] Also show the earliest release_date for each of these genres.

[Assistant]
SELECT genre, COUNT(*) AS game_count, MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY genre
HAVING COUNT(*) >= 5;

[User] Sort by game_count descending and limit to top 3.

[Assistant]
SELECT genre, COUNT(*) AS game_count, MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY genre
HAVING COUNT(*) >= 5
ORDER BY game_count 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 gaming_technology.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )


[User] Show me all reservations with their guest IDs and room IDs where the total amount is greater than $500 and the status is 'Confirmed', ordered by check-in date.

[Assistant] SELECT reservation_id, guest_id, room_id, check_in_date, total_amount FROM hospitality_technology.reservations WHERE total_amount > 500 AND status = 'Confirmed' ORDER BY check_in_date;

[User] Now, join this with the service_orders table to include the total price of all services ordered for each reservation.

[Assistant] SELECT r.reservation_id, r.guest_id, r.room_id, r.check_in_date, r.total_amount, SUM(so.total_price) AS total_service_price FROM hospitality_technology.reservations r LEFT JOIN hospitality_technology.service_orders so ON r.reservation_id = so.reservation_id WHERE r.total_amount > 500 AND r.status = 'Confirmed' GROUP BY r.reservation_id, r.guest_id, r.room_id, r.check_in_date, r.total_amount ORDER BY r.check_in_date;

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.text, property_id.text, guest_id.text, room_id.text, room_type_id.text, check_in_date.date, check_out_date.date, actual_check_in_ts.timestamp, actual_check_out_ts.timestamp, num_adults.integer, num_children.integer, status.text, booking_source.text, rate_plan_id.text, total_amount.numeric, amount_paid.numeric, special_requests.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] 特定の職種の従業員情報を取得したいです。従業員ID、名前、職種、雇用日を表示してください。

[Assistant]
db.employees.find(
    { job_title: '<specific_job_title>' },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用日が2020年1月1日以降の従業員だけに絞り込むことはできますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') }
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用ステータスが「Active」の従業員だけをさらに条件に加えられますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] スキル認定情報も結果に含めてください。

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, skill_certifications: 1, _id: 0 }
).sort({ hire_date: -1 })

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Collection 'assembly_steps'. Document structure: { _id: <ObjectId (or step_id)>, step_id: String, line_id: String (reference), step_number: NumberInt, step_name: String, description: String, standard_duration_hours: Decimal128, required_skill_level: String, workstation: String }. Required: step_id, line_id, step_number, step_name. Index on line_id, step_number.
Collection 'employees'. Document structure: { _id: <ObjectId (or employee_id)>, employee_id: String, first_name: String, last_name: String, job_title: String, skill_certifications: [String], hire_date: ISODate, assigned_line_id: String (reference, optional), employment_status: String, supervisor_employee_id: String (reference, optional) }. Required: employee_id, first_name, last_name, job_title, hire_date, employment_status.


[User] List the first name, last name, license number, and status for all drivers whose license expires in the next 6 months.

[Assistant]
SELECT
  first_name,
  last_name,
  license_number,
  status
FROM transportation.drivers
WHERE
  license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '6 month'
ORDER BY
  license_expiry_date;

[User] Now, count how many drivers from that list have an 'Active' status.

[Assistant]
SELECT
  COUNT(*)
FROM transportation.drivers
WHERE
  license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '6 month' AND status = 'Active';

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 )


[User] How many trips are there for each driver?

[Assistant] SELECT driver_id, COUNT(*) AS trip_count FROM transportation.trips GROUP BY driver_id;

[User] Can you also show the total number of completed trips for each driver?

[Assistant] SELECT driver_id, COUNT(*) AS completed_trip_count FROM transportation.trips WHERE status = 'Completed' GROUP BY driver_id;

[User] Now, include both the total trips and completed trips for each driver in the same result.

[Assistant] SELECT driver_id, COUNT(*) AS total_trips, SUM(CASE WHEN status = 'Completed' THEN 1 ELSE 0 END) AS completed_trips FROM transportation.trips GROUP BY driver_id;

[User] Sort the output by the number of completed trips in descending order.

[Assistant] SELECT driver_id, COUNT(*) AS total_trips, SUM(CASE WHEN status = 'Completed' THEN 1 ELSE 0 END) AS completed_trips FROM transportation.trips GROUP BY driver_id ORDER BY completed_trips DESC;

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


[User] What is the detailed repair history for train number T5678?

[Assistant] I'm sorry, but I can't provide the detailed repair history for train number T5678 as this information is not available in the current database table. The table only includes basic information such as train ID, model, manufacturer, capacity, status, and maintenance dates. For repair history, you may need to consult a different database or department.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.trains ( train_id text, train_number text, model text, manufacturer text, year_manufactured integer, capacity integer, status text, last_maintenance_date date, next_maintenance_date date )


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

[Assistant]
SELECT t1.transaction_id AS tx1,
       t2.transaction_id AS tx2,
       t1.to_address,
       t1.block_number
FROM transactions t1
JOIN transactions t2
  ON t1.to_address = t2.to_address
 AND t1.block_number = t2.block_number
 AND t1.transaction_id < t2.transaction_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )


[User] What is the total USD value held by all centralized exchanges (CEX) for the token with the symbol 'BTC'?

[Assistant] SELECT SUM(usd_value) AS total_btc_cex_value FROM cex_token_balance WHERE token_symbol = 'BTC';

[User] Can you break down the total USD value for 'BTC' held by CEXes by chain?

[Assistant] SELECT chain, SUM(usd_value) AS total_btc_cex_value FROM cex_token_balance WHERE token_symbol = 'BTC' GROUP BY chain ORDER BY total_btc_cex_value 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 project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE token_dexpool_info ( pair_address.text, token_name.text, token_symbol.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_6h.numeric, price_change_percentage_24h.numeric, makers_24h.numeric, volume_24h.numeric, liquidity.numeric, market_cap.numeric, trend_rank.numeric )
CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp chain character varying(128) NOT NULL, -- the chain that the token resides address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX exchange character varying(512) NOT NULL, -- a centralized exchange name token_address character varying(128) NOT NULL, -- token contract address token_symbol character varying(512), --token symbol balance numeric(38,10), -- token balance usd_value numeric(38,14), -- value of the token held in USD price double precision, --price of the token in USD ,PRIMARY KEY (snapshot_time, exchange, address, chain, token_address) )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
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 )
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] List the top 5 largest PDF documents in claim_documents, showing document_id, claim_id, file_name, and file_size_bytes.

[Assistant]
SELECT document_id,
       claim_id,
       file_name,
       file_size_bytes
FROM insurance.claim_documents
WHERE document_type = 'pdf'
ORDER BY file_size_bytes 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 insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )


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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.routes (
    route_id character varying(64) NOT NULL,  -- unique identifier for the route
    route_number character varying(32) NOT NULL UNIQUE, -- public-facing route number/name
    description text, -- description of the route
    origin_location_id character varying(64) NOT NULL, -- identifier of the starting location
    destination_location_id character varying(64) NOT NULL, -- identifier of the ending location
    distance_km numeric(10, 2), -- estimated distance in kilometers
    estimated_duration_minutes integer, -- estimated travel time in minutes
    type character varying(32) NOT NULL, -- e.g., City Bus, Intercity Train, Cargo Delivery
    PRIMARY KEY (route_id)
)
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )
CREATE TABLE transportation.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )


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

[Assistant] SELECT first_name, last_name, date_of_birth FROM healthcare.patients WHERE phone_number IS NULL OR TRIM(phone_number) = '';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )


[User] What is the average daily trading volume for each security_id in the market_data table from the last 30 days?

[Assistant] SELECT security_id, AVG(volume) as avg_daily_volume FROM financial_services.market_data WHERE data_timestamp >= CURRENT_DATE - INTERVAL '30 days' GROUP BY security_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 financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.trades ( trade_id text, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees ( employee_id text, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )