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

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

[User] Can you join this with the nft_metadata table to include the name and image URI of each token?

[Assistant] SELECT nh.wallet_address, nh.token_id, nh.amount, nm.name, nm.image_uri 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 CAST(nh.amount AS decimal) > 1000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders (
    block_number bigint NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract(with bloom filter)
    token_id varchar NOT NULL, -- NFT token id
    contract_type varchar NOT NULL, -- NFT contract type
    amount varchar NOT NULL, -- Number of held NFTs
    pk varchar NOT NULL  -- The last string partition of the contract.
)
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins_metadata ( object_id.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 varchar, contract_address varchar, name varchar, symbol varchar, deploy_block_number bigint, deploy_block_time bigint, erc_type varchar, owner varchar, traits varchar, description varchar, slug varchar, media_info varchar, image_url varchar, banner_image_url varchar, updated_at bigint, banner varchar, token_count bigint, floor_price varchar, floor_price_symbol varchar, floor_price_contract varchar, pk integer )
CREATE TABLE token_prices ( uuid.text, blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(255) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities_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_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )


[User] For each guest, calculate their total spending on delivered service orders and the total number of those orders.

[Assistant]
SELECT g.guest_id,
       g.first_name || ' ' || g.last_name AS full_name,
       SUM(so.total_price) AS total_spent,
       COUNT(*) AS total_orders
FROM hospitality_technology.guests g
JOIN hospitality_technology.service_orders so
  ON g.guest_id = so.guest_id
WHERE so.status = 'delivered'
GROUP BY g.guest_id, full_name;

[User] I need the breakdown by month for the current year. Show guest ID, month, total spent, and total orders.

[Assistant]
SELECT so.guest_id,
       DATE_TRUNC('month', so.delivery_timestamp) AS month,
       SUM(so.total_price) AS total_spent,
       COUNT(*) AS total_orders
FROM hospitality_technology.service_orders so
WHERE so.status = 'delivered'
  AND so.delivery_timestamp >= '2024-01-01'
  AND so.delivery_timestamp < '2025-01-01'
GROUP BY so.guest_id, month
ORDER BY month;

[User] Also include the guest’s email and only show months where total spent is greater than 500.

[Assistant]
SELECT sub.guest_id,
       g.email,
       sub.month,
       sub.total_spent,
       sub.total_orders
FROM (
  SELECT so.guest_id,
         DATE_TRUNC('month', so.delivery_timestamp) AS month,
         SUM(so.total_price) AS total_spent,
         COUNT(*) AS total_orders
  FROM hospitality_technology.service_orders so
  WHERE so.status = 'delivered'
    AND so.delivery_timestamp >= '2024-01-01'
    AND so.delivery_timestamp < '2025-01-01'
  GROUP BY so.guest_id, month
) sub
JOIN hospitality_technology.guests g
  ON sub.guest_id = g.guest_id
WHERE sub.total_spent > 500
ORDER BY sub.month;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] For all NFT collections on the Ethereum blockchain, show me the collection name and the current floor price. Sort by floor price descending.

[Assistant] SELECT name, floor_price FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Include also the collection symbol and the number of tokens in each collection.

[Assistant] SELECT name, symbol, floor_price, token_count FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Can you also show the owner of each collection in the result?

[Assistant] SELECT name, symbol, floor_price, token_count, owner FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Now only include collections whose floor price is greater than 1 ETH.

[Assistant] SELECT name, symbol, floor_price, token_count, owner FROM nft_collections WHERE blockchain = 'Ethereum' AND CAST(floor_price AS FLOAT) > 1 AND floor_price_symbol = 'ETH' ORDER BY CAST(floor_price AS FLOAT) DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )


[User] What are the safety ratings or crash statistics for the Boeing 787 Dreamliner?

[Assistant] I'm sorry, but I don't have access to safety ratings or crash statistics for specific aircraft models like the Boeing 787 Dreamliner. My data is limited to the information in the aircraft_models table, which includes details such as model name, manufacturer, passenger capacity, and technical specifications. For safety-related information, I recommend consulting official aviation authorities or safety reports.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE manufacturing.aircraft_models ( model_id text, model_name text, manufacturer text, passenger_capacity integer, max_range_km integer, engine_type text, wingspan_m numeric, status text, first_flight_date date )


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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )


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

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

