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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.transactions ( transaction_id.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees ( employee_id.text, first_name.text, last_name.text, job_title.text, department.text, branch_id.text, email.text, phone_extension.text, hire_date.date, termination_date.date, manager_id.text, status.text )
CREATE TABLE financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )


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

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

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


[User] For each driver, find the other driver whose license_expiry_date is the next one after theirs. Show both IDs, names and their expiry dates.

[Assistant]
SELECT
  d1.driver_id            AS driver_id,
  d1.first_name || ' ' || d1.last_name     AS driver_name,
  d1.license_expiry_date  AS expiry_date,
  d2.driver_id            AS next_driver_id,
  d2.first_name || ' ' || d2.last_name     AS next_driver_name,
  d2.license_expiry_date  AS next_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date = (
    SELECT MIN(d3.license_expiry_date)
    FROM transportation.drivers d3
    WHERE d3.license_expiry_date > d1.license_expiry_date
  );

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


[User] List all users who have bought assets, along with their wallet addresses.

[Assistant] SELECT DISTINCT T1.user_id, T1.address FROM wallets AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id;

[User] Filter this list to include only trades made in the last 30 days.

[Assistant] SELECT DISTINCT T1.user_id, T1.address FROM wallets AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id WHERE T2.traded_at >= datetime('now', '-30 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 trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.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.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.logs ( log_id.text, user_id.text, action.text, details.text, logged_at.timestamp )


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

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

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

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

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


[User] Show me the top 3 smart money addresses by profit across all chains, along with their most profitable token and chain information.

[Assistant]
SELECT address, profit, most_profit_token, chain
FROM smart_money_profit
ORDER BY profit DESC
LIMIT 3;

[User] Actually, I only want to see addresses from Ethereum chain with ROI over 30%.

[Assistant]
SELECT address, profit, most_profit_token, roi
FROM smart_money_profit
WHERE chain = 'Ethereum' AND roi > 30
ORDER BY profit DESC
LIMIT 3;

[User] Can you add their realized profit ratio and filter to only show results with profit over $100,000?

[Assistant]
SELECT address, profit, most_profit_token, roi, realized_ratio
FROM smart_money_profit
WHERE chain = 'Ethereum' AND roi > 30 AND profit > 100000
ORDER BY profit DESC
LIMIT 3;

[User] Now order these results by ROI in descending order instead of profit.

[Assistant]
SELECT address, profit, most_profit_token, roi, realized_ratio
FROM smart_money_profit
WHERE chain = 'Ethereum' AND roi > 30 AND profit > 100000
ORDER BY roi DESC
LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
CREATE TABLE 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] How many documents are there for each document_type? Show document_type and count ordered by the count in descending order.

[Assistant]
SELECT document_type,
       COUNT(*) AS count
FROM legal_services.documents
GROUP BY document_type
ORDER BY 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 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] Find cases where an address received tokens in one transfer and then sent tokens in another. List the receive transfer_id, the send transfer_id, the address, and both transfer values.

[Assistant]
SELECT recv.transfer_id AS receive_transfer_id,
       send.transfer_id AS send_transfer_id,
       recv.to_address AS address,
       recv.value       AS received_value,
       send.value       AS sent_value
FROM web3.token_transfers recv
JOIN web3.token_transfers send
  ON recv.to_address = send.from_address;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)


[User] Find all pairs of distinct routes that share the same origin location ID. List the route IDs and route numbers for both routes in each pair, along with the shared origin location ID.

[Assistant] SELECT r1.route_id AS route1_id, r1.route_number AS route1_number, r2.route_id AS route2_id, r2.route_number AS route2_number, r1.origin_location_id FROM transportation.routes AS r1 JOIN transportation.routes AS r2 ON r1.origin_location_id = r2.origin_location_id WHERE r1.route_id < r2.route_id;

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


[User] For each group chat, can you show me each participant's username and the date they joined the chat?

[Assistant]
SELECT u.username, c.group_name, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = true;

[User] Can you also include the total number of participants for each group chat in the result?

[Assistant]
SELECT u.username, c.group_name, cp.joined_at, COUNT(cp2.participant_id) AS total_participants
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
JOIN social_media.conversation_participants cp2 ON cp2.conversation_id = cp.conversation_id
WHERE c.is_group_chat = true
GROUP BY u.username, c.group_name, cp.joined_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 social_media.users ( user_id text, 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 boolean )
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.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )


[User] List the content and sent time for messages sent by user 'U101'.

[Assistant] SELECT content, sent_at FROM social_media.messages WHERE sender_user_id = 'U101';

