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
CREATE TABLE erc1155_approval_for_all ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text )
CREATE TABLE erc20_balances_historical ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_coins ( object_id.text, status.text, coin_type.text, balance.text, owner.text )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_metadata ( blockchain.text, contract_address.text, token_id.text, contract_name.text, erc_type.text, amount.bigint, minter.text, owner.text, mint_block_number.bigint, mint_time.bigint, mint_transaction_hash.text, mint_price.text, token_uri.text, metadata.text, name.text, image_uri.text, traits.text, updated_at.bigint, status.text, rarity_score.real, rarity_rank.integer, unique_attribute_count.integer, pk.integer )
CREATE TABLE 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, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_balances_bitcoin ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.text, amount.text )
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_activities_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_avalanche ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )

[User] Which wallets currently hold more than 100 units of any ERC1155 NFT on Ethereum? Please show contract address, token id, wallet address, and amount.

[Assistant]
SELECT contract_address, token_id, wallet_address, CAST(amount AS NUMERIC) AS amount
FROM nft_holders
WHERE contract_type = 'ERC1155' AND CAST(amount AS NUMERIC) > 100;

[User] Also include only those NFTs whose contract address matches a collection on Ethereum in the nft_metadata table.

[Assistant]
SELECT nh.contract_address, nh.token_id, nh.wallet_address, CAST(nh.amount AS NUMERIC) AS amount
FROM nft_holders nh
JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id
WHERE nh.contract_type = 'ERC1155' AND nm.blockchain = 'Ethereum' AND CAST(nh.amount AS NUMERIC) > 100;


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
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )

[User] List all Avalanche tokens where the circulating total supply is less than the maximum supply. Include tick, creator, max_supply, total_supply (sum of amount), and the difference between max_supply and total_supply.

[Assistant]
SELECT bi.tick,
       bi.creator,
       bi.max_supply,
       COALESCE(tb.total_supply, 0) AS total_supply,
       (bi.max_supply - COALESCE(tb.total_supply, 0)) AS supply_diff
FROM token_info_avalanche bi
LEFT JOIN (
  SELECT tick,
         SUM(amount) AS total_supply
  FROM token_balances_avalanche
  GROUP BY tick
) tb ON bi.tick = tb.tick;

[User] Also include the number of holders and number of transactions (holders and txs) for each token.

[Assistant]
SELECT bi.tick,
       bi.creator,
       bi.max_supply,
       COALESCE(tb.total_supply, 0) AS total_supply,
       (bi.max_supply - COALESCE(tb.total_supply, 0)) AS supply_diff,
       bi.holders,
       bi.txs
FROM token_info_avalanche bi
LEFT JOIN (
  SELECT tick,
         SUM(amount) AS total_supply
  FROM token_balances_avalanche
  GROUP BY tick
) tb ON bi.tick = tb.tick;

[User] Now restrict to tokens where the supply difference is greater than 1000 and only include records where the info block_number is above 500000.

[Assistant]
SELECT bi.tick,
       bi.creator,
       bi.max_supply,
       COALESCE(tb.total_supply, 0) AS total_supply,
       (bi.max_supply - COALESCE(tb.total_supply, 0)) AS supply_diff,
       bi.holders,
       bi.txs
FROM token_info_avalanche bi
LEFT JOIN (
  SELECT tick,
         SUM(amount) AS total_supply
  FROM token_balances_avalanche
  GROUP BY tick
) tb ON bi.tick = tb.tick
WHERE (bi.max_supply - COALESCE(tb.total_supply, 0)) > 1000
  AND bi.block_number > 500000;

[User] Finally, sort the results by supply_diff descending and limit to the top 5 tokens.

[Assistant]
SELECT bi.tick,
       bi.creator,
       bi.max_supply,
       COALESCE(tb.total_supply, 0) AS total_supply,
       (bi.max_supply - COALESCE(tb.total_supply, 0)) AS supply_diff,
       bi.holders,
       bi.txs
FROM token_info_avalanche bi
LEFT JOIN (
  SELECT tick,
         SUM(amount) AS total_supply
  FROM token_balances_avalanche
  GROUP BY tick
) tb ON bi.tick = tb.tick
WHERE (bi.max_supply - COALESCE(tb.total_supply, 0)) > 1000
  AND bi.block_number > 500000
ORDER BY supply_diff DESC
LIMIT 5;


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
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, 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 int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.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 PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] List staff members who responded to public reviews with an overall rating of 3 or less. Include the staff member's first name, last name, and the review ID.

[Assistant] SELECT T1.first_name, T1.last_name, T2.review_id FROM staff AS T1 JOIN reviews AS T2 ON T1.staff_id = T2.response_staff_id WHERE T2.is_public = TRUE AND T2.rating_overall <= 3;

[User] Also, only show reviews where the cleanliness rating was 3 or less.