[User] Can you also include the symbol and decimals for these tokens?

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

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

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

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


[User] Find all nodes that were last seen in the last 30 days and have port numbers between 8000 and 9000.

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

[User] Can you also show the count of transactions sent from wallet addresses that share the same IP as these nodes?

[Assistant] This query isn't possible with the current schema as there's no relationship between nodes IP addresses and wallet addresses.

[User] Then just show me nodes that share the same IP address along with how many nodes share each IP.

[Assistant] SELECT ip_address, COUNT(*) as node_count FROM blockchain.nodes GROUP BY ip_address HAVING COUNT(*) > 1

[User] Now filter this to only show IP addresses with more than 3 nodes and include the earliest and latest last_seen timestamps.

[Assistant] SELECT ip_address, COUNT(*) as node_count, MIN(last_seen) as earliest_seen, MAX(last_seen) as latest_seen FROM blockchain.nodes GROUP BY ip_address HAVING COUNT(*) > 3

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.transactions ( transaction_id text, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.nodes ( node_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )
CREATE TABLE blockchain.smart_contracts ( contract_id text, creator_address text, code text, timestamp timestamp )


[User] List pairs of wallet IDs owned by the same user where the creation dates are more than one year apart. Show the user ID and the wallet IDs of both wallets.

[Assistant] SELECT w1.user_id, w1.wallet_id AS wallet_id_1, w2.wallet_id AS wallet_id_2 FROM web3.wallets w1 JOIN web3.wallets w2 ON w1.user_id = w2.user_id AND w2.created_at > w1.created_at + INTERVAL '1 year' ORDER BY w1.user_id, w1.created_at;

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


[User] List all the appointments that overlap in time for the same location, showing both appointment IDs, their start and end times, and the location.

[Assistant]
SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2,
       a1.start_time AS start_1, a1.end_time AS end_1,
       a2.start_time AS start_2, a2.end_time AS end_2,
       a1.location
FROM legal_services.appointments a1
JOIN legal_services.appointments a2
  ON a1.location = a2.location
 AND a1.appointment_id < a2.appointment_id
 AND a1.start_time < a2.end_time
 AND a2.start_time < a1.end_time;

[User] Can you narrow this to only show overlapping appointments that are both in 'Scheduled' status?

[Assistant]
SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2,
       a1.start_time AS start_1, a1.end_time AS end_1,
       a2.start_time AS start_2, a2.end_time AS end_2,
       a1.location
FROM legal_services.appointments a1
JOIN legal_services.appointments a2
  ON a1.location = a2.location
 AND a1.appointment_id < a2.appointment_id
 AND a1.start_time < a2.end_time
 AND a2.start_time < a1.end_time
WHERE a1.status = 'Scheduled' AND a2.status = 'Scheduled';

[User] Also, please only show overlaps that last longer than 10 minutes.

[Assistant]
SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2,
       a1.start_time AS start_1, a1.end_time AS end_1,
       a2.start_time AS start_2, a2.end_time AS end_2,
       a1.location
FROM legal_services.appointments a1
JOIN legal_services.appointments a2
  ON a1.location = a2.location
 AND a1.appointment_id < a2.appointment_id
 AND a1.start_time < a2.end_time
 AND a2.start_time < a1.end_time
WHERE a1.status = 'Scheduled' AND a2.status = 'Scheduled'
  AND EXTRACT(EPOCH FROM (LEAST(a1.end_time, a2.end_time) - GREATEST(a1.start_time, a2.start_time))) > 600;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.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 usernames and the length of their 'bio' field for users whose 'is_verified' status is true.

[Assistant] SELECT username, LENGTH(bio) AS bio_length FROM social_media.users WHERE is_verified IS TRUE;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )


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

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

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


[User] List each lawyer's full name with the full name of the partner at the same firm.

[Assistant]
SELECT l.lawyer_id,
       CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_name
FROM legal_services.lawyers l
JOIN legal_services.lawyers p
  ON l.firm_id = p.firm_id
 AND p.is_partner = true;