[User] Could you also include the group name for those messages and only show messages sent in group chats?

[Assistant] SELECT m.content, m.sent_at, c.name AS group_name FROM social_media.messages m JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.sender_user_id = 'U101' AND c.type = 'group';

[User] Now filter to include only messages sent in June 2024 and order them by sent time descending.

[Assistant] SELECT m.content, m.sent_at, c.name AS group_name FROM social_media.messages m JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.sender_user_id = 'U101' AND c.type = 'group' AND m.sent_at >= '2024-06-01' AND m.sent_at < '2024-07-01' ORDER BY m.sent_at DESC;

[User] Also limit the results to the top 15.

[Assistant] SELECT m.content, m.sent_at, c.name AS group_name FROM social_media.messages m JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.sender_user_id = 'U101' AND c.type = 'group' AND m.sent_at >= '2024-06-01' AND m.sent_at < '2024-07-01' ORDER BY m.sent_at DESC LIMIT 15;

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.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)


[User] For each NFT collection on Ethereum, calculate the number of unique tokens and the average rarity_score. Show contract_address, token_count, and avg_rarity.

[Assistant]
SELECT nm.contract_address,
       COUNT(DISTINCT nm.token_id) AS token_count,
       AVG(nm.rarity_score) AS avg_rarity
FROM nft_metadata nm
WHERE nm.blockchain = 'Ethereum'
GROUP BY nm.contract_address
ORDER BY avg_rarity DESC;

[User] Now only include collections with token_count > 100 and avg_rarity > 80.

[Assistant]
SELECT nm.contract_address,
       COUNT(DISTINCT nm.token_id) AS token_count,
       AVG(nm.rarity_score) AS avg_rarity
FROM nft_metadata nm
WHERE nm.blockchain = 'Ethereum'
GROUP BY nm.contract_address
HAVING COUNT(DISTINCT nm.token_id) > 100
   AND AVG(nm.rarity_score) > 80
ORDER BY avg_rarity DESC;

[User] Also include the number of unique holders from nft_holders by joining on contract_address.

[Assistant]
WITH stats AS (
  SELECT contract_address,
         COUNT(DISTINCT token_id) AS token_count,
         AVG(rarity_score) AS avg_rarity
  FROM nft_metadata
  WHERE blockchain = 'Ethereum'
  GROUP BY contract_address
  HAVING COUNT(DISTINCT token_id) > 100
     AND AVG(rarity_score) > 80
)
SELECT s.contract_address,
       s.token_count,
       s.avg_rarity,
       COUNT(DISTINCT nh.wallet_address) AS holder_count
FROM stats s
JOIN nft_holders nh ON s.contract_address = nh.contract_address
GROUP BY s.contract_address, s.token_count, s.avg_rarity
ORDER BY s.avg_rarity DESC;

[User] Finally, sort by holder_count descending and limit to top 10.

[Assistant]
WITH stats AS (
  SELECT contract_address,
         COUNT(DISTINCT token_id) AS token_count,
         AVG(rarity_score) AS avg_rarity
  FROM nft_metadata
  WHERE blockchain = 'Ethereum'
  GROUP BY contract_address
  HAVING COUNT(DISTINCT token_id) > 100
     AND AVG(rarity_score) > 80
)
SELECT s.contract_address,
       s.token_count,
       s.avg_rarity,
       COUNT(DISTINCT nh.wallet_address) AS holder_count
FROM stats s
JOIN nft_holders nh ON s.contract_address = nh.contract_address
GROUP BY s.contract_address, s.token_count, s.avg_rarity
ORDER BY holder_count DESC
LIMIT 10;

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


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

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

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


[User] What is the reason behind the cost variation for maintenance of asset_id 'ASSET456' over the past year?

[Assistant] I'm sorry, but I can't provide information on the reasons behind cost variations for maintenance. The data in the maintenance_records table includes only the cost amount and other basic details of each maintenance record, but it does not contain explanations or factors influencing cost changes.

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.maintenance_records ( record_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, asset_type character varying(32) NOT NULL, maintenance_type character varying(128) NOT NULL, staff_id character varying(64), start_datetime timestamp NOT NULL, end_datetime timestamp, description text NOT NULL, cost numeric(12, 2), status character varying(32) NOT NULL DEFAULT 'Completed', PRIMARY KEY (record_id), FOREIGN KEY (staff_id) REFERENCES train_station_management.staff(staff_id) )


[User] List all rooms that have a 'Jacuzzi' feature, including the room_number, property_id, type_name, and base_rate.

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

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


