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 erc20_balances ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE nft_holders (
    block_number bigint NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract(with bloom filter)
    token_id varchar NOT NULL, -- NFT token id
    contract_type varchar NOT NULL, -- NFT contract type
    amount varchar NOT NULL, -- Number of held NFTs
    pk varchar NOT NULL  -- The last string partition of the contract.
)
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    name varchar NOT NULL, -- name fields for the functionType  in contract
    symbol varchar NOT NULL, -- symbol fields for the functionType  in contract
    deploy_block_number bigint NOT NULL, -- deploy_block_number fields for the functionType  in contract
    deploy_block_time bigint NOT NULL, -- deploy_block_time fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    description varchar NOT NULL, -- description fields for the functionType  in contract
    slug varchar NOT NULL, -- slug fields for the functionType  in contract
    media_info varchar NOT NULL, -- media_info fields for the functionType  in contract
    image_url varchar NOT NULL, -- image_url fields for the functionType  in contract
    banner_image_url varchar NOT NULL, -- banner_image_url fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    banner varchar NOT NULL, -- banner fields for the functionType  in contract
    token_count bigint NOT NULL, -- token_count fields for the functionType  in contract
    floor_price varchar NOT NULL, -- floor_price fields for the functionType  in contract
    floor_price_symbol varchar NOT NULL, -- floor_price_symbol fields for the functionType  in contract
    floor_price_contract varchar NOT NULL, -- floor_price_contract fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(deploy_block_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.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 varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )

[User] Which wallets currently hold more than 200 units of ERC1155 NFTs on the Ethereum blockchain? Show the contract address, token ID, wallet address, and amount.

[Assistant]
SELECT nh.contract_address, nh.token_id, nh.wallet_address, nh.amount
FROM nft_holders nh
WHERE nh.contract_type = 'ERC1155'
  AND nh.amount::numeric > 200
  AND EXISTS (
    SELECT 1 FROM nft_collections nc
    WHERE nc.contract_address = nh.contract_address AND nc.blockchain = 'Ethereum'
  );

[User] Add the collection name for each NFT by joining with nft_collections.

[Assistant]
SELECT nh.contract_address, nh.token_id, nh.wallet_address, nh.amount, nc.name AS collection_name
FROM nft_holders nh
JOIN nft_collections nc
  ON nh.contract_address = nc.contract_address AND nc.blockchain = 'Ethereum'
WHERE nh.contract_type = 'ERC1155'
  AND nh.amount::numeric > 200;

[User] Only include results where the collection's deploy_block_number is after 13000000.

[Assistant]
SELECT nh.contract_address, nh.token_id, nh.wallet_address, nh.amount, nc.name AS collection_name
FROM nft_holders nh
JOIN nft_collections nc
  ON nh.contract_address = nc.contract_address AND nc.blockchain = 'Ethereum'
WHERE nh.contract_type = 'ERC1155'
  AND nh.amount::numeric > 200
  AND nc.deploy_block_number > 13000000;

[User] Also add the rarity score for each NFT from nft_metadata.

[Assistant]
SELECT nh.contract_address, nh.token_id, nh.wallet_address, nh.amount, nc.name AS collection_name, nm.rarity_score
FROM nft_holders nh
JOIN nft_collections nc
  ON nh.contract_address = nc.contract_address AND nc.blockchain = 'Ethereum'
LEFT JOIN nft_metadata nm
  ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id AND nm.blockchain = 'Ethereum'
WHERE nh.contract_type = 'ERC1155'
  AND nh.amount::numeric > 200
  AND nc.deploy_block_number > 13000000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)

[User] Find employees who were hired after their managers. Display the employee's full name, their hire date, the manager's full name, and the manager's hire date.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, e.hire_date AS employee_hire_date, m.first_name || ' ' || m.last_name AS manager_name, m.hire_date AS manager_hire_date FROM government_services.employees e JOIN government_services.employees m ON e.manager_employee_id = m.employee_id WHERE e.hire_date > m.hire_date;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )

[User] Can you retrieve the document_id, file_name, file_size_bytes, uploaded_at, and the full name of the agent (first and last name concatenated) for all documents uploaded in 2024 by active agents licensed in CA?