[Assistant] SELECT T1.first_name, T1.last_name, T2.review_id FROM staff AS T1 JOIN reviews AS T2 ON T1.staff_id = T2.response_staff_id WHERE T2.is_public = TRUE AND T2.rating_overall <= 3 AND T2.rating_cleanliness <= 3;

[User] Instead of listing each review, show the count of such reviews for each staff member.

[Assistant] SELECT T1.first_name, T1.last_name, COUNT(T2.review_id) AS review_count FROM staff AS T1 JOIN reviews AS T2 ON T1.staff_id = T2.response_staff_id WHERE T2.is_public = TRUE AND T2.rating_overall <= 3 AND T2.rating_cleanliness <= 3 GROUP BY T1.staff_id, T1.first_name, T1.last_name;


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

[User] Find tokens on the 'Polygon' chain with a market cap greater than $1,000,000,000 and a positive price change in the last 24 hours. List their symbol, name, market cap, and 24h price change.

[Assistant] SELECT token_symbol, token_name, market_cap, price_change_percentage_24h FROM token_basic_info WHERE chain = 'Polygon' AND market_cap > 1000000000 AND price_change_percentage_24h > 0;

[User] Also include their current price and 7-day price change percentage. Order the results by market cap descending.

[Assistant] SELECT token_symbol, token_name, market_cap, price_change_percentage_24h, price, price_change_percentage_7d FROM token_basic_info WHERE chain = 'Polygon' AND market_cap > 1000000000 AND price_change_percentage_24h > 0 ORDER BY market_cap DESC;


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
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.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )

[User] How many available services are there per department for each property? Include property_id, department, and the service count.

[Assistant]
SELECT
  property_id,
  department,
  COUNT(*) AS available_services_count
FROM hospitality_technology.services
WHERE is_available = TRUE
GROUP BY property_id, department;

[User] Also include the average price of these available services per department.

[Assistant]
SELECT
  property_id,
  department,
  COUNT(*) AS available_services_count,
  AVG(price) AS avg_service_price
FROM hospitality_technology.services
WHERE is_available = TRUE
GROUP BY property_id, department;


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
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )

[User] I need a report showing the count of drivers per status.

[Assistant]
SELECT status, COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status;

[User] Actually, only include statuses that have at least 2 drivers.

[Assistant]
SELECT status, COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) >= 2;

[User] Also, order the results by driver_count descending.

[Assistant]
SELECT status, COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) >= 2
ORDER BY driver_count DESC;

[User] Limit to the top 3 statuses.

[Assistant]
SELECT status, COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) >= 2
ORDER BY driver_count DESC
LIMIT 3;


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
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )

[User] List all services with an average processing time greater than the overall average processing time for all services. Show the service name, average processing time, and the overall average processing time.

[Assistant] SELECT service_name, average_processing_time_days, (SELECT AVG(average_processing_time_days) FROM government_services.services WHERE average_processing_time_days IS NOT NULL) as overall_avg_processing_time FROM government_services.services WHERE average_processing_time_days IS NOT NULL AND average_processing_time_days > (SELECT AVG(average_processing_time_days) FROM government_services.services WHERE average_processing_time_days IS NOT NULL);


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
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 )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )

[User] List all invoices with a total_amount less than 1000 and show the associated client's ID and case ID.

[Assistant]
SELECT invoice_id, client_id, case_id, total_amount
FROM legal_services.invoices
WHERE total_amount < 1000;

[User] Actually, can you also include the invoice status and order the results by total_amount ascending?

[Assistant]
SELECT invoice_id, client_id, case_id, total_amount, status
FROM legal_services.invoices
WHERE total_amount < 1000
ORDER BY total_amount ASC;

[User] Now, only show invoices where the status is 'Sent' or 'Overdue', and include the issue_date as well.

[Assistant]
SELECT invoice_id, client_id, case_id, total_amount, status, issue_date
FROM legal_services.invoices
WHERE total_amount < 1000 AND status IN ('Sent', 'Overdue')
ORDER BY total_amount ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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 )

[User] How many unique customers are there in the system?

[Assistant]
SELECT COUNT(DISTINCT customer_id) AS unique_customer_count
FROM insurance.customers;


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
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.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.notifications (
    notification_id character varying(64) NOT NULL,  -- unique identifier for the notification
    user_id character varying(64) NOT NULL, -- identifier of the user receiving the notification
    message text NOT NULL, -- message of the notification
    sent_at timestamp NOT NULL, -- time when the notification was sent
    read_at timestamp, -- time when the notification was read
    PRIMARY KEY (notification_id)
)

[User] Find the username, email, and total number of orders placed by each user.

[Assistant]
SELECT u.username, u.email, COUNT(o.order_id) AS order_count
FROM trading_platform.users u
LEFT JOIN trading_platform.wallets w ON u.user_id = w.user_id
LEFT JOIN trading_platform.orders o ON w.wallet_id = o.wallet_id
GROUP BY u.user_id, u.username, u.email;