[User] List all agencies that do not have a website URL specified. Return their agency_id, agency_name, and main_phone_number.

[Assistant] SELECT agency_id, agency_name, main_phone_number FROM government_services.agencies WHERE website_url IS NULL OR website_url = '';

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 character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )


[User] Show me the username and email of all users who own at least one wallet.

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.wallets ( wallet_id.text, user_id.text, address_id.text, private_key.text )
CREATE TABLE blockchain.users ( user_id.text, username.text, email.text, password_hash.text )


[User] List all pairs of hashtags that were created on the same date. Show both tag names and the creation date.

[Assistant]
SELECT a.tag_name AS tag1, b.tag_name AS tag2, a.created_at::date AS created_date
FROM social_media.hashtags a
JOIN social_media.hashtags b
  ON a.created_at::date = b.created_at::date
  AND a.hashtag_id < b.hashtag_id;

[User] Actually, only include pairs where both tag names start with the letter 'S'.

[Assistant]
SELECT a.tag_name AS tag1, b.tag_name AS tag2, a.created_at::date AS created_date
FROM social_media.hashtags a
JOIN social_media.hashtags b
  ON a.created_at::date = b.created_at::date
  AND a.hashtag_id < b.hashtag_id
WHERE a.tag_name LIKE 'S%'
  AND b.tag_name LIKE 'S%';

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.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )


[User] I want to identify pairs of bookings that share the same payment_transaction_id, showing both booking IDs and the payment_transaction_id.

[Assistant]
SELECT b1.booking_id AS booking1, b2.booking_id AS booking2, b1.payment_transaction_id
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.payment_transaction_id = b2.payment_transaction_id
  AND b1.booking_id < b2.booking_id;

[User] Now limit the results to only include pairs where both bookings have a status of 'Completed'.

[Assistant]
SELECT b1.booking_id AS booking1, b2.booking_id AS booking2, b1.payment_transaction_id
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.payment_transaction_id = b2.payment_transaction_id
  AND b1.booking_id < b2.booking_id
WHERE b1.status = 'Completed'
  AND b2.status = 'Completed';

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.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )


[User] Calculate the average number of days between when an incident occurred and when the claim was reported, but only for claims that were settled in the year 2023.

[Assistant]
SELECT
  AVG(EXTRACT(EPOCH FROM (reported_date - incident_date)) / 86400.0)::numeric(10, 2)
FROM
  insurance.claims
WHERE
  settlement_date IS NOT NULL AND EXTRACT(YEAR FROM settlement_date) = 2023;

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


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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE nft_metadata (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    token_id varchar NOT NULL, -- The number of the token
    contract_name varchar NOT NULL, -- contract_name fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    amount bigint NOT NULL, -- amount fields for the functionType  in contract
    minter varchar NOT NULL, -- minter fields for the functionType  in contract
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    mint_block_number bigint NOT NULL, -- mint_block_number fields for the functionType  in contract
    mint_time bigint NOT NULL, -- mint_time fields for the functionType  in contract
    mint_transaction_hash varchar NOT NULL, -- mint_transaction_hash fields for the functionType  in contract
    mint_price varchar NOT NULL, -- mint_price fields for the functionType  in contract
    token_uri varchar NOT NULL, -- token_uri fields for the functionType  in contract
    metadata varchar NOT NULL, -- metadata fields for the functionType  in contract
    name varchar NOT NULL, -- name fields for the functionType  in contract
    image_uri varchar NOT NULL, -- image_uri fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    status varchar NOT NULL, -- status fields for the functionType  in contract
    rarity_score real NOT NULL, -- rarity_score fields for the functionType  in contract
    rarity_rank integer NOT NULL, -- rarity_rank fields for the functionType  in contract
    unique_attribute_count integer NOT NULL, -- unique_attribute_count fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(mint_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE mud_holesky_redstone (
    address varchar NOT NULL, -- address fields for the functionType  in contract
    table_id varchar NOT NULL, -- table_id fields for the functionType  in contract
    key_bytes varchar NOT NULL, -- key_bytes fields for the functionType  in contract
    key0 varchar NOT NULL, -- key0 fields for the functionType  in contract
    key1 varchar NOT NULL, -- key1 fields for the functionType  in contract
    static_data varchar NOT NULL, -- static_data fields for the functionType  in contract
    encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType  in contract
    dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType  in contract
    is_deleted boolean NOT NULL, -- is_deleted fields for the functionType  in contract
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    log_index bigint NOT NULL  -- Index of the log within the transaction
)
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] For each premium payment, list all previous payments made by the same customer. Show customer_id, previous_payment_id, previous_payment_date, current_payment_id, current_payment_date, and amount difference.

[Assistant]
SELECT p1.customer_id,
       p1.payment_id AS previous_payment_id,
       p1.payment_date AS previous_payment_date,
       p2.payment_id AS current_payment_id,
       p2.payment_date AS current_payment_date,
       p2.amount_paid - p1.amount_paid AS amount_diff
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.customer_id = p2.customer_id
  AND p1.payment_date < p2.payment_date;

[User] Actually, only include pairs where the current payment date is in 2024.

[Assistant]
SELECT p1.customer_id,
       p1.payment_id AS previous_payment_id,
       p1.payment_date AS previous_payment_date,
       p2.payment_id AS current_payment_id,
       p2.payment_date AS current_payment_date,
       p2.amount_paid - p1.amount_paid AS amount_diff
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.customer_id = p2.customer_id
  AND p1.payment_date < p2.payment_date
WHERE p2.payment_date BETWEEN '2024-01-01' AND '2024-12-31';

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.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )


[User] Show me all accounts (account_id, account_number, balance) that have a balance greater than $50,000 and are in USD currency, along with the security details (ticker_symbol, security_name) for securities traded on the same exchange as the account's last_updated_at date.

[Assistant] SELECT a.account_id, a.account_number, a.balance, s.ticker_symbol, s.security_name FROM financial_services.accounts a JOIN financial_services.securities s ON a.currency = s.currency WHERE a.balance > 50000 AND a.currency = 'USD' AND s.exchange IS NOT NULL;

[User] Now modify the query to only include accounts with status 'Open' and securities from the 'Technology' sector, sorted by account balance in descending order.

[Assistant] SELECT a.account_id, a.account_number, a.balance, s.ticker_symbol, s.security_name FROM financial_services.accounts a JOIN financial_services.securities s ON a.currency = s.currency WHERE a.balance > 50000 AND a.currency = 'USD' AND a.status = 'Open' AND s.sector = 'Technology' AND s.exchange IS NOT NULL ORDER BY a.balance 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 financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
CREATE TABLE financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)


[User] I need to find all tickets for a specific route 'RT456' along with the car details and route information.

[Assistant]
SELECT t.ticket_id, t.seat_number, t.price, tc.car_number, tc.car_type, r.route_name, r.description
FROM train_station_management.tickets t
JOIN train_station_management.train_cars tc ON t.car_id = tc.car_id
JOIN train_station_management.trains tr ON tc.train_id = tr.train_id
JOIN train_station_management.routes r ON tr.route_id = r.route_id
WHERE r.route_id = 'RT456';

[User] Can you filter this to show only tickets that have been checked in?

[Assistant]
SELECT t.ticket_id, t.seat_number, t.price, tc.car_number, tc.car_type, r.route_name, r.description
FROM train_station_management.tickets t
JOIN train_station_management.train_cars tc ON t.car_id = tc.car_id
JOIN train_station_management.trains tr ON tc.train_id = tr.train_id
JOIN train_station_management.routes r ON tr.route_id = r.route_id
WHERE r.route_id = 'RT456' AND t.is_checked_in = true;

[User] Can you also add the ticket type to the results?