[User] Actually, I only want those lawyers whose specialization includes 'Corporate Law'. Could you update the query?

[Assistant]
SELECT l.lawyer_id,
       CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_name
FROM legal_services.lawyers l
JOIN legal_services.lawyers p
  ON l.firm_id = p.firm_id
 AND p.is_partner = true
WHERE l.specialization ILIKE '%Corporate Law%';

[User] Also only show those who were hired after 2020-01-01.

[Assistant]
SELECT l.lawyer_id,
       CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_name
FROM legal_services.lawyers l
JOIN legal_services.lawyers p
  ON l.firm_id = p.firm_id
 AND p.is_partner = true
WHERE l.specialization ILIKE '%Corporate Law%'
  AND l.hire_date > '2020-01-01';

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


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

[Assistant]
SELECT g.guest_id,
       g.first_name || ' ' || g.last_name AS full_name,
       COUNT(so.order_id) AS order_count
FROM hospitality_technology.guests g
LEFT JOIN hospitality_technology.service_orders so
  ON g.guest_id = so.guest_id
GROUP BY g.guest_id, full_name
ORDER BY order_count DESC;


[User] Show the plan name and insurance provider for all insurance plans along with the total number of unique patients enrolled in each plan.

[Assistant]
SELECT ip.plan_name, ip.insurance_provider, COUNT(DISTINCT pi.patient_id) AS enrolled_patient_count
FROM healthcare.insurance_plans ip
JOIN healthcare.patients_insurance pi ON ip.plan_id = pi.plan_id
GROUP BY ip.plan_name, ip.insurance_provider;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
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.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records ( record_id 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.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.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id 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] For each chain, which token had the highest number of smart money addresses buying it this week? Show the token symbol and narrative too.

[Assistant] SELECT chain, token_symbol, narrative, MAX(address_amount) AS max_buyers FROM smart_money_token_inflow WHERE type = 1 AND DATE_TRUNC('week', CURRENT_DATE) = DATE_TRUNC('week', CURRENT_DATE) GROUP BY chain, token_symbol, narrative;

[User] I got an error, I think the filter for the week may be wrong. Please revise the query so that it only counts buys from the current week.

[Assistant] SELECT chain, token_symbol, narrative, address_amount AS buyers FROM smart_money_token_inflow WHERE type = 1 AND EXTRACT(week FROM CURRENT_DATE) = EXTRACT(week FROM CURRENT_DATE) AND EXTRACT(year FROM CURRENT_DATE) = EXTRACT(year FROM CURRENT_DATE) ORDER BY chain, buyers DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )


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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


[User] Show me all transactions where the description contains the word 'fee'.

[Assistant] SELECT * FROM financial_services.transactions WHERE description ILIKE '%fee%';

[User] Limit the results to transactions that occurred in the previous month.

[Assistant] SELECT * FROM financial_services.transactions WHERE description ILIKE '%fee%' AND transaction_date >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month') AND transaction_date < date_trunc('month', CURRENT_DATE);

[User] Only include transactions with an amount greater than 20.

[Assistant] SELECT * FROM financial_services.transactions WHERE description ILIKE '%fee%' AND transaction_date >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month') AND transaction_date < date_trunc('month', CURRENT_DATE) AND amount > 20;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.transactions ( transaction_id text, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )


[User] What is the ticket price for a journey on train number T4321?

[Assistant] I'm sorry, but I don't have access to information about ticket prices for specific trains. The data I have is limited to train details such as model, manufacturer, capacity, and maintenance schedules. For ticket pricing, please consult the ticketing office or the official website.

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


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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )


[User] For each user, list all pairs of read and unread notifications, showing the recipient_user_id, the unread notification_id and type, and the read notification_id and type.

[Assistant]
SELECT
  n_unread.recipient_user_id,
  n_unread.notification_id   AS unread_id,
  n_unread.notification_type AS unread_type,
  n_read.notification_id     AS read_id,
  n_read.notification_type   AS read_type
FROM social_media.notifications n_unread
JOIN social_media.notifications n_read
  ON n_unread.recipient_user_id = n_read.recipient_user_id
WHERE n_unread.read_at IS NULL
  AND n_read.read_at IS NOT NULL;