[Assistant] SELECT cd.document_id, cd.file_name, cd.file_size_bytes, cd.uploaded_at, a.first_name || ' ' || a.last_name AS agent_full_name FROM insurance.claim_documents cd JOIN insurance.agents a ON cd.uploaded_by = a.agent_id WHERE a.license_state = 'CA' AND a.status = 'Active' AND cd.uploaded_at BETWEEN '2024-01-01' AND '2024-12-31';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.payments ( payment_id text PRIMARY KEY, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] Show me the total payment amount made by each guest, including their guest_id and full name.

[Assistant]
SELECT g.guest_id, g.first_name || ' ' || g.last_name AS full_name, SUM(p.amount) AS total_paid
FROM hospitality_technology.guests g
JOIN hospitality_technology.payments p ON g.guest_id = p.guest_id
GROUP BY g.guest_id, full_name;

[User] Only include guests whose total payment amount exceeds 1000.

[Assistant]
SELECT g.guest_id, g.first_name || ' ' || g.last_name AS full_name, SUM(p.amount) AS total_paid
FROM hospitality_technology.guests g
JOIN hospitality_technology.payments p ON g.guest_id = p.guest_id
GROUP BY g.guest_id, full_name
HAVING SUM(p.amount) > 1000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.token_transfers (
    transfer_id 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 pairs of distinct token transfers that occurred in the same transaction and were initiated by the same sender address. List the transaction ID, the common sender address, and both transfer IDs.

[Assistant]
SELECT
  t1.transaction_id,
  t1.from_address,
  t1.transfer_id AS transfer_id_1,
  t2.transfer_id AS transfer_id_2
FROM web3.token_transfers AS t1
JOIN web3.token_transfers AS t2
  ON t1.transaction_id = t2.transaction_id
  AND t1.from_address = t2.from_address
WHERE
  t1.transfer_id < t2.transfer_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )

[User] Can you give me the number of available services and their average price for each department?

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

[User] I want the result to only include departments where the average price is above 80.

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

[User] Also, show the minimum and maximum price of available services for each of those departments.

[Assistant]
SELECT department, COUNT(*) AS available_services_count, AVG(price) AS average_price, MIN(price) AS min_price, MAX(price) AS max_price
FROM hospitality_technology.services
WHERE is_available = TRUE
GROUP BY department
HAVING AVG(price) > 80;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
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 NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata ( object_id varchar NOT NULL, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    token_id varchar NOT NULL, -- The number of the token
    contract_name varchar NOT NULL, -- contract_name fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    amount bigint NOT NULL, -- amount fields for the functionType  in contract
    minter varchar NOT NULL, -- minter fields for the functionType  in contract
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    mint_block_number bigint NOT NULL, -- mint_block_number fields for the functionType  in contract
    mint_time bigint NOT NULL, -- mint_time fields for the functionType  in contract
    mint_transaction_hash varchar NOT NULL, -- mint_transaction_hash fields for the functionType  in contract
    mint_price varchar NOT NULL, -- mint_price fields for the functionType  in contract
    token_uri varchar NOT NULL, -- token_uri fields for the functionType  in contract
    metadata varchar NOT NULL, -- metadata fields for the functionType  in contract
    name varchar NOT NULL, -- name fields for the functionType  in contract
    image_uri varchar NOT NULL, -- image_uri fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    status varchar NOT NULL, -- status fields for the functionType  in contract
    rarity_score real NOT NULL, -- rarity_score fields for the functionType  in contract
    rarity_rank integer NOT NULL, -- rarity_rank fields for the functionType  in contract
    unique_attribute_count integer NOT NULL, -- unique_attribute_count fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(mint_time / 1000 / 86400 / 30))
)
CREATE TABLE nft_collections ( blockchain.text, contract_address.text, name.text, symbol.text, deploy_block_number.bigint, deploy_block_time.bigint, erc_type.text, owner.text, traits.text, description.text, slug.text, media_info.text, image_url.text, banner_image_url.text, updated_at.bigint, banner.text, token_count.bigint, floor_price.text, floor_price_symbol.text, floor_price_contract.text, pk.integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_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 varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_bitcoin (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(255) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities_bitcoin (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(62) NOT NULL, -- Address sending the inscription
    to_address varchar(62) NOT NULL  -- Address receiving the inscription
)
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(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )

[User] List all ERC721 collections with their names, symbols, and floor prices where the floor price is greater than 0.1 ETH.

[Assistant] SELECT name, symbol, floor_price FROM nft_collections WHERE erc_type = 'ERC721' AND CAST(floor_price AS decimal) > 0.1;

[User] I think there's an error in your query - it should be CAST(floor_price AS decimal) not CAST(floor_price AS decimal). Also, can you include the banner image URL for these collections?

[Assistant] SELECT name, symbol, floor_price, banner_image_url FROM nft_collections WHERE erc_type = 'ERC721' AND CAST(floor_price AS decimal) > 0.1;

[User] Now sort these results by floor price in descending order and limit to the top 10.

[Assistant] SELECT name, symbol, floor_price, banner_image_url FROM nft_collections WHERE erc_type = 'ERC721' AND CAST(floor_price AS decimal) > 0.1 ORDER BY CAST(floor_price AS decimal) DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )

[User] Which users have commented on posts created by the users they follow? Please show the commenter user_ids and the followed user_ids.

[Assistant] SELECT DISTINCT c.user_id AS commenter_user_id, f.following_user_id AS followed_user_id FROM social_media.comments c JOIN social_media.follows f ON c.user_id = f.follower_user_id AND c.post_id IN (SELECT post_id FROM social_media.comments WHERE user_id = f.following_user_id);

[User] Can you also include the post_id in the results?

[Assistant] SELECT DISTINCT c.user_id AS commenter_user_id, f.following_user_id AS followed_user_id, c.post_id FROM social_media.comments c JOIN social_media.follows f ON c.user_id = f.follower_user_id AND c.post_id IN (SELECT post_id FROM social_media.comments WHERE user_id = f.following_user_id);


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id character varying(64) NOT NULL, follower_user_id character varying(64) NOT NULL, following_user_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (follow_id), CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
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 character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] Show the number of followers for each user who is following others, listing their user_id and follower count.