[Assistant]
SELECT t.ticket_id, t.seat_number, t.price, t.ticket_type, tc.car_number, tc.car_type, r.route_name, r.description
FROM train_station_management.tickets t
JOIN train_station_management.train_cars tc ON t.car_id = tc.car_id
JOIN train_station_management.trains tr ON tc.train_id = tr.train_id
JOIN train_station_management.routes r ON tr.route_id = r.route_id
WHERE r.route_id = 'RT456' AND t.is_checked_in = true;

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.train_cars (
    car_id character varying(64) NOT NULL, -- Unique identifier for the train car
    train_id character varying(64) NOT NULL, -- Foreign key referencing trains
    car_number character varying(10) NOT NULL, -- Identifier of the car within the train set
    car_type character varying(64) NOT NULL, -- e.g., Locomotive, Passenger, Sleeper, Dining, Baggage
    class character varying(32), -- e.g., First, Business, Economy (null for non-passenger cars)
    capacity integer, -- Passenger capacity of this specific car (null for non-passenger cars)
    features text, -- Comma-separated list of features (e.g., 'WiFi', 'Power Outlet', 'Accessible Restroom')
    PRIMARY KEY (car_id),
    FOREIGN KEY (train_id) REFERENCES train_station_management.trains(train_id)
)
CREATE TABLE train_station_management.routes (
    route_id character varying(64) NOT NULL, -- Unique identifier for the route
    route_name character varying(128) NOT NULL, -- Name of the route (e.g., 'Northeast Corridor')
    description text, -- Description of the route
    origin_station_id character varying(64) NOT NULL, -- Starting station
    destination_station_id character varying(64) NOT NULL, -- Final station
    is_active boolean NOT NULL DEFAULT true, -- Is the route currently operational?
    PRIMARY KEY (route_id),
    FOREIGN KEY (origin_station_id) REFERENCES train_station_management.stations(station_id),
    FOREIGN KEY (destination_station_id) REFERENCES train_station_management.stations(station_id)
)
CREATE TABLE train_station_management.tickets (
    ticket_id character varying(64) NOT NULL, -- Unique identifier for the ticket
    booking_id character varying(64) NOT NULL, -- Foreign key referencing the booking
    car_id character varying(64) NOT NULL, -- Foreign key referencing the train car
    seat_number character varying(10), -- Assigned seat number (e.g., '12A')
    ticket_type character varying(32) NOT NULL DEFAULT 'Adult', -- e.g., Adult, Child, Senior, Student
    price numeric(10, 2) NOT NULL, -- Price of this specific ticket
    is_checked_in boolean NOT NULL DEFAULT false, -- Has the passenger checked in with this ticket?
    qr_code_data text, -- Data for generating a QR code for the ticket
    PRIMARY KEY (ticket_id),
    FOREIGN KEY (booking_id) REFERENCES train_station_management.bookings(booking_id),
    FOREIGN KEY (car_id) REFERENCES train_station_management.train_cars(car_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] For each player and game pair, please show the total number of achievements unlocked by the player in that game.

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

[User] Can you only include player-game pairs where the player has unlocked at least two achievements for that game?

[Assistant]
SELECT gs.player_id, gs.game_id, COUNT(pa.achievement_id) AS achievements_unlocked
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.player_achievements pa ON gs.player_id = pa.player_id
GROUP BY gs.player_id, gs.game_id
HAVING COUNT(pa.achievement_id) >= 2;

[User] Also show the most recent unlocked_at timestamp among that player's achievements in each game.

[Assistant]
SELECT gs.player_id, gs.game_id, COUNT(pa.achievement_id) AS achievements_unlocked, MAX(pa.unlocked_at) AS most_recent_unlocked
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.player_achievements pa ON gs.player_id = pa.player_id
GROUP BY gs.player_id, gs.game_id
HAVING COUNT(pa.achievement_id) >= 2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, game_id uuid NOT NULL, server_id uuid, start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb, PRIMARY KEY (session_id) )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )


[User] I want to find the total number of players currently connected per region for each game.

[Assistant]
SELECT
  s.region,
  s.game_id,
  SUM(s.current_players) AS total_players
FROM gaming_technology.servers s
GROUP BY
  s.region,
  s.game_id;

[User] Now include the game's title in the output.

[Assistant]
SELECT
  s.region,
  s.game_id,
  g.title,
  SUM(s.current_players) AS total_players
FROM gaming_technology.servers s
JOIN gaming_technology.games g
  ON s.game_id = g.game_id
GROUP BY
  s.region,
  s.game_id,
  g.title;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, game_id uuid NOT NULL, server_id uuid, start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb, PRIMARY KEY (session_id) )
CREATE TABLE gaming_technology.servers ( server_id uuid PRIMARY KEY, game_id uuid, server_name text, region text, ip_address text, port int, current_players int, max_players int, status text, last_heartbeat timestamptz )
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid PRIMARY KEY, player_id uuid, achievement_id uuid, unlocked_at timestamptz )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )


[User] List all loans (loan_id, loan_type, principal_amount) that have a current principal balance less than 25% of the original principal amount, along with their account_id and the difference between principal_amount and current_principal_balance.

[Assistant] SELECT loan_id, loan_type, principal_amount, account_id, (principal_amount - current_principal_balance) AS amount_paid FROM financial_services.loans WHERE current_principal_balance < (0.25 * principal_amount);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] Provide a count of notifications, separated by whether they have been read or not.

[Assistant] SELECT CASE WHEN T1.read_at IS NULL THEN 'Unread' ELSE 'Read' END, count(T1.notification_id) FROM trading_platform.notifications AS T1 GROUP BY CASE WHEN T1.read_at IS NULL THEN 'Unread' ELSE 'Read' END

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