[User] Actually, only include pairs where the unread notification_type is 'message'.

[Assistant]
SELECT
  n_unread.recipient_user_id,
  n_unread.notification_id   AS unread_id,
  n_unread.notification_type AS unread_type,
  n_read.notification_id     AS read_id,
  n_read.notification_type   AS read_type
FROM social_media.notifications n_unread
JOIN social_media.notifications n_read
  ON n_unread.recipient_user_id = n_read.recipient_user_id
WHERE n_unread.read_at IS NULL
  AND n_read.read_at IS NOT NULL
  AND n_unread.notification_type = 'message';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )


[User] Can you help me get the total number of operational platforms across all stations?

[Assistant] db.platforms.countDocuments({ status: 'Operational' });

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
// db.createCollection('platforms')
// Optional: db.platforms.createIndex({ platform_id: 1 }, { unique: true })
// Optional: db.platforms.createIndex({ station_id: 1 })
{
  _id: ObjectId(),
  platform_id: "plat_123", // String (unique)
  station_id: "station_xyz", // String (references stations.station_id)
  platform_number: "1A", // String
  track_number: "T1", // String
  status: "Operational", // String ('Operational', 'Maintenance', 'Closed')
  length_meters: 250.50, // Decimal128 or Double
  accessible: true // Boolean
}
// db.createCollection('routes')
// Optional: db.routes.createIndex({ route_id: 1 }, { unique: true })
{
  _id: ObjectId(),
  route_id: "route_ne_corr", // String (unique)
  route_name: "Northeast Corridor", // String
  description: "High-speed rail linking Boston and Washington D.C.", // String
  origin_station_id: "station_bos", // String (references stations.station_id)
  destination_station_id: "station_was", // String (references stations.station_id)
  is_active: true // Boolean
}
// db.createCollection('route_stations')
// Optional: db.route_stations.createIndex({ route_station_id: 1 }, { unique: true })
// Optional: db.route_stations.createIndex({ route_id: 1, sequence_order: 1 }, { unique: true })
{
  _id: ObjectId(),
  route_station_id: "rs_ne_1", // String (unique)
  route_id: "route_ne_corr", // String (references routes.route_id)
  station_id: "station_bos", // String (references stations.station_id)
  sequence_order: 1, // Int32
  distance_from_previous_km: null, // Decimal128 or Double (null for first stop)
  typical_stop_duration_minutes: null // Int32 (null for origin/destination or if no stop)
}
// --- OR --- Embed within the Route document:
// {
//   _id: ObjectId(), route_id: "route_ne_corr", ...,
//   stations: [
//     { station_id: "station_bos", sequence_order: 1, distance_from_previous_km: null, typical_stop_duration_minutes: null },
//     { station_id: "station_pvd", sequence_order: 2, distance_from_previous_km: 70.5, typical_stop_duration_minutes: 5 },
//     ...
//   ]
// }
// db.createCollection('schedules')
// Optional: db.schedules.createIndex({ schedule_id: 1 }, { unique: true })
// Optional: db.schedules.createIndex({ route_id: 1, departure_datetime: 1 })
{
  _id: ObjectId(),
  schedule_id: "sched_1122", // String (unique)
  train_id: "train_789", // String (references trains.train_id)
  route_id: "route_ne_corr", // String (references routes.route_id)
  departure_datetime: ISODate("2024-05-10T08:00:00-04:00"), // Date (with timezone)
  arrival_datetime: ISODate("2024-05-10T15:30:00-04:00"), // Date (with timezone)
  status: "Scheduled", // String ('Scheduled', 'On Time', 'Delayed', 'Cancelled', 'Arrived')
  notes: "Track work expected near Philadelphia" // String
}
// db.createCollection('schedule_stops')
// Optional: db.schedule_stops.createIndex({ stop_id: 1 }, { unique: true })
// Optional: db.schedule_stops.createIndex({ schedule_id: 1, sequence_order: 1 }, { unique: true })
{
  _id: ObjectId(),
  stop_id: "stop_sched1122_1", // String (unique)
  schedule_id: "sched_1122", // String (references schedules.schedule_id)
  station_id: "station_bos", // String (references stations.station_id)
  platform_id: "plat_bos_3", // String (references platforms.platform_id, nullable)
  sequence_order: 1, // Int32
  scheduled_arrival_time: null, // Date
  scheduled_departure_time: ISODate("2024-05-10T08:00:00-04:00"), // Date
  actual_arrival_time: null, // Date
  actual_departure_time: ISODate("2024-05-10T08:01:00-04:00"), // Date
  status: "On Time" // String
}
// --- OR --- Embed within the Schedule document using an array 'stops'
// db.createCollection('passengers')
// Optional: db.passengers.createIndex({ passenger_id: 1 }, { unique: true })
// Optional: db.passengers.createIndex({ email: 1 }, { unique: true, sparse: true })
// Optional: db.passengers.createIndex({ phone_number: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  passenger_id: "pass_pqr", // String (unique)
  first_name: "Alice", // String
  last_name: "Smith", // String
  email: "alice.smith@example.com", // String (unique, sparse)
  phone_number: "+15551234567", // String (unique, sparse)
  date_of_birth: ISODate("1990-03-20"), // Date
  loyalty_program_id: "LOYALTY123", // String
  created_at: ISODate("2023-02-01T11:00:00Z") // Date
}
// db.createCollection('staff')
// Optional: db.staff.createIndex({ staff_id: 1 }, { unique: true })
// Optional: db.staff.createIndex({ employee_number: 1 }, { unique: true })
// Optional: db.staff.createIndex({ contact_email: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  staff_id: "staff_mno", // String (unique)
  first_name: "Bob", // String
  last_name: "Jones", // String
  role: "Conductor", // String
  primary_station_id: null, // String (references stations.station_id, nullable)
  employee_number: "E12345", // String (unique)
  hire_date: ISODate("2018-06-01"), // Date
  contact_email: "bob.jones@example-rail.com", // String (unique, sparse)
  contact_phone: "+15559876543", // String
  is_active: true // Boolean
}


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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )


[User] Which service locations are not accessible and belong to agencies with a jurisdiction level of 'Local'? Show the location name and city.

[Assistant]
SELECT sl.location_name, sl.city
FROM government_services.service_locations sl
INNER JOIN government_services.agencies a ON sl.agency_id = a.agency_id
WHERE sl.is_accessible = FALSE
  AND a.jurisdiction_level = 'Local';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.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.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)
)


[User] Show all likes made by user 'U555' on comments, including the comment_id and like creation time.

[Assistant]
SELECT like_id, comment_id, created_at
FROM social_media.likes
WHERE user_id = 'U555' AND comment_id IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
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) )
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)


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

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

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


[User] Show me all events emitted by contracts where the event name contains 'Approval', along with the contract ID and transaction ID, sorted by emitted timestamp in descending order.

[Assistant] SELECT event_id, contract_id, event_name, transaction_id, emitted_at FROM web3.events WHERE event_name LIKE '%Approval%' ORDER BY emitted_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)


[User] What is the history of incidents or accidents that occurred on platform 5 at station GHI?

[Assistant] I'm sorry, but I can't provide information about the history of incidents or accidents on platform 5 at station GHI. My data is limited to the structural and operational details of the platforms, such as platform ID, station ID, and status. For incident history, you may need to consult a different database or contact the relevant authorities.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.platforms ( platform_id.text, station_id.text, platform_number.text, track_number.text, status.text, length_meters.numeric, accessible.boolean )


[User] Show each policy number and the total amount paid for it across all premium payments received so far.

[Assistant] SELECT T1.policy_number, SUM(T2.amount_paid) FROM insurance.policies AS T1 JOIN insurance.premium_payments AS T2 ON T1.policy_id = T2.policy_id GROUP BY T1.policy_number;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.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 )
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )


[User] List the names of services for which documents are set to expire in the next 90 days.

[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 T3.expiry_date IS NOT NULL AND T3.expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '90 days'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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] Count the number of events for each hour of the day based on the emitted_at timestamp.

[Assistant] SELECT EXTRACT(HOUR FROM emitted_at) AS event_hour, COUNT(*) AS event_count FROM web3.events GROUP BY event_hour ORDER BY event_hour;