[User] The query failed because there is no orders table. I want instead the username, email, and total number of trades each user has been involved in, either as a buyer or a seller.

[Assistant]
SELECT u.username, u.email, COUNT(t.trade_id) AS trade_count
FROM trading_platform.users u
LEFT JOIN trading_platform.trades t ON u.user_id = t.buyer_id OR u.user_id = t.seller_id
GROUP BY u.user_id, u.username, u.email;

[User] Please only show users who have participated in more than 2 trades.

[Assistant]
SELECT u.username, u.email, COUNT(t.trade_id) AS trade_count
FROM trading_platform.users u
LEFT JOIN trading_platform.trades t ON u.user_id = t.buyer_id OR u.user_id = t.seller_id
GROUP BY u.user_id, u.username, u.email
HAVING COUNT(t.trade_id) > 2;

[User] Also, show the total trade quantity that each user has bought (as buyer) and the quantity they have sold (as seller).

[Assistant]
SELECT u.username, u.email,
       COUNT(t.trade_id) AS trade_count,
       COALESCE(SUM(CASE WHEN t.buyer_id = u.user_id THEN t.quantity END), 0) AS total_bought,
       COALESCE(SUM(CASE WHEN t.seller_id = u.user_id THEN t.quantity END), 0) AS total_sold
FROM trading_platform.users u
LEFT JOIN trading_platform.trades t ON u.user_id = t.buyer_id OR u.user_id = t.seller_id
GROUP BY u.user_id, u.username, u.email
HAVING COUNT(t.trade_id) > 2;


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

[User] For each year since 2015, show the total number of games released per year.

[Assistant]
SELECT EXTRACT(YEAR FROM release_date) AS year, COUNT(*) AS total_games
FROM gaming_technology.games
WHERE release_date >= '2015-01-01'
GROUP BY year
ORDER BY year ASC;

[User] Include the number of distinct developers who released games each year.

[Assistant]
SELECT EXTRACT(YEAR FROM release_date) AS year, COUNT(*) AS total_games, COUNT(DISTINCT developer_id) AS developer_count
FROM gaming_technology.games
WHERE release_date >= '2015-01-01'
GROUP BY year
ORDER BY year ASC;

[User] Now only show years where more than 20 games were released.

[Assistant]
SELECT EXTRACT(YEAR FROM release_date) AS year, COUNT(*) AS total_games, COUNT(DISTINCT developer_id) AS developer_count
FROM gaming_technology.games
WHERE release_date >= '2015-01-01'
GROUP BY year
HAVING COUNT(*) > 20
ORDER BY year ASC;

[User] Please also add the average number of games released per developer for each year.

[Assistant]
SELECT EXTRACT(YEAR FROM release_date) AS year, COUNT(*) AS total_games, COUNT(DISTINCT developer_id) AS developer_count, ROUND(COUNT(*)::numeric / NULLIF(COUNT(DISTINCT developer_id), 0), 2) AS avg_games_per_developer
FROM gaming_technology.games
WHERE release_date >= '2015-01-01'
GROUP BY year
HAVING COUNT(*) > 20
ORDER BY year ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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) )

[User] For each passenger, show their passenger_id, first_name, last_name, and the count of other passengers in the same loyalty_program_id.

[Assistant]
SELECT p1.passenger_id, p1.first_name, p1.last_name, COUNT(p2.passenger_id) AS peer_count
FROM transportation.passengers p1
LEFT JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
GROUP BY p1.passenger_id, p1.first_name, p1.last_name;

[User] Only include passengers who have more than 3 peers in their loyalty program.

[Assistant]
SELECT p1.passenger_id, p1.first_name, p1.last_name, COUNT(p2.passenger_id) AS peer_count
FROM transportation.passengers p1
LEFT JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
GROUP BY p1.passenger_id, p1.first_name, p1.last_name
HAVING COUNT(p2.passenger_id) > 3;

[User] Also include the loyalty_program_id in the results.

[Assistant]
SELECT p1.passenger_id, p1.first_name, p1.last_name, p1.loyalty_program_id, COUNT(p2.passenger_id) AS peer_count
FROM transportation.passengers p1
LEFT JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
GROUP BY p1.passenger_id, p1.first_name, p1.last_name, p1.loyalty_program_id
HAVING COUNT(p2.passenger_id) > 3;


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
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )

[User] Find token transfers within the same transaction where the recipient of an earlier transfer (based on log_index) becomes the sender of a later transfer. List the transaction ID, the earlier transfer ID, the later transfer ID, the shared address, and the value transferred in both cases.