[Assistant]
SELECT following_user_id AS user_id, COUNT(follower_user_id) AS follower_count
FROM social_media.follows
GROUP BY following_user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] Calculate the total number of drivers for each status.

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

[User] Now only include statuses with more than 10 drivers.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] List each patient's active insurance policy and the number of prescriptions they have during that policy. Show patient_id, plan_id, policy_number, and prescription_count.

[Assistant]
SELECT pi.patient_id, pi.plan_id, pi.policy_number, COUNT(p.prescription_id) AS prescription_count
FROM healthcare.patient_insurance pi
LEFT JOIN healthcare.prescriptions p
  ON pi.patient_id = p.patient_id
  AND DATE(p.prescription_date) BETWEEN pi.effective_date AND COALESCE(pi.expiration_date, CURRENT_DATE)
GROUP BY pi.patient_id, pi.plan_id, pi.policy_number;

[User] Only include patients with more than 5 prescriptions.

[Assistant]
SELECT pi.patient_id, pi.plan_id, pi.policy_number, COUNT(p.prescription_id) AS prescription_count
FROM healthcare.patient_insurance pi
LEFT JOIN healthcare.prescriptions p
  ON pi.patient_id = p.patient_id
  AND DATE(p.prescription_date) BETWEEN pi.effective_date AND COALESCE(pi.expiration_date, CURRENT_DATE)
GROUP BY pi.patient_id, pi.plan_id, pi.policy_number
HAVING COUNT(p.prescription_id) > 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.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 the number of trips and the average passenger count per vehicle.

[Assistant]
SELECT v.vehicle_id, COUNT(t.trip_id) AS trip_count, AVG(t.passenger_count) AS avg_passenger_count
FROM transportation.vehicles v
LEFT JOIN transportation.trips t ON v.vehicle_id = t.vehicle_id
GROUP BY v.vehicle_id;

[User] Only include vehicles that have transported more than 50 passengers in total.

[Assistant]
SELECT v.vehicle_id, COUNT(t.trip_id) AS trip_count, AVG(t.passenger_count) AS avg_passenger_count, SUM(t.passenger_count) AS total_passengers
FROM transportation.vehicles v
LEFT JOIN transportation.trips t ON v.vehicle_id = t.vehicle_id
GROUP BY v.vehicle_id
HAVING SUM(t.passenger_count) > 50;

[User] Can you add the vehicle make and model to the result?

[Assistant]
SELECT v.vehicle_id, v.make, v.model, COUNT(t.trip_id) AS trip_count, AVG(t.passenger_count) AS avg_passenger_count, SUM(t.passenger_count) AS total_passengers
FROM transportation.vehicles v
LEFT JOIN transportation.trips t ON v.vehicle_id = t.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model
HAVING SUM(t.passenger_count) > 50;

[User] I am getting null for total_passengers for some vehicles, can you exclude vehicles with no trips?