[User] Actually, only show hours with more than 100 events.

[Assistant] SELECT EXTRACT(HOUR FROM emitted_at) AS event_hour, COUNT(*) AS event_count FROM web3.events GROUP BY event_hour HAVING COUNT(*) > 100 ORDER BY event_hour;

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


[User] Show smart money addresses with an ROI greater than 3 and a realized ratio greater than 0.7. Display the address, chain, ROI, realized ratio, and most profitable token.

[Assistant] SELECT address, chain, roi, realized_ratio, most_profit_token FROM smart_money_profit WHERE roi > 3 AND realized_ratio > 0.7;

[User] For these tokens (`most_profit_token` from the previous result), what is the total USD value held by CEXes across all chains? Show the token symbol and the total CEX USD value.

[Assistant] WITH HighlyPerformingTokens AS (SELECT DISTINCT most_profit_token FROM smart_money_profit WHERE roi > 3 AND realized_ratio > 0.7 AND most_profit_token IS NOT NULL) SELECT c.token_symbol, SUM(c.usd_value) AS total_cex_usd_value FROM cex_token_balance c JOIN HighlyPerformingTokens h ON c.token_symbol = h.most_profit_token WHERE c.usd_value IS NOT NULL GROUP BY c.token_symbol ORDER BY total_cex_usd_value DESC;

[User] Filter the previous results to only include tokens where the `average_smart_money_roi` is greater than 10 (1000%) and the `average_smart_money_realized_ratio` is greater than 0.8.

[Assistant] WITH CexHeldTokens AS (SELECT DISTINCT token_symbol FROM cex_token_balance WHERE token_symbol IS NOT NULL AND token_symbol != ''), TokenPerformance AS (SELECT s.most_profit_token AS token_symbol, AVG(s.roi) AS average_smart_money_roi, AVG(s.realized_ratio) AS average_smart_money_realized_ratio FROM smart_money_profit s JOIN CexHeldTokens c ON s.most_profit_token = c.token_symbol WHERE s.roi IS NOT NULL AND s.realized_ratio IS NOT NULL GROUP BY s.most_profit_token) SELECT token_symbol, average_smart_money_roi, average_smart_money_realized_ratio FROM TokenPerformance WHERE average_smart_money_roi > 10 AND average_smart_money_realized_ratio > 0.8 ORDER BY average_smart_money_roi DESC;

[User] For these filtered tokens, add the total USD value held by CEXes (`usd_value` from `cex_token_balance`) to the results. Show token symbol, total CEX USD value, average ROI, and average realized ratio.

[Assistant] WITH CexHeldTokens AS (SELECT DISTINCT token_symbol FROM cex_token_balance WHERE token_symbol IS NOT NULL AND token_symbol != ''), TokenPerformance AS (SELECT s.most_profit_token AS token_symbol, AVG(s.roi) AS average_smart_money_roi, AVG(s.realized_ratio) AS average_smart_money_realized_ratio FROM smart_money_profit s JOIN CexHeldTokens c ON s.most_profit_token = c.token_symbol WHERE s.roi IS NOT NULL AND s.realized_ratio IS NOT NULL GROUP BY s.most_profit_token), FilteredPerformance AS (SELECT token_symbol, average_smart_money_roi, average_smart_money_realized_ratio FROM TokenPerformance WHERE average_smart_money_roi > 10 AND average_smart_money_realized_ratio > 0.8) SELECT fp.token_symbol, SUM(c.usd_value) AS total_cex_usd_value, fp.average_smart_money_roi, fp.average_smart_money_realized_ratio FROM FilteredPerformance fp JOIN cex_token_balance c ON fp.token_symbol = c.token_symbol WHERE c.usd_value IS NOT NULL GROUP BY fp.token_symbol, fp.average_smart_money_roi, fp.average_smart_money_realized_ratio ORDER BY fp.average_smart_money_roi DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )


[User] Show me the wallet addresses and their creation dates for wallets created in the last 30 days, sorted by creation date in descending order.

[Assistant] SELECT address, created_at FROM web3.wallets WHERE created_at >= CURRENT_DATE - INTERVAL '30 days' ORDER BY created_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)