[Assistant] SELECT t1.transaction_id, t1.transfer_id AS earlier_transfer_id, t2.transfer_id AS later_transfer_id, t1.to_address AS shared_address, t1.value AS earlier_transfer_value, t2.value AS later_transfer_value FROM web3.token_transfers AS t1 JOIN web3.token_transfers AS t2 ON t1.transaction_id = t2.transaction_id WHERE t1.to_address = t2.from_address AND t1.log_index < t2.log_index;


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
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )

[User] Find pairs of active services from the same agency where one service's average processing time is longer than the other's. Display the agency_id, the slower service name with its processing time, and the faster service name with its processing time.

[Assistant]
SELECT
  s1.agency_id,
  s1.service_name AS slower_service_name,
  s1.average_processing_time_days AS slower_time,
  s2.service_name AS faster_service_name,
  s2.average_processing_time_days AS faster_time
FROM
  government_services.services s1
JOIN
  government_services.services s2
  ON s1.agency_id = s2.agency_id
  AND s1.average_processing_time_days > s2.average_processing_time_days
WHERE
  s1.is_active = true
  AND s2.is_active = true;


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
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )

[User] I need a list of all routes and the number of trips made on each route.

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

[User] Actually, show the route_number and description instead of route_id.

[Assistant]
SELECT r.route_number,
       r.description,
       COUNT(t.trip_id) AS trip_count
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
GROUP BY r.route_number, r.description;

[User] Also, only include routes with more than 20 trips and sort by trip_count descending.

[Assistant]
SELECT r.route_number,
       r.description,
       COUNT(t.trip_id) AS trip_count
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
GROUP BY r.route_number, r.description
HAVING COUNT(t.trip_id) > 20
ORDER BY trip_count DESC;

[User] Finally, display the average passenger count per trip for each of these routes.

[Assistant]
SELECT r.route_number,
       r.description,
       COUNT(t.trip_id) AS trip_count,
       AVG(t.passenger_count) AS avg_passengers
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
GROUP BY r.route_number, r.description
HAVING COUNT(t.trip_id) > 20
ORDER BY trip_count DESC;


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
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )

[User] List the first name and last name of citizens who have scheduled appointments, along with the scheduled start time and purpose of their appointments.

[Assistant] SELECT T1.first_name, T1.last_name, T2.scheduled_start_time, T2.purpose FROM government_services.citizens AS T1 JOIN government_services.appointments AS T2 ON T1.citizen_id = T2.citizen_id;


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
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
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.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] Which achievements have the highest unlock counts? List the top 5 achievement names along with the number of distinct players who unlocked each.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name
ORDER BY player_count DESC
LIMIT 5;

[User] Only exclude hidden achievements from the ranking.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
WHERE a.hidden = FALSE
GROUP BY a.name
ORDER BY player_count DESC
LIMIT 5;

[User] Now include only achievements unlocked by at least 50 players and order by player_count descending.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
WHERE a.hidden = FALSE
GROUP BY a.name
HAVING COUNT(DISTINCT pa.player_id) >= 50
ORDER BY player_count DESC;


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

[User] For each narrative, what is the average smart money ROI and the total 24-hour trading volume of the narrative?

[Assistant] SELECT T3.narrative, T4.avg_roi, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative

[User] Only include narratives that have more than 20 tokens and a total 24h trading volume above $1,000,000.

[Assistant] SELECT T3.narrative, T4.avg_roi, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative WHERE T3.token_num > 20 AND T3.volume_24h > 1000000

[User] Also show the average net flow for smart money performance within each of these narratives.

[Assistant] SELECT T3.narrative, T4.avg_roi, T4.avg_net_flow, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi, AVG(T1.net_flow) as avg_net_flow FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative WHERE T3.token_num > 20 AND T3.volume_24h > 1000000

[User] Order the results by average ROI descending and show the top 5.

[Assistant] SELECT T3.narrative, T4.avg_roi, T4.avg_net_flow, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi, AVG(T1.net_flow) as avg_net_flow FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative WHERE T3.token_num > 20 AND T3.volume_24h > 1000000 ORDER BY T4.avg_roi DESC LIMIT 5


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
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.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, 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.medications ( medication_id text PRIMARY KEY, 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 )

[User] List the license number and specialty for all doctors who have a phone number on record.

[Assistant] SELECT license_number, specialty FROM healthcare.doctors WHERE phone_number IS NOT NULL;


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
CREATE TABLE social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.comments ( comment_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, parent_comment_id character varying(64), content text NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (comment_id) )
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )

[User] Show me the usernames and the count of comments they made on posts associated with the hashtag 'community'.

[Assistant]
SELECT u.username, COUNT(c.comment_id) AS comment_count
FROM social_media.users u
JOIN social_media.comments c ON u.user_id = c.user_id
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'community'
GROUP BY u.username;

[User] Only include users who have made more than 3 comments on such posts.