[Assistant]
SELECT v.vehicle_id, v.make, v.model, COUNT(t.trip_id) AS trip_count, AVG(t.passenger_count) AS avg_passenger_count, SUM(t.passenger_count) AS total_passengers
FROM transportation.vehicles v
JOIN transportation.trips t ON v.vehicle_id = t.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model
HAVING SUM(t.passenger_count) > 50;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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)
)
CREATE TABLE financial_services.market_data (
    data_point_id bigserial NOT NULL, -- auto-incrementing primary key
    security_id character varying(64) NOT NULL, -- identifier for the security
    data_timestamp timestamp NOT NULL, -- timestamp for the data point (e.g., end of day, intraday)
    open_price numeric(19, 8), -- opening price for the period
    high_price numeric(19, 8), -- highest price during the period
    low_price numeric(19, 8), -- lowest price during the period
    close_price numeric(19, 8) NOT NULL, -- closing price for the period
    adjusted_close_price numeric(19, 8), -- closing price adjusted for dividends and splits
    volume bigint, -- trading volume during the period
    source character varying(50), -- source of the market data (e.g., Bloomberg, Refinitiv)
    PRIMARY KEY (data_point_id),
    UNIQUE (security_id, data_timestamp), -- Ensure unique data point per security per time
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)

[User] List the ticker_symbol and average close price for all securities of type 'ETF'.

[Assistant]
SELECT s.ticker_symbol, AVG(md.close_price) AS avg_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.security_type = 'ETF'
GROUP BY s.ticker_symbol;

[User] Sort the result by average close price descending.

[Assistant]
SELECT s.ticker_symbol, AVG(md.close_price) AS avg_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.security_type = 'ETF'
GROUP BY s.ticker_symbol
ORDER BY avg_close_price DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.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) )
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.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    application_id character varying(64), -- FK to applications table (optional)
    message_subject character varying(255),
    message_body text NOT NULL,
    channel character varying(30) NOT NULL, -- e.g., Email, SMS, Portal Message, Mail
    sent_at timestamp NOT NULL,
    status character varying(30) NOT NULL, -- e.g., Queued, Sent, Delivered, Failed, Read
    related_entity_type character varying(50), -- e.g., Application, Appointment, Document Request
    related_entity_id character varying(64), -- ID of the related entity
    PRIMARY KEY (notification_id)
)

[User] List all job titles of employees who work in the 'Finance' department.

[Assistant]
SELECT DISTINCT job_title
FROM government_services.employees
WHERE department = 'Finance';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, 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] For each notification, list its notification_id, message_subject, and the message_subject of the notification it relates to (assuming related_entity_type = 'notification').

[Assistant]
SELECT n.notification_id,
       n.message_subject,
       parent.message_subject AS related_message_subject
FROM government_services.notifications n
LEFT JOIN government_services.notifications parent
  ON n.related_entity_type = 'notification'
 AND n.related_entity_id = parent.notification_id;

[User] Only include notifications with status = 'Sent'.

[Assistant]
SELECT n.notification_id,
       n.message_subject,
       parent.message_subject AS related_message_subject
FROM government_services.notifications n
LEFT JOIN government_services.notifications parent
  ON n.related_entity_type = 'notification'
 AND n.related_entity_id = parent.notification_id
WHERE n.status = 'Sent';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
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 )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] List all agents who have a commission rate above 0.1, showing their full names and agency names.

[Assistant] SELECT agent_id, first_name, last_name, agency_name, commission_rate FROM insurance.agents WHERE commission_rate > 0.1 AND status = 'active';

[User] Now include only agents who were hired in the last 2 years.

[Assistant] SELECT agent_id, first_name, last_name, agency_name, commission_rate, hire_date FROM insurance.agents WHERE commission_rate > 0.1 AND status = 'active' AND hire_date >= CURRENT_DATE - INTERVAL '2 years';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.market_data (
    data_point_id bigserial NOT NULL, -- auto-incrementing primary key
    security_id character varying(64) NOT NULL, -- identifier for the security
    data_timestamp timestamp NOT NULL, -- timestamp for the data point (e.g., end of day, intraday)
    open_price numeric(19, 8), -- opening price for the period
    high_price numeric(19, 8), -- highest price during the period
    low_price numeric(19, 8), -- lowest price during the period
    close_price numeric(19, 8) NOT NULL, -- closing price for the period
    adjusted_close_price numeric(19, 8), -- closing price adjusted for dividends and splits
    volume bigint, -- trading volume during the period
    source character varying(50), -- source of the market data (e.g., Bloomberg, Refinitiv)
    PRIMARY KEY (data_point_id),
    UNIQUE (security_id, data_timestamp), -- Ensure unique data point per security per time
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)