[User] Show me the top 5 narratives by market cap, along with their 24-hour trading volume and 7-day price change percentage.

[Assistant] SELECT narrative.text, volume_24h.numeric, price_change_percentage_7d.numeric FROM narrative_info ORDER BY market_cap.numeric DESC LIMIT 5;

[User] Can you also include the top 3 coins for each of these narratives?

[Assistant] SELECT narrative.text, volume_24h.numeric, price_change_percentage_7d.numeric, top_3_coins.text FROM narrative_info ORDER BY market_cap.numeric 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 narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )


[User] Could you list each game_id along with the count of hidden achievements and the count of visible achievements?

[Assistant]
SELECT game_id,
       SUM(CASE WHEN hidden THEN 1 ELSE 0 END) AS hidden_count,
       SUM(CASE WHEN NOT hidden THEN 1 ELSE 0 END) AS visible_count
FROM gaming_technology.achievements
GROUP BY game_id;

[User] Actually, please provide pairs of one hidden and one visible achievement name for each game where both types exist.

[Assistant]
SELECT h.game_id,
       h.name AS hidden_name,
       v.name AS visible_name
FROM gaming_technology.achievements h
JOIN gaming_technology.achievements v
  ON h.game_id = v.game_id
 AND h.hidden = TRUE
 AND v.hidden = FALSE
WHERE EXISTS (
  SELECT 1 FROM gaming_technology.achievements x
   WHERE x.game_id = h.game_id
     AND x.hidden = FALSE
)
AND EXISTS (
  SELECT 1 FROM gaming_technology.achievements y
   WHERE y.game_id = h.game_id
     AND y.hidden = 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 gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )


[User] Can you help me fetch the inventory details for components associated with a specific aircraft build, including the batch number, quantity, and warehouse location?

[Assistant]
MATCH (ab:AircraftBuild {build_id: 'specific_build_id'})-[:IS_MODEL]->(am:AircraftModel),
(ib:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
RETURN ib.inventory_record_id, ib.batch_number, ib.quantity, ib.location_warehouse

[User] Can you modify this to show only inventory batches received after a specific date, say June 1, 2023?

[Assistant]
MATCH (ab:AircraftBuild {build_id: 'specific_build_id'})-[:IS_MODEL]->(am:AircraftModel),
(ib:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
WHERE ib.received_date > datetime('2023-06-01')
RETURN ib.inventory_record_id, ib.batch_number, ib.quantity, ib.location_warehouse

[User] What if I also want to exclude batches with quantities less than 10?

[Assistant]
MATCH (ab:AircraftBuild {build_id: 'specific_build_id'})-[:IS_MODEL]->(am:AircraftModel),
(ib:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
WHERE ib.received_date > datetime('2023-06-01') AND ib.quantity >= 10
RETURN ib.inventory_record_id, ib.batch_number, ib.quantity, ib.location_warehouse

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 ':AircraftModel'. Properties: { model_id: String (Constraint: UNIQUE), model_name: String, manufacturer: String, passenger_capacity: Integer, max_range_km: Integer, engine_type: String, wingspan_m: Float, status: String, first_flight_date: Date }. Index on model_id.
Node Label ':Material'. Properties: { material_id: String (Constraint: UNIQUE), material_name: String, specification: String, description: String, density_kg_m3: Float, tensile_strength_mpa: Integer }. Index on material_id.
Node Label ':AssemblyLine'. Properties: { line_id: String (Constraint: UNIQUE), line_name: String, location_building: String, location_area: String, capacity_units_per_month: Integer, status: String }. Relationship: (:AssemblyLine)-[:BUILDS_MODEL]->(:AircraftModel {model_id}). Index on line_id.
Node Label ':AssemblyStep'. Properties: { step_id: String (Constraint: UNIQUE), step_number: Integer, step_name: String, description: String, standard_duration_hours: Float, required_skill_level: String, workstation: String }. Relationship: (:AssemblyLine {line_id})-[:HAS_STEP {sequence: <step_number>}]->(:AssemblyStep). Index on step_id.
Node Label ':AircraftBuild'. Properties: { build_id: String (Constraint: UNIQUE), serial_number: String (Constraint: UNIQUE), build_start_date: Datetime, estimated_completion_date: Date, actual_completion_date: Datetime, current_status: String, customer_order_id: String }. Relationships: (:AircraftBuild)-[:IS_MODEL]->(:AircraftModel {model_id}), (:AircraftBuild)-[:ASSEMBLED_ON]->(:AssemblyLine {line_id}). Index on build_id, serial_number, current_status.
Node Label ':Employee'. Properties: { employee_id: String (Constraint: UNIQUE), first_name: String, last_name: String, job_title: String, skill_certifications: String[], hire_date: Date, employment_status: String }. Relationships: (:Employee)-[:ASSIGNED_TO]->(:AssemblyLine {line_id}), (:Employee)-[:REPORTS_TO]->(:Employee {employee_id as supervisor_id}). Index on employee_id.
Node Label ':InventoryBatch'. Properties: { inventory_record_id: String (Constraint: UNIQUE), quantity: Integer, location_warehouse: String, location_bin: String, received_date: Datetime, expiry_date: Date, batch_number: String, last_updated: Datetime }. Relationship: (:InventoryBatch)-[:IS_INSTANCE_OF]->(:Component {component_id}). Index on inventory_record_id, component_id.


[User] List the names of employees and the agency they work for who have scheduled at least one appointment. Show the employee's first name, last name, and agency_id.

[Assistant]
SELECT DISTINCT e.first_name, e.last_name, e.agency_id
FROM government_services.employees e
JOIN government_services.appointments a ON e.employee_id = a.employee_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] Find all wallets that were created on the same day and list their wallet IDs, addresses, and the creation date.

[Assistant] SELECT w1.wallet_id, w1.address, w1.created_at::date AS creation_date FROM web3.wallets w1 JOIN (SELECT created_at::date AS creation_date FROM web3.wallets GROUP BY created_at::date HAVING COUNT(*) > 1) w2 ON w1.created_at::date = w2.creation_date ORDER BY creation_date, w1.wallet_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.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] 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] List all reviews with their property IDs and overall ratings where the rating is 4 or higher.