[Assistant]
SELECT u.username, COUNT(c.comment_id) AS comment_count
FROM social_media.users u
JOIN social_media.comments c ON u.user_id = c.user_id
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'community'
GROUP BY u.username
HAVING COUNT(c.comment_id) > 3;

[User] Also, show the user's full name and sort the result by comment_count descending.

[Assistant]
SELECT u.username, u.full_name, COUNT(c.comment_id) AS comment_count
FROM social_media.users u
JOIN social_media.comments c ON u.user_id = c.user_id
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'community'
GROUP BY u.username, u.full_name
HAVING COUNT(c.comment_id) > 3
ORDER BY comment_count DESC;

[User] Show only the top 10 users by comment_count.

[Assistant]
SELECT u.username, u.full_name, COUNT(c.comment_id) AS comment_count
FROM social_media.users u
JOIN social_media.comments c ON u.user_id = c.user_id
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'community'
GROUP BY u.username, u.full_name
HAVING COUNT(c.comment_id) > 3
ORDER BY comment_count DESC
LIMIT 10;


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
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE 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_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )

[User] List all NFT holdings from the `nft_holders` table where the `contract_type` is 'ERC721'. Show the wallet address, contract address, token ID, and amount held.

[Assistant] SELECT wallet_address, contract_address, token_id, CAST(amount AS DECIMAL) as amount FROM nft_holders WHERE contract_type = 'ERC721';

[User] For these ERC721 holdings, join with the `nft_metadata` table to get the `name` and `rarity_score` for each NFT. Only include NFTs where the rarity score is greater than 70.

[Assistant] SELECT nh.wallet_address, nh.contract_address, nh.token_id, nh.amount, nm.name, nm.rarity_score FROM nft_holders nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_type = 'ERC721' AND nm.rarity_score > 70;

[User] Now, group these results by the NFT collection, joining with `nft_collections` for Ethereum collections. Show the collection name, the average rarity score for NFTs in that collection (filtered above), and the total number of unique holders across all NFTs in that collection (from the initial filter). Only show collections with more than 50 unique holders, order by average rarity score descending, and limit to the top 10.

[Assistant] SELECT nc.name AS collection_name, AVG(nm.rarity_score) AS average_rarity_score, COUNT(DISTINCT nh.wallet_address) AS unique_holder_count FROM nft_holders nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id JOIN nft_collections nc ON nh.contract_address = nc.contract_address WHERE nh.contract_type = 'ERC721' AND nm.rarity_score > 70 AND nc.blockchain = 'Ethereum' GROUP BY nc.name HAVING COUNT(DISTINCT nh.wallet_address) > 50 ORDER BY average_rarity_score DESC LIMIT 10;


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

[User] List all pairs of wallets with the same creation timestamp but different wallet addresses, including both wallet_ids and the creation timestamp.

[Assistant]
SELECT w1.wallet_id AS wallet_id_1, w2.wallet_id AS wallet_id_2, w1.created_at
FROM web3.wallets w1
JOIN web3.wallets w2
  ON w1.created_at = w2.created_at
     AND w1.address <> w2.address
     AND w1.wallet_id < w2.wallet_id;


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
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
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 )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )

[User] Find all tokens with their contract addresses and the number of wallets that hold each token, sorted by wallet count in descending order.

[Assistant] SELECT t.token_id, t.contract_address, COUNT(DISTINCT w.wallet_id) AS wallet_count FROM web3.tokens t LEFT JOIN web3.transactions tr ON t.contract_address = tr.to_address OR t.contract_address = tr.from_address JOIN web3.wallets w ON tr.from_address = w.address OR tr.to_address = w.address GROUP BY t.token_id, t.contract_address ORDER BY wallet_count DESC;


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
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )

[User] List the plan ID, name, provider, and type for all insurance plans from 'Healthcare Partners' with a plan type of 'PPO'.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO';

[User] Now, only show those plans that also have a website listed.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO' AND website IS NOT NULL;

[User] Further refine the results to only include plans where the plan name contains the word 'Plus'.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO' AND website IS NOT NULL AND plan_name ILIKE '%Plus%';

[User] Finally, count how many such plans exist.

[Assistant] SELECT COUNT(*) FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO' AND website IS NOT NULL AND plan_name ILIKE '%Plus%';


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
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )

[User] Can you give me the total number of appointments grouped by status?

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

[User] Filter the result to show only statuses with more than 50 appointments.

[Assistant]
SELECT status,
       COUNT(*) AS total_appointments
FROM healthcare.appointments
GROUP BY status
HAVING COUNT(*) > 50;


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
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )

[User] Show the service names that had documents uploaded for their applications in the calendar year 2023.

[Assistant] SELECT DISTINCT T1.service_name FROM government_services.services AS T1 JOIN applications AS T2 ON T1.service_id = T2.service_id JOIN government_services.documents AS T3 ON T2.application_id = T3.application_id WHERE EXTRACT(YEAR FROM T3.upload_timestamp) = 2023