[User] For each security sector, what is the average volume recorded in the market data?

[Assistant] SELECT T2.sector, AVG(T1.volume) FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id GROUP BY T2.sector;

[User] Can you restrict this to data points from the last 6 months?

[Assistant] SELECT T2.sector, AVG(T1.volume) FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= NOW() - INTERVAL '6 months' GROUP BY T2.sector;

[User] Also include the count of data points per sector in the result.

[Assistant] SELECT T2.sector, AVG(T1.volume), COUNT(T1.data_point_id) FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= NOW() - INTERVAL '6 months' GROUP BY T2.sector;

[User] Filter out sectors with fewer than 1000 data points in this period.

[Assistant] SELECT T2.sector, AVG(T1.volume), COUNT(T1.data_point_id) FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= NOW() - INTERVAL '6 months' GROUP BY T2.sector HAVING COUNT(T1.data_point_id) >= 1000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] Show the total revenue and the average order value for each order status.

[Assistant] SELECT status, SUM(total_price) AS total_revenue, AVG(total_price) AS avg_order_value FROM hospitality_technology.service_orders GROUP BY status;

[User] Please only include statuses where the total revenue is above 1000.

[Assistant] SELECT status, SUM(total_price) AS total_revenue, AVG(total_price) AS avg_order_value FROM hospitality_technology.service_orders GROUP BY status HAVING SUM(total_price) > 1000;

[User] Also order the results by total revenue descending.

[Assistant] SELECT status, SUM(total_price) AS total_revenue, AVG(total_price) AS avg_order_value FROM hospitality_technology.service_orders GROUP BY status HAVING SUM(total_price) > 1000 ORDER BY total_revenue DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )

[User] How many insurance policies does each subscriber have? Please display the subscriber name and policy count.

[Assistant] SELECT subscriber_name, COUNT(*) AS policy_count FROM healthcare.patient_insurance GROUP BY subscriber_name;

[User] Please include only subscribers who have more than one policy.

[Assistant] SELECT subscriber_name, COUNT(*) AS policy_count FROM healthcare.patient_insurance GROUP BY subscriber_name HAVING COUNT(*) > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] Which room types have a base rate above 250, and what are their property names and maximum occupancy?

[Assistant]
SELECT rt.room_type_id, rt.type_name, p.property_name, rt.base_rate, rt.max_occupancy
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
WHERE rt.base_rate > 250;

[User] I only want to see room types with a maximum occupancy greater than 2.

[Assistant]
SELECT rt.room_type_id, rt.type_name, p.property_name, rt.base_rate, rt.max_occupancy
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
WHERE rt.base_rate > 250 AND rt.max_occupancy > 2;

[User] Also include the bed type and the area in square feet for each room type.

[Assistant]
SELECT rt.room_type_id, rt.type_name, p.property_name, rt.base_rate, rt.max_occupancy, rt.bed_type, rt.area_sqft
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
WHERE rt.base_rate > 250 AND rt.max_occupancy > 2;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.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.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, 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] List the city and the count of accessible and inaccessible service locations separately. Return city, accessible_count, and inaccessible_count.

[Assistant]
SELECT city,
       SUM(CASE WHEN is_accessible THEN 1 ELSE 0 END) AS accessible_count,
       SUM(CASE WHEN is_accessible = false THEN 1 ELSE 0 END) AS inaccessible_count
FROM government_services.service_locations
GROUP BY city;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )

[User] Find all pairs of origin and destination cities, along with their route_number and distance, where the estimated duration is less than 90 minutes.

[Assistant] SELECT route_number, origin_location_id, destination_location_id, distance_km FROM transportation.routes WHERE estimated_duration_minutes < 90;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id.uuid, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
CREATE TABLE gaming_technology.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.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(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )

[User] List each game's title along with the name of the developer and the total number of servers currently hosting that game.

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

[User] Can you include the number of online servers for each game as well?

[Assistant]
SELECT g.title, g.developer_id,
       COUNT(s.server_id) AS total_servers,
       SUM(CASE WHEN s.status = 'online' THEN 1 ELSE 0 END) AS online_servers