[User] Find the address that has the highest total amount across all its UTXOs.

[Assistant] SELECT address FROM utxos GROUP BY address ORDER BY SUM(amount) DESC LIMIT 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.trades ( trade_id.text, order_id.text, buyer_id.text, seller_id.text, asset_id.text, quantity.numeric, price.numeric, traded_at.timestamp )
CREATE TABLE trading_platform.assets ( asset_id.text, name.text, symbol.text, type.text )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id.text, asset_id.text, key.text, value.text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )


[User] List all wallet addresses that hold any NFT currently. Show the wallet address and the count of distinct token IDs they hold.

[Assistant] SELECT wallet_address, COUNT(DISTINCT token_id) FROM nft_holders GROUP BY wallet_address;

[User] Filter the list to only include wallets that hold more than 5 unique NFTs.

[Assistant] SELECT wallet_address, COUNT(DISTINCT token_id) FROM nft_holders GROUP BY wallet_address HAVING COUNT(DISTINCT token_id) > 5;

[User] Order the results by the count of unique NFTs held in descending order.

[Assistant] SELECT wallet_address, COUNT(DISTINCT token_id) AS unique_nft_count FROM nft_holders GROUP BY wallet_address HAVING COUNT(DISTINCT token_id) > 5 ORDER BY unique_nft_count DESC;

[User] Limit the output to the top 20 wallets.

[Assistant] SELECT wallet_address, COUNT(DISTINCT token_id) AS unique_nft_count FROM nft_holders GROUP BY wallet_address HAVING COUNT(DISTINCT token_id) > 5 ORDER BY unique_nft_count DESC LIMIT 20;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE sui_coins_metadata ( object_id varchar NOT NULL, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id varchar NOT NULL, status varchar NOT NULL, collection_type varchar NOT NULL, package_id varchar NOT NULL, previous_transaction varchar NOT NULL, display varchar NOT NULL, owner varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(255) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )


[User] List all passengers along with their ages and loyalty program membership status.

[Assistant] SELECT passenger_id, first_name, last_name, date_of_birth, loyalty_program_id, DATE_PART('year', AGE(current_date, date_of_birth)) AS age FROM transportation.passengers ORDER BY last_name, first_name;

[User] I need to see only passengers who are at least 30 years old.

[Assistant] SELECT passenger_id, first_name, last_name, date_of_birth, loyalty_program_id, DATE_PART('year', AGE(current_date, date_of_birth)) AS age FROM transportation.passengers WHERE DATE_PART('year', AGE(current_date, date_of_birth)) >= 30 ORDER BY last_name, first_name;

[User] Can you also exclude passengers without a registered email address?

[Assistant] SELECT passenger_id, first_name, last_name, date_of_birth, loyalty_program_id, DATE_PART('year', AGE(current_date, date_of_birth)) AS age FROM transportation.passengers WHERE DATE_PART('year', AGE(current_date, date_of_birth)) >= 30 AND email IS NOT NULL ORDER BY last_name, first_name;

[User] Actually, add their phone number and order by age descending.

[Assistant] SELECT passenger_id, first_name, last_name, date_of_birth, loyalty_program_id, email, phone_number, DATE_PART('year', AGE(current_date, date_of_birth)) AS age FROM transportation.passengers WHERE DATE_PART('year', AGE(current_date, date_of_birth)) >= 30 AND email IS NOT NULL ORDER BY age DESC, last_name, first_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)


[User] What is the total number of drivers hired each year? Provide the hire_year and driver_count.

[Assistant]
SELECT EXTRACT(YEAR FROM hire_date) AS hire_year,
       COUNT(*)                  AS driver_count
FROM transportation.drivers
GROUP BY EXTRACT(YEAR FROM hire_date);

[User] Now only include years where driver_count > 3 and order the results by driver_count DESC.

[Assistant]
SELECT hire_year, driver_count
FROM (
  SELECT EXTRACT(YEAR FROM hire_date) AS hire_year,
         COUNT(*)                  AS driver_count
  FROM transportation.drivers
  GROUP BY EXTRACT(YEAR FROM hire_date)
) sub
WHERE driver_count > 3
ORDER BY driver_count DESC;

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