[User] Only include services belonging to the 'Healthcare' category.

[Assistant] SELECT DISTINCT T1.service_name FROM government_services.services AS T1 JOIN applications AS T2 ON T1.service_id = T2.service_id JOIN government_services.documents AS T3 ON T2.application_id = T3.application_id WHERE EXTRACT(YEAR FROM T3.upload_timestamp) = 2023 AND T1.category = 'Healthcare'


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
CREATE TABLE social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )

[User] List the usernames and email addresses of users who have participated in any conversation.

[Assistant] SELECT DISTINCT T1.username, T1.email FROM social_media.users AS T1 JOIN social_media.conversation_participants AS T2 ON T1.user_id = T2.user_id;

[User] Can you also include the time they joined their first conversation?

[Assistant] SELECT T1.username, T1.email, MIN(T2.joined_at) AS first_joined_at FROM social_media.users AS T1 JOIN social_media.conversation_participants AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username, T1.email;

[User] Only show users whose email ends with '.com' and joined after '2024-01-15'.

[Assistant] SELECT T1.username, T1.email, MIN(T2.joined_at) AS first_joined_at FROM social_media.users AS T1 JOIN social_media.conversation_participants AS T2 ON T1.user_id = T2.user_id WHERE T1.email LIKE '%.com' GROUP BY T1.user_id, T1.username, T1.email HAVING MIN(T2.joined_at) > '2024-01-15';


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
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
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 )

[User] Show for each player the total score achieved in sessions on each server, and the number of sessions per server.

[Assistant]
SELECT player_id, server_id, SUM(score) AS total_score, COUNT(*) AS session_count
FROM gaming_technology.game_sessions
GROUP BY player_id, server_id;

[User] Now also include the maximum duration of any session that player has had on that server.

[Assistant]
SELECT player_id, server_id, SUM(score) AS total_score, COUNT(*) AS session_count, MAX(duration_seconds) AS max_session_duration
FROM gaming_technology.game_sessions
GROUP BY player_id, server_id;

[User] For each player-server pair, include the average session duration as well.

[Assistant]
SELECT player_id, server_id, SUM(score) AS total_score, COUNT(*) AS session_count, MAX(duration_seconds) AS max_session_duration, AVG(duration_seconds) AS avg_session_duration
FROM gaming_technology.game_sessions
GROUP BY player_id, server_id;

[User] Finally, only include player-server pairs where the session_count is at least 5.

[Assistant]
SELECT player_id, server_id, SUM(score) AS total_score, COUNT(*) AS session_count, MAX(duration_seconds) AS max_session_duration, AVG(duration_seconds) AS avg_session_duration
FROM gaming_technology.game_sessions
GROUP BY player_id, server_id
HAVING COUNT(*) >= 5;


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
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] Can you show me the count of new doctors added each month in 2023? Return the month and number of doctors.

[Assistant]
SELECT DATE_TRUNC('month', created_at) AS month, COUNT(*) AS doctor_count
FROM healthcare.doctors
WHERE created_at >= '2023-01-01' AND created_at < '2024-01-01'
GROUP BY DATE_TRUNC('month', created_at);

[User] Actually, include the month as the first day of the month and order the results by month in descending order.

[Assistant]
SELECT DATE_TRUNC('month', created_at)::date AS month_start, COUNT(*) AS doctor_count
FROM healthcare.doctors
WHERE created_at >= '2023-01-01' AND created_at < '2024-01-01'
GROUP BY DATE_TRUNC('month', created_at)
ORDER BY month_start DESC;


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
CREATE TABLE hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.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.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.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
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 )

[User] For each property, list the property name, the number of room types it offers, and the average area in square feet.

[Assistant]
SELECT p.property_name,
       COUNT(rt.room_type_id) AS room_type_count,
       ROUND(AVG(rt.area_sqft), 2) AS avg_area_sqft
FROM hospitality_technology.properties p
JOIN hospitality_technology.room_types rt
  ON p.property_id = rt.property_id
GROUP BY p.property_name;

[User] Now show only properties where the average area is greater than 500 square feet and sort by average area descending.

[Assistant]
SELECT p.property_name,
       COUNT(rt.room_type_id) AS room_type_count,
       ROUND(AVG(rt.area_sqft), 2) AS avg_area_sqft
FROM hospitality_technology.properties p
JOIN hospitality_technology.room_types rt
  ON p.property_id = rt.property_id
GROUP BY p.property_name
HAVING AVG(rt.area_sqft) > 500
ORDER BY avg_area_sqft DESC;


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
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )

[User] List token symbols on any chain that have both a realized ratio above 0.8 and an ROI greater than 5. Show their symbol, chain, realized ratio, and ROI.