FROM gaming_technology.games g
LEFT JOIN gaming_technology.servers s ON g.game_id = s.game_id
GROUP BY g.title, g.developer_id;

[User] I need to see the actual developer names, not just developer_id.

[Assistant]
SELECT g.title, d.name AS developer_name,
       COUNT(s.server_id) AS total_servers,
       SUM(CASE WHEN s.status = 'online' THEN 1 ELSE 0 END) AS online_servers
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
LEFT JOIN gaming_technology.servers s ON g.game_id = s.game_id
GROUP BY g.title, d.name;

[User] Only show games that have at least 2 online servers, and order by online_servers descending.

[Assistant]
SELECT g.title, d.name AS developer_name,
       COUNT(s.server_id) AS total_servers,
       SUM(CASE WHEN s.status = 'online' THEN 1 ELSE 0 END) AS online_servers
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
LEFT JOIN gaming_technology.servers s ON g.game_id = s.game_id
GROUP BY g.title, d.name
HAVING SUM(CASE WHEN s.status = 'online' THEN 1 ELSE 0 END) >= 2
ORDER BY online_servers DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )

[User] List `user_id` and `conversation_id` for participants who are in conversations where there is at least one message sent by *another* user that they have not read.

[Assistant] SELECT DISTINCT T1.user_id, T1.conversation_id FROM social_media.conversation_participants AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T2.sender_user_id != T1.user_id AND (T1.last_read_at IS NULL OR T2.sent_at > T1.last_read_at);


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)

[User] List the record ID, record date, patient ID, and chief complaint for medical records belonging to patients whose last name is 'Smith'. Also include the patient's last name in the results.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, mr.chief_complaint, p.last_name FROM healthcare.medical_records mr JOIN patients p ON mr.patient_id = p.patient_id WHERE p.last_name = 'Smith';

[User] Refine this list to only show records where the record date is in 2024 and the chief complaint is not null. Sort by record_date in ascending order.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, mr.chief_complaint, p.last_name FROM healthcare.medical_records mr JOIN patients p ON mr.patient_id = p.patient_id WHERE p.last_name = 'Smith' AND EXTRACT(YEAR FROM mr.record_date) = 2024 AND (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') ORDER BY mr.record_date ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )

[User] List the name of each agency and the number of appointments associated with services from that agency.

[Assistant] SELECT T1.agency_name, COUNT(T2.appointment_id) FROM agencies AS T1 JOIN appointments AS T2 ON T1.agency_id = T2.agency_id GROUP BY T1.agency_name;


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

[User] I need to compare consecutive daily close_prices for each security to find when the close_price increased compared to the previous day.

[Assistant]
SELECT a.security_id, b.data_timestamp AS prev_date, b.close_price AS prev_close, a.data_timestamp AS curr_date, a.close_price AS curr_close
FROM financial_services.market_data a
JOIN financial_services.market_data b
  ON a.security_id = b.security_id
  AND CAST(a.data_timestamp AS date) = CAST(b.data_timestamp + INTERVAL '1 day' AS date)
WHERE a.close_price > b.close_price;

[User] Now, restrict this to only securities whose average volume over the past 30 days exceeds 1,000,000.

[Assistant]
WITH high_vol AS (
  SELECT security_id
  FROM financial_services.market_data
  WHERE data_timestamp >= NOW() - INTERVAL '30 days'
  GROUP BY security_id
  HAVING AVG(volume) > 1000000
)
SELECT a.security_id, b.data_timestamp AS prev_date, b.close_price AS prev_close, a.data_timestamp AS curr_date, a.close_price AS curr_close
FROM financial_services.market_data a
JOIN financial_services.market_data b
  ON a.security_id = b.security_id
  AND CAST(a.data_timestamp AS date) = CAST(b.data_timestamp + INTERVAL '1 day' AS date)
JOIN high_vol h
  ON a.security_id = h.security_id
WHERE a.close_price > b.close_price;

[User] Also, only include those increases where the percentage change between days is greater than 2%.

[Assistant]
WITH high_vol AS (
  SELECT security_id
  FROM financial_services.market_data
  WHERE data_timestamp >= NOW() - INTERVAL '30 days'
  GROUP BY security_id
  HAVING AVG(volume) > 1000000
)
SELECT a.security_id,
       b.data_timestamp AS prev_date,
       b.close_price AS prev_close,
       a.data_timestamp AS curr_date,
       a.close_price AS curr_close,
       ROUND((a.close_price - b.close_price) / b.close_price * 100, 2) AS pct_change
FROM financial_services.market_data a
JOIN financial_services.market_data b
  ON a.security_id = b.security_id
  AND CAST(a.data_timestamp AS date) = CAST(b.data_timestamp + INTERVAL '1 day' AS date)
JOIN high_vol h
  ON a.security_id = h.security_id
WHERE (a.close_price - b.close_price) / b.close_price * 100 > 2;

[User] Finally, add the adjusted_close_price for both current and previous days to the result.

[Assistant]
WITH high_vol AS (
  SELECT security_id
  FROM financial_services.market_data
  WHERE data_timestamp >= NOW() - INTERVAL '30 days'
  GROUP BY security_id
  HAVING AVG(volume) > 1000000
)
SELECT a.security_id,
       b.data_timestamp AS prev_date,
       b.close_price AS prev_close,
       b.adjusted_close_price AS prev_adj_close,
       a.data_timestamp AS curr_date,
       a.close_price AS curr_close,
       a.adjusted_close_price AS curr_adj_close,
       ROUND((a.close_price - b.close_price) / b.close_price * 100, 2) AS pct_change
FROM financial_services.market_data a
JOIN financial_services.market_data b
  ON a.security_id = b.security_id
  AND CAST(a.data_timestamp AS date) = CAST(b.data_timestamp + INTERVAL '1 day' AS date)
JOIN high_vol h
  ON a.security_id = h.security_id
WHERE (a.close_price - b.close_price) / b.close_price * 100 > 2;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] List all insurance plans along with their provider, plan type, and the contact phone number. Also, for each plan, show how many doctors have their hospital affiliation ID matching the plan ID.