[Assistant] SELECT review_id, property_id, rating_overall FROM hospitality_technology.reviews WHERE rating_overall >= 4;

[User] Now, include only reviews that have a staff response.

[Assistant] SELECT review_id, property_id, rating_overall FROM hospitality_technology.reviews WHERE rating_overall >= 4 AND staff_response IS NOT NULL;

[User] The query is missing the review date. Can you include that as well?

[Assistant] SELECT review_id, property_id, rating_overall, review_date FROM hospitality_technology.reviews WHERE rating_overall >= 4 AND staff_response IS NOT NULL;

[User] Actually, I need to see the reviews ordered by rating in descending order, and only show the top 10.

[Assistant] SELECT review_id, property_id, rating_overall, review_date FROM hospitality_technology.reviews WHERE rating_overall >= 4 AND staff_response IS NOT NULL ORDER BY rating_overall DESC LIMIT 10;

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


[User] Show a list of all game developers with their name and founded year.

[Assistant]
SELECT
  name,
  founded_year
FROM gaming_technology.developers;

[User] Please filter the list to only include developers founded in the year 1998.

[Assistant]
SELECT
  name,
  founded_year
FROM gaming_technology.developers
WHERE
  founded_year = 1998;

[User] Can you also include the number of games each of these developers has released?

[Assistant]
SELECT
  T1.name,
  T1.founded_year,
  COUNT(T2.game_id) AS game_count
FROM gaming_technology.developers AS T1
LEFT JOIN gaming_technology.games AS T2
  ON T1.developer_id = T2.developer_id
WHERE
  T1.founded_year = 1998
GROUP BY
  T1.developer_id,
  T1.name,
  T1.founded_year;

[User] Now, only show the developers who have released exactly 2 games.

[Assistant]
SELECT
  T1.name,
  T1.founded_year,
  COUNT(T2.game_id) AS game_count
FROM gaming_technology.developers AS T1
JOIN gaming_technology.games AS T2
  ON T1.developer_id = T2.developer_id
WHERE
  T1.founded_year = 1998
GROUP BY
  T1.developer_id,
  T1.name,
  T1.founded_year
HAVING
  COUNT(T2.game_id) = 2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player
    username character varying(100) NOT NULL UNIQUE, -- player's chosen display name
    email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery
    password_hash text NOT NULL, -- securely hashed password
    registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created
    last_login timestamp with time zone, -- timestamp of the last successful login
    country_code character(2), -- player's country (ISO 3166-1 alpha-2)
    status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended)
    profile_data jsonb, -- flexible field for avatar url, bio, preferences etc.
    PRIMARY KEY (player_id)
)
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.developers (
    developer_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the developer studio
    name character varying(150) NOT NULL UNIQUE, -- name of the development studio
    country character varying(100), -- country where the studio is based
    founded_year integer, -- year the studio was founded
    website character varying(255), -- developer's official website
    created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (developer_id)
)
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)