[Assistant] SELECT token_symbol, chain, realized_ratio, roi FROM smart_money_token_performance WHERE realized_ratio > 0.8 AND roi > 5

[User] Can you also include their PNL and Net Flow in the result?

[Assistant] SELECT token_symbol, chain, realized_ratio, roi, pnl, net_flow FROM smart_money_token_performance WHERE realized_ratio > 0.8 AND roi > 5


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
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] What is the total amount paid by each customer? Show the customer_id and the sum of amount_paid.

[Assistant] SELECT customer_id, SUM(amount_paid) FROM insurance.premium_payments GROUP BY customer_id;

[User] Could you refine that to only include payments made in the year 2023?

[Assistant] SELECT customer_id, SUM(amount_paid) FROM insurance.premium_payments WHERE EXTRACT(YEAR FROM payment_date) = 2023 GROUP BY customer_id;

[User] Now, only show the customers whose total amount paid in 2023 was greater than 5000.

[Assistant] SELECT customer_id, SUM(amount_paid) FROM insurance.premium_payments WHERE EXTRACT(YEAR FROM payment_date) = 2023 GROUP BY customer_id HAVING SUM(amount_paid) > 5000;


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
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )

[User] What is the count of trips for each status?

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

[User] Only include statuses with more than 5 trips.

[Assistant]
SELECT
  status,
  COUNT(*) AS trip_count
FROM transportation.trips
GROUP BY
  status
HAVING
  COUNT(*) > 5;


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

[User] I need a list of genres and pairs of game titles in the same genre.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre;

[User] Please avoid duplicate pairs by ensuring each pair appears only once.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
WHERE g1.title < g2.title;

[User] Only include genres that have at least three games.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
WHERE g1.title < g2.title
  AND g1.genre IN (
    SELECT genre
    FROM gaming_technology.games
    GROUP BY genre
    HAVING COUNT(*) >= 3
  );

[User] Also sort the output by genre ascending and game1 ascending.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
WHERE g1.title < g2.title
  AND g1.genre IN (
    SELECT genre
    FROM gaming_technology.games
    GROUP BY genre
    HAVING COUNT(*) >= 3
  )
ORDER BY g1.genre ASC, g1.title ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )

[User] List all pairs of insurance products that share the same product_type but have differing active statuses. Return both product_ids, the product_type, and each is_active flag.

[Assistant]
SELECT p1.product_id AS product_id_1, p2.product_id AS product_id_2, p1.product_type, p1.is_active AS is_active_1, p2.is_active AS is_active_2
FROM insurance.insurance_products p1
JOIN insurance.insurance_products p2
  ON p1.product_type = p2.product_type
  AND p1.is_active <> p2.is_active
WHERE p1.product_id < p2.product_id;


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
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )

[User] List policy pairs for the same customer where one policy was cancelled and another active policy started within 30 days after the cancellation. Show customer_id, cancelled policy_number, cancellation_date, active policy_number, start_date.

[Assistant]
SELECT p1.customer_id,
       p1.policy_number AS cancelled_policy_number,
       p1.cancellation_date,
       p2.policy_number AS active_policy_number,
       p2.start_date
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.status = 'cancelled'
 AND p2.status = 'active'
 AND p2.start_date BETWEEN p1.cancellation_date AND p1.cancellation_date + INTERVAL '30 days';

[User] Also include the number of days between cancellation and new policy start as days_to_new.

[Assistant]
SELECT p1.customer_id,
       p1.policy_number AS cancelled_policy_number,
       p1.cancellation_date,
       p2.policy_number AS active_policy_number,
       p2.start_date,
       EXTRACT(DAY FROM (p2.start_date - p1.cancellation_date)) AS days_to_new
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.status = 'cancelled'
 AND p2.status = 'active'
 AND p2.start_date BETWEEN p1.cancellation_date AND p1.cancellation_date + INTERVAL '30 days';


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
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 text, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.addresses ( address_id text, public_key text, balance numeric )
CREATE TABLE blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )

[User] List the block_id, timestamp, and the total amount of transactions for each block, along with the sender and receiver addresses for each transaction that occurred on April 10th, 2023.

[Assistant]
SELECT b.block_id, b.timestamp, t.sender_address, t.receiver_address, SUM(t.amount) as total_amount_in_block
FROM blockchain.blocks b
JOIN blockchain.transactions t ON b.block_id = t.block_id
WHERE DATE(t.timestamp) = '2023-04-10'
GROUP BY b.block_id, b.timestamp, t.sender_address, t.receiver_address;

[User] Can you also include the balance of both sender and receiver addresses at the time of the transaction?