[Assistant] SELECT ip.plan_id, ip.plan_name, ip.insurance_provider, ip.plan_type, ip.contact_phone, COUNT(d.doctor_id) FROM healthcare.insurance_plans ip LEFT JOIN healthcare.doctors d ON ip.plan_id = d.hospital_affiliation_id GROUP BY ip.plan_id, ip.plan_name, ip.insurance_provider, ip.plan_type, ip.contact_phone


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)

[User] Retrieve trip_id and passenger full names for all trips where the passenger record was created before the scheduled departure.

[Assistant]
SELECT t.trip_id, p.first_name || ' ' || p.last_name AS passenger_name
FROM transportation.trips t
JOIN transportation.passengers p
  ON p.created_at < t.scheduled_departure;

[User] Filter the results to only include trips with passenger_count greater than 5.

[Assistant]
SELECT t.trip_id, t.passenger_count, p.first_name || ' ' || p.last_name AS passenger_name
FROM transportation.trips t
JOIN transportation.passengers p
  ON p.created_at < t.scheduled_departure
WHERE t.passenger_count > 5;

[User] Also sort the output by passenger_count descending and limit to the top 10 records.

[Assistant]
SELECT t.trip_id, t.passenger_count, p.first_name || ' ' || p.last_name AS passenger_name
FROM transportation.trips t
JOIN transportation.passengers p
  ON p.created_at < t.scheduled_departure
WHERE t.passenger_count > 5
ORDER BY t.passenger_count DESC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id text, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text )
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )
CREATE TABLE web3.tokens ( token_id text, contract_address text, token_name text, token_symbol text, decimals integer, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )

[User] Which user has created the most tokens? Please show the username and the number of tokens they have created.

[Assistant]
SELECT u.username, COUNT(*) AS token_count
FROM web3.tokens t
JOIN web3.contracts c ON t.contract_address = c.address
JOIN web3.wallets w ON c.deployer_address = w.address
JOIN web3.users u ON w.user_id = u.user_id
GROUP BY u.username
ORDER BY token_count DESC
LIMIT 1;

[User] Actually, show all users and the number of tokens they have created, ordered from most to least.

[Assistant]
SELECT u.username, COUNT(*) AS token_count
FROM web3.tokens t
JOIN web3.contracts c ON t.contract_address = c.address
JOIN web3.wallets w ON c.deployer_address = w.address
JOIN web3.users u ON w.user_id = u.user_id
GROUP BY u.username
ORDER BY token_count DESC;


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

[User] List all pairs of fuel log entries for the same vehicle that occurred more than 7 days apart, showing vehicle_id, first_log_id, second_log_id, and the time difference in days.