[User] List all unique claim handler IDs present in the claims table.

[Assistant] SELECT DISTINCT claim_handler_id FROM insurance.claims WHERE claim_handler_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 insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )


[User] List all invoices that were paid within 7 days of their issue date. Show invoice number, issue date, payment date, and total amount.

[Assistant] SELECT invoice_number, issue_date, payment_date, total_amount FROM legal_services.invoices WHERE status = 'Paid' AND payment_date IS NOT NULL AND (payment_date::DATE - issue_date) <= 7;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )


[User] List all claim documents along with the beneficiary first and last names and their relationship for policies where a document of type 'MEDICAL_REPORT' exists.

[Assistant]
SELECT cd.document_id, cd.claim_id, cd.file_name, cd.document_type, pb.first_name, pb.last_name, pb.relationship
FROM insurance.claim_documents cd
INNER JOIN insurance.policy_beneficiaries pb ON cd.claim_id = pb.policy_id
WHERE cd.document_type = 'MEDICAL_REPORT';

[User] Actually, please include only beneficiaries whose percentage_share is 30% or more.

[Assistant]
SELECT cd.document_id, cd.claim_id, cd.file_name, cd.document_type, pb.first_name, pb.last_name, pb.relationship, pb.percentage_share
FROM insurance.claim_documents cd
INNER JOIN insurance.policy_beneficiaries pb ON cd.claim_id = pb.policy_id
WHERE cd.document_type = 'MEDICAL_REPORT'
  AND pb.percentage_share >= 30;

[User] Also, add the uploaded_at timestamp from the document to the results and order by uploaded_at descending.

[Assistant]
SELECT cd.document_id, cd.claim_id, cd.file_name, cd.document_type, cd.uploaded_at, pb.first_name, pb.last_name, pb.relationship, pb.percentage_share
FROM insurance.claim_documents cd
INNER JOIN insurance.policy_beneficiaries pb ON cd.claim_id = pb.policy_id
WHERE cd.document_type = 'MEDICAL_REPORT'
  AND pb.percentage_share >= 30
ORDER BY cd.uploaded_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )


[User] What is the current location of train number Acela 2151?

[Assistant] I'm sorry, but I don't have access to real-time location data for trains. The database only contains static information such as train ID, model, capacity, and maintenance schedules. For current location updates, please check with the train operator or a tracking service.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.trains (
    train_id character varying(64) NOT NULL, -- Unique identifier for the train set
    train_number character varying(32) NOT NULL, -- Operational number of the train (e.g., 'Acela 2151')
    model character varying(128), -- Model of the train (e.g., 'Siemens Velaro')
    manufacturer character varying(128), -- Manufacturer of the train
    year_manufactured integer, -- Year the train was built
    capacity integer NOT NULL, -- Total passenger capacity
    status character varying(32) NOT NULL DEFAULT 'Active', -- e.g., Active, Maintenance, Retired
    last_maintenance_date date, -- Date of last scheduled maintenance
    next_maintenance_date date, -- Date of next scheduled maintenance
    PRIMARY KEY (train_id),
    UNIQUE (train_number)
)


[User] Show the symbol, name, and total supply for all SUI coins with status 'active'.

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

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

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

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

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

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


[User] Provide a list of all vehicles and the total quantity of fuel refueled for each vehicle.

[Assistant] SELECT T1.license_plate, sum(T2.quantity) FROM transportation.vehicles AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id = T2.vehicle_id GROUP BY T1.license_plate

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )


[User] List all patients who have non-primary insurance plans from providers containing 'Care' in their name, including the policy number and expiration date.

[Assistant] SELECT pi.patient_id, pi.policy_number, pi.expiration_date FROM healthcare.patient_insurance pi JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE pi.is_primary = false AND ip.insurance_provider LIKE '%Care%';

[User] Actually, I need to see only those plans that will expire within the next 90 days.

[Assistant] SELECT pi.patient_id, pi.policy_number, pi.expiration_date FROM healthcare.patient_insurance pi JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE pi.is_primary = false AND ip.insurance_provider LIKE '%Care%' AND pi.expiration_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '90 days');

[User] Can you also include the insurance provider name in the results?

[Assistant] SELECT pi.patient_id, ip.insurance_provider, pi.policy_number, pi.expiration_date FROM healthcare.patient_insurance pi JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE pi.is_primary = false AND ip.insurance_provider LIKE '%Care%' AND pi.expiration_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 healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)