[Assistant]
SELECT b.block_id, b.timestamp, t.sender_address, sa.balance AS sender_balance, t.receiver_address, ra.balance AS receiver_balance, SUM(t.amount) as total_amount_in_block
FROM blockchain.blocks b
JOIN blockchain.transactions t ON b.block_id = t.block_id
LEFT JOIN blockchain.addresses sa ON t.sender_address = sa.address_id
LEFT JOIN blockchain.addresses ra ON t.receiver_address = ra.address_id
WHERE DATE(t.timestamp) = '2023-04-10'
GROUP BY b.block_id, b.timestamp, t.sender_address, sa.balance, t.receiver_address, ra.balance;

[User] Now only show those transactions where the sender's balance was greater than 5000 at that time.

[Assistant]
SELECT b.block_id, b.timestamp, t.sender_address, sa.balance AS sender_balance, t.receiver_address, ra.balance AS receiver_balance, SUM(t.amount) as total_amount_in_block
FROM blockchain.blocks b
JOIN blockchain.transactions t ON b.block_id = t.block_id
LEFT JOIN blockchain.addresses sa ON t.sender_address = sa.address_id
LEFT JOIN blockchain.addresses ra ON t.receiver_address = ra.address_id
WHERE DATE(t.timestamp) = '2023-04-10' AND sa.balance > 5000
GROUP BY b.block_id, b.timestamp, t.sender_address, sa.balance, t.receiver_address, ra.balance;

[User] Sorry, the sender_address seems incorrect. Use sender_address from transactions table instead of addresses.

[Assistant]
SELECT b.block_id, b.timestamp, t.sender_address, sa.balance AS sender_balance, t.receiver_address, ra.balance AS receiver_balance, SUM(t.amount) as total_amount_in_block
FROM blockchain.blocks b
JOIN blockchain.transactions t ON b.block_id = t.block_id
LEFT JOIN blockchain.addresses sa ON t.sender_address = sa.address_id
LEFT JOIN blockchain.addresses ra ON t.receiver_address = ra.address_id
WHERE DATE(t.timestamp) = '2023-04-10' AND sa.balance > 5000
GROUP BY b.block_id, b.timestamp, t.sender_address, sa.balance, t.receiver_address, ra.balance;


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
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE web3.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)

[User] Find users who have at least one wallet created before their user registration date. List their username and the address of any such wallet.

[Assistant] SELECT u.username, w.address AS wallet_address FROM web3.users AS u JOIN web3.wallets AS w ON u.user_id = w.user_id WHERE w.created_at < u.created_at;


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
CREATE TABLE financial_services.accounts ( account_id text PRIMARY KEY, 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 )

[User] Show me the average interest rate for each account_type.

[Assistant]
SELECT account_type, AVG(interest_rate) AS average_interest_rate
FROM financial_services.accounts
GROUP BY account_type;

[User] Only include account types with at least 5 accounts and order by average_interest_rate ascending.

[Assistant]
SELECT account_type, AVG(interest_rate) AS average_interest_rate, COUNT(*) AS account_count
FROM financial_services.accounts
GROUP BY account_type
HAVING COUNT(*) >= 5
ORDER BY average_interest_rate ASC;

[User] Add the minimum and maximum interest rate for each account_type to the result.

[Assistant]
SELECT account_type, COUNT(*) AS account_count, AVG(interest_rate) AS average_interest_rate,
       MIN(interest_rate) AS min_interest_rate, MAX(interest_rate) AS max_interest_rate
FROM financial_services.accounts
GROUP BY account_type
HAVING COUNT(*) >= 5
ORDER BY average_interest_rate ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.locations (
    location_id character varying(64) NOT NULL,  -- unique identifier for the location
    name character varying(255) NOT NULL, -- name of the location (e.g., Central Station, Depot Alpha, Pier 7)
    type character varying(64) NOT NULL, -- e.g., Station, Stop, Depot, Port, Airport, Customer Address
    address_line1 character varying(255), -- street address
    city character varying(128), -- city name
    state_province character varying(128), -- state or province
    postal_code character varying(32), -- postal code
    country character varying(64) NOT NULL, -- country name
    latitude numeric(9, 6), -- geographic latitude
    longitude numeric(9, 6), -- geographic longitude
    timezone character varying(64), -- IANA timezone name (e.g., America/New_York)
    PRIMARY KEY (location_id)
)
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] I need to find the average maintenance cost per service type.

[Assistant]
SELECT service_type, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY service_type;

[User] Can you filter to only include service types with avg cost greater than 300?

[Assistant]
SELECT service_type, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY service_type
HAVING AVG(cost) > 300;

[User] Also include the number of services for each of those types.

[Assistant]
SELECT service_type, COUNT(*) AS service_count, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY service_type
HAVING AVG(cost) > 300;

[User] Sort the result by avg_cost descending and show only the top 3 service types.

[Assistant]
SELECT service_type, COUNT(*) AS service_count, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY service_type
HAVING AVG(cost) > 300
ORDER BY avg_cost DESC
LIMIT 3;