[Assistant]
SELECT f1.vehicle_id,
       f1.fuel_log_id AS first_log_id,
       f2.fuel_log_id AS second_log_id,
       EXTRACT(EPOCH FROM (f2.log_timestamp - f1.log_timestamp))/86400 AS days_difference
FROM transportation.fuel_logs f1
JOIN transportation.fuel_logs f2
  ON f1.vehicle_id = f2.vehicle_id
 AND f2.log_timestamp > f1.log_timestamp + INTERVAL '7 days';

[User] Now filter to only include pairs where the quantity increased by at least 50 units.

[Assistant]
SELECT f1.vehicle_id,
       f1.fuel_log_id AS first_log_id,
       f2.fuel_log_id AS second_log_id,
       EXTRACT(EPOCH FROM (f2.log_timestamp - f1.log_timestamp))/86400 AS days_difference
FROM transportation.fuel_logs f1
JOIN transportation.fuel_logs f2
  ON f1.vehicle_id = f2.vehicle_id
 AND f2.log_timestamp > f1.log_timestamp + INTERVAL '7 days'
WHERE (f2.quantity - f1.quantity) >= 50;

[User] Also display the difference in total_cost between the two logs.

[Assistant]
SELECT f1.vehicle_id,
       f1.fuel_log_id AS first_log_id,
       f2.fuel_log_id AS second_log_id,
       EXTRACT(EPOCH FROM (f2.log_timestamp - f1.log_timestamp))/86400 AS days_difference,
       (f2.quantity - f1.quantity)      AS quantity_difference,
       (f2.total_cost - f1.total_cost)  AS cost_difference
FROM transportation.fuel_logs f1
JOIN transportation.fuel_logs f2
  ON f1.vehicle_id = f2.vehicle_id
 AND f2.log_timestamp > f1.log_timestamp + INTERVAL '7 days'
WHERE (f2.quantity - f1.quantity) >= 50;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)

[User] Show me all users along with the total number of unique hashtags used in their posts.

[Assistant]
SELECT u.user_id, u.username, COUNT(DISTINCT ph.hashtag_id) AS unique_hashtag_count
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
LEFT JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
GROUP BY u.user_id, u.username;

[User] Can you include only the users who have used more than 2 unique hashtags?

[Assistant]
SELECT u.user_id, u.username, COUNT(DISTINCT ph.hashtag_id) AS unique_hashtag_count
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
LEFT JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
GROUP BY u.user_id, u.username
HAVING COUNT(DISTINCT ph.hashtag_id) > 2;


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

[User] 特定の組み立てラインに割り当てられた従業員とそのラインの手順情報を取得したいです。従業員ID、名前、職種と手順名、手順番号を含めてください。

[Assistant]
db.employees.aggregate([
    { $match: { assigned_line_id: '<specific_line_id>' } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { 'steps.step_number': 1 } }
])

[User] 従業員の雇用ステータスが「Active」のデータだけに絞り込むことはできますか？

[Assistant]
db.employees.aggregate([
    { $match: {
        assigned_line_id: '<specific_line_id>',
        employment_status: 'Active'
    } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { 'steps.step_number': 1 } }
])

[User] 手順の必要なスキルレベルが「Junior Technician」以上のものだけを表示するようにできますか？

[Assistant]
db.employees.aggregate([
    { $match: {
        assigned_line_id: '<specific_line_id>',
        employment_status: 'Active'
    } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $match: { 'steps.required_skill_level': { $in: ['Junior Technician', 'Senior Technician'] } } },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { 'steps.step_number': 1 } }
])

[User] 最後に、従業員の雇用日も結果に含めて、雇用日順に並べ替えてください。

[Assistant]
db.employees.aggregate([
    { $match: {
        assigned_line_id: '<specific_line_id>',
        employment_status: 'Active'
    } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $match: { 'steps.required_skill_level': { $in: ['Junior Technician', 'Senior Technician'] } } },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        hire_date: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { hire_date: -1, 'steps.step_number': 1 } }
])


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)

[User] List all appointments, including their subject and start time, along with the name and status of the case they are linked to.

[Assistant] SELECT T1.subject, T1.start_time, T2.case_name, T2.status FROM appointments AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.likes ( like_id text, user_id text, post_id text, comment_id text, created_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.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.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )

[User] How many comments does each post have? Return post_id and comment_count for posts with more than 5 comments.

[Assistant]
SELECT post_id,
       COUNT(*) AS comment_count
FROM social_media.comments
GROUP BY post_id
HAVING COUNT(*) > 5;