System:
You are very professional for database language writing. 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.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id text 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.reviews (
    review_id character varying(64) NOT NULL,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    PRIMARY KEY (review_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id)
)

[User] Show me the list of all room numbers and their corresponding guest full names for current reservations (status is 'Occupied' or 'CheckedIn').

[Assistant]
SELECT r.room_number, g.first_name || ' ' || g.last_name AS guest_full_name
FROM hospitality_technology.reservations res
JOIN hospitality_technology.rooms r ON res.room_id = r.room_id
JOIN hospitality_technology.guests g ON res.guest_id = g.guest_id
WHERE res.status IN ('Occupied', 'CheckedIn');

[User] Add the property name to the result and sort the list by property name, then by room number.

[Assistant]
SELECT p.property_name, r.room_number, g.first_name || ' ' || g.last_name AS guest_full_name
FROM hospitality_technology.reservations res
JOIN hospitality_technology.rooms r ON res.room_id = r.room_id
JOIN hospitality_technology.guests g ON res.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE res.status IN ('Occupied', 'CheckedIn')
ORDER BY p.property_name, r.room_number;


System:
You are very professional for database language writing. 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.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)

[User] For each player, count the total number of achievements they've unlocked.

[Assistant]
SELECT player_id,
       COUNT(*) AS total_achievements
FROM gaming_technology.player_achievements
GROUP BY player_id;

[User] Exclude players with fewer than 10 achievements.

[Assistant]
SELECT player_id,
       COUNT(*) AS total_achievements
FROM gaming_technology.player_achievements
GROUP BY player_id
HAVING COUNT(*) >= 10;

[User] Additionally, provide the month when they achieved their 10th achievement. Show player_id, total_achievements, and the month of the 10th unlock.

[Assistant]
WITH ranked AS (
  SELECT player_id,
         unlocked_at,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at) AS rn
  FROM gaming_technology.player_achievements
),
counts AS (
  SELECT player_id,
         COUNT(*) AS total_achievements
  FROM gaming_technology.player_achievements
  GROUP BY player_id
  HAVING COUNT(*) >= 10
)
SELECT c.player_id,
       c.total_achievements,
       EXTRACT(MONTH FROM r.unlocked_at) AS tenth_achievement_month
FROM counts c
JOIN ranked r
  ON c.player_id = r.player_id
 AND r.rn = 10;

[User] Finally, order by total_achievements descending.

[Assistant]
WITH ranked AS (
  SELECT player_id,
         unlocked_at,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at) AS rn
  FROM gaming_technology.player_achievements
),
counts AS (
  SELECT player_id,
         COUNT(*) AS total_achievements
  FROM gaming_technology.player_achievements
  GROUP BY player_id
  HAVING COUNT(*) >= 10
)
SELECT c.player_id,
       c.total_achievements,
       EXTRACT(MONTH FROM r.unlocked_at) AS tenth_achievement_month
FROM counts c
JOIN ranked r
  ON c.player_id = r.player_id
 AND r.rn = 10
ORDER BY c.total_achievements DESC;


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )

[User] Show me a list of all customers from California along with their full names and phone numbers.

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number FROM insurance.customers WHERE state = 'CA';

[User] Can you also include their email addresses in the results?

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number, email FROM insurance.customers WHERE state = 'CA';

[User] Actually, show me only those customers whose status is 'active'.

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number, email FROM insurance.customers WHERE state = 'CA' AND status = 'active';


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )

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

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

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

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

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

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


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )

[User] Show me the username and registration date for players who do not have a last login recorded.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE last_login IS NULL;

[User] Also include their country code in the output.

[Assistant] SELECT username, registration_date, country_code FROM gaming_technology.players WHERE last_login IS NULL;

[User] Filter this list to only include players from the United Kingdom ('GB').

[Assistant] SELECT username, registration_date, country_code FROM gaming_technology.players WHERE last_login IS NULL AND country_code = 'GB';

[User] Order the results by their registration date, from oldest to newest.

[Assistant] SELECT username, registration_date, country_code FROM gaming_technology.players WHERE last_login IS NULL AND country_code = 'GB' ORDER BY registration_date ASC;


System:
You are very professional for database language writing. 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.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )

[User] Show me all trades (trade_id, security_id, total_amount) where the trade_type is 'Buy' and the execution_venue is 'NYSE', along with the loan details (loan_type, principal_amount) for accounts that have both trades and loans.

[Assistant] SELECT t.trade_id, t.security_id, t.total_amount, l.loan_type, l.principal_amount FROM financial_services.trades t JOIN financial_services.loans l ON t.account_id = l.account_id WHERE t.trade_type = 'Buy' AND t.execution_venue = 'NYSE';

[User] Now modify the query to only include trades with a total_amount greater than $10,000 and loans with a principal_amount greater than $50,000, sorted by total_amount in descending order.

[Assistant] SELECT t.trade_id, t.security_id, t.total_amount, l.loan_type, l.principal_amount FROM financial_services.trades t JOIN financial_services.loans l ON t.account_id = l.account_id WHERE t.trade_type = 'Buy' AND t.execution_venue = 'NYSE' AND t.total_amount > 10000 AND l.principal_amount > 50000 ORDER BY t.total_amount DESC;


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id character varying(64) NOT NULL, previous_block_id character varying(64), timestamp timestamp NOT NULL, nonce integer NOT NULL, merkle_root character varying(128) NOT NULL, difficulty integer NOT NULL, PRIMARY KEY (block_id) )

[User] Show me the block with the earliest timestamp and its corresponding previous block's difficulty level.

[Assistant] SELECT b1.block_id, b1.timestamp, b2.difficulty AS previous_block_difficulty FROM blockchain.blocks b1 LEFT JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id ORDER BY b1.timestamp ASC LIMIT 1;

[User] Now show me the same information but for the 5 earliest blocks instead of just one.

[Assistant] SELECT b1.block_id, b1.timestamp, b2.difficulty AS previous_block_difficulty FROM blockchain.blocks b1 LEFT JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id ORDER BY b1.timestamp ASC LIMIT 5;


System:
You are very professional for database language writing. 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 PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text PRIMARY KEY, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text PRIMARY KEY, post_id text, hashtag_id text )
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] Show all notifications of type 'comment' with the content of the corresponding comment and the author's username.

[Assistant]
SELECT n.notification_id,
       n.recipient_user_id,
       c.content AS comment_content,
       u.username
FROM social_media.notifications n
JOIN social_media.comments c
  ON n.target_entity_type = 'comment'
  AND n.target_entity_id = c.comment_id
JOIN social_media.users u
  ON c.user_id = u.user_id
WHERE n.notification_type = 'comment';

[User] Now restrict to notifications created within the last 7 days.

[Assistant]
SELECT n.notification_id,
       n.recipient_user_id,
       c.content AS comment_content,
       u.username
FROM social_media.notifications n
JOIN social_media.comments c
  ON n.target_entity_type = 'comment'
  AND n.target_entity_id = c.comment_id
JOIN social_media.users u
  ON c.user_id = u.user_id
WHERE n.notification_type = 'comment'
  AND n.created_at >= CURRENT_DATE - INTERVAL '7 days';


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )

[User] List all rooms with their latest review comment and the date of that review, showing the room number and property id.

[Assistant]
SELECT r.room_number, r.property_id, rv.comment, rv.review_date
FROM hospitality_technology.rooms r
LEFT JOIN hospitality_technology.reviews rv
  ON r.property_id = rv.property_id
WHERE rv.review_date = (
    SELECT MAX(rv2.review_date)
    FROM hospitality_technology.reviews rv2
    WHERE rv2.property_id = r.property_id
);

[User] Can you also include the overall rating in the result?

[Assistant]
SELECT r.room_number, r.property_id, rv.comment, rv.rating_overall, rv.review_date
FROM hospitality_technology.rooms r
LEFT JOIN hospitality_technology.reviews rv
  ON r.property_id = rv.property_id
WHERE rv.review_date = (
    SELECT MAX(rv2.review_date)
    FROM hospitality_technology.reviews rv2
    WHERE rv2.property_id = r.property_id
);

[User] Show only rooms located on the 2nd floor.

[Assistant]
SELECT r.room_number, r.property_id, rv.comment, rv.rating_overall, rv.review_date
FROM hospitality_technology.rooms r
LEFT JOIN hospitality_technology.reviews rv
  ON r.property_id = rv.property_id
WHERE r.floor = 2
  AND rv.review_date = (
    SELECT MAX(rv2.review_date)
    FROM hospitality_technology.reviews rv2
    WHERE rv2.property_id = r.property_id
);


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] Show reviews with an overall rating of 5, including the guest's full name and the property ID.

[Assistant] SELECT T1.first_name, T1.last_name, T2.property_id FROM hospitality_technology.guests AS T1 JOIN hospitality_technology.reviews AS T2 ON T1.guest_id = T2.guest_id WHERE T2.rating_overall = 5;

[User] Can you also include the review date and order the results by review date descending?

[Assistant] SELECT T1.first_name, T1.last_name, T2.property_id, T2.review_date FROM hospitality_technology.guests AS T1 JOIN hospitality_technology.reviews AS T2 ON T1.guest_id = T2.guest_id WHERE T2.rating_overall = 5 ORDER BY T2.review_date DESC;

[User] Actually, I only want reviews for properties with property IDs starting with 'P1' and where the review source is 'Online'.

[Assistant] SELECT T1.first_name, T1.last_name, T2.property_id, T2.review_date FROM hospitality_technology.guests AS T1 JOIN hospitality_technology.reviews AS T2 ON T1.guest_id = T2.guest_id WHERE T2.rating_overall = 5 AND T2.property_id LIKE 'P1%' AND T2.review_source = 'Online' ORDER BY T2.review_date DESC;


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.employees ( employee_id text, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )

[User] For each employee who acts as a manager, please show the number of employees directly reporting to them.

[Assistant] SELECT m.first_name || ' ' || m.last_name AS manager_name, COUNT(e.employee_id) AS direct_report_count FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id GROUP BY m.employee_id, manager_name;

[User] Include the department of the manager in the output as well.

[Assistant] SELECT m.first_name || ' ' || m.last_name AS manager_name, m.department, COUNT(e.employee_id) AS direct_report_count FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id GROUP BY m.employee_id, manager_name, m.department;

[User] Only list managers who have fewer than 10 direct reports.

[Assistant] SELECT m.first_name || ' ' || m.last_name AS manager_name, m.department, COUNT(e.employee_id) AS direct_report_count FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id GROUP BY m.employee_id, manager_name, m.department HAVING COUNT(e.employee_id) < 10;


System:
You are very professional for database language writing. 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.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.service_orders ( order_id text, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity integer, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )

[User] Get the count of service orders and total payment amount for each reservation.

[Assistant]
SELECT so.reservation_id,
       COUNT(*) AS order_count,
       SUM(p.amount) AS total_payment
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.payments p
  ON so.reservation_id = p.reservation_id
GROUP BY so.reservation_id
ORDER BY total_payment DESC;

[User] Actually, show only those reservations where the total number of service orders exceeds 3.

[Assistant]
SELECT so.reservation_id,
       COUNT(*) AS order_count,
       SUM(p.amount) AS total_payment
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.payments p
  ON so.reservation_id = p.reservation_id
GROUP BY so.reservation_id
HAVING COUNT(*) > 3
ORDER BY total_payment DESC;


System:
You are very professional for database language writing. 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.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )

[User] For each payment, list its payment_id, guest_id, payment_timestamp, and the next payment_id and next payment_timestamp made by the same guest.

[Assistant]
SELECT p.payment_id,
       p.guest_id,
       p.payment_timestamp,
       n.payment_id AS next_payment_id,
       n.payment_timestamp AS next_payment_timestamp
FROM hospitality_technology.payments p
LEFT JOIN hospitality_technology.payments n
  ON p.guest_id = n.guest_id
 AND n.payment_timestamp = (
       SELECT MIN(payment_timestamp)
       FROM hospitality_technology.payments
       WHERE guest_id = p.guest_id
         AND payment_timestamp > p.payment_timestamp
     );


System:
You are very professional for database language writing. 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.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )

[User] List the reference number and status for all applications, including the registration date of the citizen who submitted it.

[Assistant] SELECT a.reference_number, a.status, c.registration_date FROM government_services.applications AS a JOIN citizens AS c ON a.citizen_id = c.citizen_id;


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

[User] Give me the product name and description of all insurance products that have been updated in the last 30 days.

[Assistant] SELECT product_name, description FROM insurance.insurance_products WHERE updated_at >= NOW() - INTERVAL '30 days';


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] List all assets that have at least one associated metadata entry, showing the asset name, symbol, and the key and value of each metadata entry.

[Assistant] SELECT a.name, a.symbol, m.key, m.value FROM trading_platform.assets a JOIN trading_platform.metadata m ON a.asset_id = m.asset_id;

[User] Only show metadata entries where the metadata key contains the word 'link' or 'id'.

[Assistant] SELECT a.name, a.symbol, m.key, m.value FROM trading_platform.assets a JOIN trading_platform.metadata m ON a.asset_id = m.asset_id WHERE m.key ILIKE '%link%' OR m.key ILIKE '%id%';


System:
You are very professional for database language writing. 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.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] List the medication IDs and names for all entries where the description is missing or empty.

[Assistant] SELECT medication_id, medication_name FROM healthcare.medications WHERE description IS NULL OR description = '';

[User] For those medications, please also show the manufacturer and sort the results by medication name in ascending order.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE description IS NULL OR description = '' ORDER BY medication_name ASC;


System:
You are very professional for database language writing. 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 )

[User] Count the number of users whose location is 'London'.

[Assistant] SELECT count(*) FROM social_media.users WHERE location = 'London';


System:
You are very professional for database language writing. 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, 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.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )
CREATE TABLE government_services.notifications ( notification_id text 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] Show the first and last name of each citizen and the count of their scheduled appointments.

[Assistant] SELECT c.first_name, c.last_name, COUNT(a.appointment_id) AS scheduled_appointment_count FROM government_services.citizens AS c JOIN government_services.appointments AS a ON c.citizen_id = a.citizen_id WHERE a.status = 'Scheduled' GROUP BY c.citizen_id, c.first_name, c.last_name;

[User] Only include citizens who have more than 2 scheduled appointments.

[Assistant] SELECT c.first_name, c.last_name, COUNT(a.appointment_id) AS scheduled_appointment_count FROM government_services.citizens AS c JOIN government_services.appointments AS a ON c.citizen_id = a.citizen_id WHERE a.status = 'Scheduled' GROUP BY c.citizen_id, c.first_name, c.last_name HAVING COUNT(a.appointment_id) > 2;

[User] I got an error with that query. Let's simplify. Just show the first name, last name, and the total number of all appointments (regardless of status) for each citizen.

[Assistant] SELECT c.first_name, c.last_name, COUNT(a.appointment_id) AS total_appointment_count FROM government_services.citizens AS c JOIN government_services.appointments AS a ON c.citizen_id = a.citizen_id GROUP BY c.citizen_id, c.first_name, c.last_name;


System:
You are very professional for database language writing. 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.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.agents ( agent_id text 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 PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] List all policies where the premium_amount exceeds the base_premium of its insurance product. Display the policy_number, premium_amount, product_name, and base_premium. Sort the results by premium_amount descending.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
ORDER BY p.premium_amount DESC;

[User] Actually, I only want policies that are active and whose insurance products are also active.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'active'
  AND ip.is_active = TRUE
ORDER BY p.premium_amount DESC;

[User] Also, limit the output to policies with a coverage_limit greater than 1000000.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'active'
  AND ip.is_active = TRUE
  AND p.coverage_limit > 1000000
ORDER BY p.premium_amount DESC;


System:
You are very professional for database language writing. 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.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Show the first name, last name, and contact information for beneficiaries added before 2023.

[Assistant] SELECT first_name, last_name, contact_info FROM insurance.policy_beneficiaries WHERE added_at < '2023-01-01';

[User] Now, only include beneficiaries with a 'Child' relationship and add their percentage share to the output.

[Assistant] SELECT first_name, last_name, contact_info, percentage_share FROM insurance.policy_beneficiaries WHERE added_at < '2023-01-01' AND relationship = 'Child';


System:
You are very professional for database language writing. 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, 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 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.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees (
    employee_id 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 PRIMARY KEY, 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.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) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] Find currently employed employees whose direct manager has been terminated. Display the employee's full name, hire date, manager's full name, and manager's termination date.

[Assistant]
SELECT e.employee_id,
       CONCAT(e.first_name, ' ', e.last_name) AS employee_full_name,
       e.hire_date,
       CONCAT(m.first_name, ' ', m.last_name) AS manager_full_name,
       m.termination_date
FROM government_services.employees e
JOIN government_services.employees m ON e.manager_employee_id = m.employee_id
WHERE e.termination_date IS NULL
  AND m.termination_date IS NOT NULL;


System:
You are very professional for database language writing. 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.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.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )

[User] Show me a list of all appointment IDs, the name of the service associated with each appointment, and the location name where it is scheduled.

[Assistant]
SELECT appt.appointment_id, srv.service_id, loc.location_name
FROM government_services.appointments appt
JOIN government_services.service_locations loc ON appt.location_id = loc.location_id
JOIN government_services.applications appl ON appl.citizen_id = appt.citizen_id AND appl.service_id = appt.service_id
JOIN government_services.applications app ON app.service_id = appt.service_id
JOIN government_services.service_locations sloc ON appt.location_id = sloc.location_id;

[User] Actually, can you also include the scheduled start time for each appointment in the result?

[Assistant]
SELECT appt.appointment_id, srv.service_id, loc.location_name, appt.scheduled_start_time
FROM government_services.appointments appt
JOIN government_services.service_locations loc ON appt.location_id = loc.location_id
JOIN government_services.applications appl ON appl.citizen_id = appt.citizen_id AND appl.service_id = appt.service_id
JOIN government_services.applications app ON app.service_id = appt.service_id
JOIN government_services.service_locations sloc ON appt.location_id = sloc.location_id;


System:
You are very professional for database language writing. 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.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.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 )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )

[User] Find all vehicles that have at least one fuel log and at least one maintenance log. For each vehicle, show vehicle_id, make, model, the date of its most recent maintenance, and the timestamp of its earliest fuel log.

[Assistant]
SELECT v.vehicle_id,
       v.make,
       v.model,
       MAX(m.service_date)      AS last_service_date,
       MIN(f.log_timestamp)     AS first_fuel_log_timestamp
FROM transportation.vehicles v
JOIN transportation.maintenance_logs m
  ON v.vehicle_id = m.vehicle_id
JOIN transportation.fuel_logs f
  ON v.vehicle_id = f.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model;

[User] Now only include vehicles where the earliest fuel log occurred before the most recent maintenance service.

[Assistant]
SELECT v.vehicle_id,
       v.make,
       v.model,
       MAX(m.service_date)      AS last_service_date,
       MIN(f.log_timestamp)     AS first_fuel_log_timestamp
FROM transportation.vehicles v
JOIN transportation.maintenance_logs m
  ON v.vehicle_id = m.vehicle_id
JOIN transportation.fuel_logs f
  ON v.vehicle_id = f.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model
HAVING MIN(f.log_timestamp) < MAX(m.service_date);

[User] Also include the odometer reading at the most recent maintenance and the quantity of the earliest fuel log, and order the results by the time difference between the maintenance and fuel log in descending order.

[Assistant]
WITH last_maint AS (
  SELECT ml.vehicle_id,
         ml.odometer_reading,
         ml.service_date
  FROM transportation.maintenance_logs ml
  JOIN (
    SELECT vehicle_id, MAX(service_date) AS max_date
    FROM transportation.maintenance_logs
    GROUP BY vehicle_id
  ) mx
    ON ml.vehicle_id = mx.vehicle_id
   AND ml.service_date = mx.max_date
), first_fuel AS (
  SELECT fl.vehicle_id,
         fl.quantity,
         fl.log_timestamp
  FROM transportation.fuel_logs fl
  JOIN (
    SELECT vehicle_id, MIN(log_timestamp) AS min_ts
    FROM transportation.fuel_logs
    GROUP BY vehicle_id
  ) mn
    ON fl.vehicle_id = mn.vehicle_id
   AND fl.log_timestamp = mn.min_ts
)
SELECT v.vehicle_id,
       v.make,
       v.model,
       lm.odometer_reading     AS last_odo,
       ff.quantity             AS first_fuel_qty,
       (lm.service_date - ff.log_timestamp) AS time_diff
FROM last_maint lm
JOIN first_fuel ff
  ON lm.vehicle_id = ff.vehicle_id
JOIN transportation.vehicles v
  ON v.vehicle_id = lm.vehicle_id
ORDER BY time_diff DESC;


System:
You are very professional for database language writing. 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.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )

[User] Show the count of invoices for each case ID.

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id ORDER BY invoice_count DESC

[User] Only include case IDs with more than 2 invoices.

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id HAVING COUNT(invoice_id) > 2 ORDER BY invoice_count DESC

[User] For these cases, what is the average total amount across all invoices?

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count, AVG(total_amount) AS average_total_amount FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id HAVING COUNT(invoice_id) > 2 ORDER BY average_total_amount DESC

[User] Order the results by average total amount ascending.

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count, AVG(total_amount) AS average_total_amount FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id HAVING COUNT(invoice_id) > 2 ORDER BY average_total_amount ASC


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )

[User] How many smart money addresses are in the top 100 rank?

[Assistant] SELECT count(address) FROM smart_money_profit WHERE rank <= 100

[User] Okay, can you break that down by `chain`? Show the count for each chain where the rank is 100 or better.

[Assistant] SELECT chain, count(address) FROM smart_money_profit WHERE rank <= 100 GROUP BY chain


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.train_cars (
    car_id character varying(64) NOT NULL, -- Unique identifier for the train car
    train_id character varying(64) NOT NULL, -- Foreign key referencing trains
    car_number character varying(10) NOT NULL, -- Identifier of the car within the train set
    car_type character varying(64) NOT NULL, -- e.g., Locomotive, Passenger, Sleeper, Dining, Baggage
    class character varying(32), -- e.g., First, Business, Economy (null for non-passenger cars)
    capacity integer, -- Passenger capacity of this specific car (null for non-passenger cars)
    features text, -- Comma-separated list of features (e.g., 'WiFi', 'Power Outlet', 'Accessible Restroom')
    PRIMARY KEY (car_id),
    FOREIGN KEY (train_id) REFERENCES train_station_management.trains(train_id)
)
CREATE TABLE train_station_management.routes (
    route_id character varying(64) NOT NULL, -- Unique identifier for the route
    route_name character varying(128) NOT NULL, -- Name of the route (e.g., 'Northeast Corridor')
    description text, -- Description of the route
    origin_station_id character varying(64) NOT NULL, -- Starting station
    destination_station_id character varying(64) NOT NULL, -- Final station
    is_active boolean NOT NULL DEFAULT true, -- Is the route currently operational?
    PRIMARY KEY (route_id),
    FOREIGN KEY (origin_station_id) REFERENCES train_station_management.stations(station_id),
    FOREIGN KEY (destination_station_id) REFERENCES train_station_management.stations(station_id)
)
CREATE TABLE train_station_management.route_stations (
    route_station_id character varying(64) NOT NULL, -- Unique ID for this route-station link
    route_id character varying(64) NOT NULL, -- Foreign key referencing routes
    station_id character varying(64) NOT NULL, -- Foreign key referencing stations
    sequence_order integer NOT NULL, -- Order of the station in the route (1 for origin, 2, 3...)
    distance_from_previous_km numeric(10, 2), -- Distance from the previous station in the sequence
    typical_stop_duration_minutes integer, -- Typical dwell time at this station
    PRIMARY KEY (route_station_id),
    UNIQUE (route_id, station_id),
    UNIQUE (route_id, sequence_order),
    FOREIGN KEY (route_id) REFERENCES train_station_management.routes(route_id),
    FOREIGN KEY (station_id) REFERENCES train_station_management.stations(station_id)
)
CREATE TABLE train_station_management.schedules (
    schedule_id character varying(64) NOT NULL, -- Unique identifier for a specific scheduled trip
    train_id character varying(64) NOT NULL, -- Foreign key referencing the train used
    route_id character varying(64) NOT NULL, -- Foreign key referencing the route taken
    departure_datetime timestamp with time zone NOT NULL, -- Scheduled departure time from origin station
    arrival_datetime timestamp with time zone NOT NULL, -- Scheduled arrival time at destination station
    status character varying(32) NOT NULL DEFAULT 'Scheduled', -- e.g., Scheduled, On Time, Delayed, Cancelled, Arrived
    notes text, -- Any notes regarding this specific trip (e.g., reason for delay)
    PRIMARY KEY (schedule_id),
    FOREIGN KEY (train_id) REFERENCES train_station_management.trains(train_id),
    FOREIGN KEY (route_id) REFERENCES train_station_management.routes(route_id)
)
CREATE TABLE train_station_management.passengers (
    passenger_id character varying(64) NOT NULL, -- Unique identifier for the passenger
    first_name character varying(100) NOT NULL, -- Passenger's first name
    last_name character varying(100) NOT NULL, -- Passenger's last name
    email character varying(128) UNIQUE, -- Passenger's email address
    phone_number character varying(32) UNIQUE, -- Passenger's phone number
    date_of_birth date, -- Passenger's date of birth
    loyalty_program_id character varying(64), -- ID for loyalty program, if applicable
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- When the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE train_station_management.bookings (
    booking_id character varying(64) NOT NULL, -- Unique identifier for the booking
    passenger_id character varying(64) NOT NULL, -- Foreign key referencing the passenger
    schedule_id character varying(64) NOT NULL, -- Foreign key referencing the scheduled trip
    booking_datetime timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- When the booking was made
    status character varying(32) NOT NULL DEFAULT 'Confirmed', -- e.g., Confirmed, Cancelled, Pending
    total_price numeric(12, 2) NOT NULL, -- Total price for all tickets in this booking
    currency_code character varying(3) NOT NULL DEFAULT 'USD', -- Currency of the price
    special_requests text, -- Any special requests (e.g., wheelchair assistance)
    PRIMARY KEY (booking_id),
    FOREIGN KEY (passenger_id) REFERENCES train_station_management.passengers(passenger_id),
    FOREIGN KEY (schedule_id) REFERENCES train_station_management.schedules(schedule_id)
)
CREATE TABLE train_station_management.staff (
    staff_id character varying(64) NOT NULL, -- Unique identifier for the staff member
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    role character varying(64) NOT NULL, -- e.g., Station Master, Ticket Agent, Conductor, Engineer, Maintenance Crew
    primary_station_id character varying(64), -- Base station for the staff member (nullable for mobile staff)
    employee_number character varying(32) UNIQUE NOT NULL, -- Unique employee identifier
    hire_date date NOT NULL,
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    is_active boolean NOT NULL DEFAULT true, -- Is the staff member currently employed?
    PRIMARY KEY (staff_id),
    FOREIGN KEY (primary_station_id) REFERENCES train_station_management.stations(station_id)
)

[User] Can you help me retrieve the details of all bookings for a specific route with route_id 'RT789', including the passenger names and the scheduled departure times?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
WHERE s.route_id = 'RT789';

[User] Can you modify the query to include only bookings with a status of 'Pending'?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
WHERE s.route_id = 'RT789' AND b.status = 'Pending';

[User] Can you also add the route name and origin station ID to the results?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price, r.route_name, r.origin_station_id
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
JOIN train_station_management.routes r ON s.route_id = r.route_id
WHERE s.route_id = 'RT789' AND b.status = 'Pending';

[User] Can you sort the results by departure datetime in descending order?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price, r.route_name, r.origin_station_id
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
JOIN train_station_management.routes r ON s.route_id = r.route_id
WHERE s.route_id = 'RT789' AND b.status = 'Pending'
ORDER BY s.departure_datetime DESC;


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.transactions ( transaction_id text, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.smart_contracts ( contract_id text, creator_address text, code text, timestamp timestamp )

[User] I want to know how many times each smart contract has been invoked by transactions; also include the contract creator.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(t.transaction_id) AS invocation_count
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
GROUP BY sc.contract_id, sc.creator_address;

[User] I'd like to see only contracts with more than 100 invocations.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(t.transaction_id) AS invocation_count
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
GROUP BY sc.contract_id, sc.creator_address
HAVING COUNT(t.transaction_id) > 100;

[User] Actually, I want to order them by invocation_count descending and limit to the top 5.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(t.transaction_id) AS invocation_count
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
GROUP BY sc.contract_id, sc.creator_address
HAVING COUNT(t.transaction_id) > 100
ORDER BY invocation_count DESC
LIMIT 5;

[User] Also, show the timestamp when each of those top 5 contracts was created.

[Assistant]
SELECT sc.contract_id, sc.creator_address, sc.timestamp AS creation_time, COUNT(t.transaction_id) AS invocation_count
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
GROUP BY sc.contract_id, sc.creator_address, sc.timestamp
HAVING COUNT(t.transaction_id) > 100
ORDER BY invocation_count DESC
LIMIT 5;


System:
You are very professional for database language writing. 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.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )

[User] How many payments have been made using each payment_method, and what is the total amount for each method?

[Assistant]
SELECT payment_method, COUNT(*) AS payment_count, SUM(amount) AS total_amount
FROM government_services.payments
GROUP BY payment_method;

[User] Can you filter to only include methods where the total_amount exceeds 1000?

[Assistant]
SELECT payment_method, COUNT(*) AS payment_count, SUM(amount) AS total_amount
FROM government_services.payments
GROUP BY payment_method
HAVING SUM(amount) > 1000;

[User] Also exclude any payments with status other than 'Completed'.

[Assistant]
SELECT payment_method, COUNT(*) AS payment_count, SUM(amount) AS total_amount
FROM government_services.payments
WHERE status = 'Completed'
GROUP BY payment_method
HAVING SUM(amount) > 1000;

[User] Order the results by total_amount descending and limit to the top 5 payment methods.

[Assistant]
SELECT payment_method, COUNT(*) AS payment_count, SUM(amount) AS total_amount
FROM government_services.payments
WHERE status = 'Completed'
GROUP BY payment_method
HAVING SUM(amount) > 1000
ORDER BY total_amount DESC
LIMIT 5;


System:
You are very professional for database language writing. 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.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )

[User] Find all pairs of overlapping reservations for the same room. Show the two reservation IDs, room_id, and both reservations' check-in and check-out dates.

[Assistant] SELECT r1.reservation_id AS reservation1_id, r2.reservation_id AS reservation2_id, r1.room_id, r1.check_in_date AS reservation1_check_in, r1.check_out_date AS reservation1_check_out, r2.check_in_date AS reservation2_check_in, r2.check_out_date AS reservation2_check_out FROM hospitality_technology.reservations r1 JOIN hospitality_technology.reservations r2 ON r1.room_id = r2.room_id AND r1.reservation_id < r2.reservation_id AND r1.check_in_date < r2.check_out_date AND r2.check_in_date < r1.check_out_date;


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.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 PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] List all patients who have both primary and non-primary insurance plans, showing their full names and the count of each type of plan.

[Assistant] SELECT p.first_name, p.last_name, SUM(CASE WHEN pi.is_primary = true THEN 1 ELSE 0 END) AS primary_plans, SUM(CASE WHEN pi.is_primary = false THEN 1 ELSE 0 END) AS non_primary_plans FROM healthcare.patients p JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id GROUP BY p.patient_id, p.first_name, p.last_name HAVING SUM(CASE WHEN pi.is_primary = true THEN 1 ELSE 0 END) > 0 AND SUM(CASE WHEN pi.is_primary = false THEN 1 ELSE 0 END) > 0;

[User] Actually, I only need patients who have more than one non-primary insurance plan.

[Assistant] SELECT p.first_name, p.last_name, SUM(CASE WHEN pi.is_primary = true THEN 1 ELSE 0 END) AS primary_plans, SUM(CASE WHEN pi.is_primary = false THEN 1 ELSE 0 END) AS non_primary_plans FROM healthcare.patients p JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id GROUP BY p.patient_id, p.first_name, p.last_name HAVING SUM(CASE WHEN pi.is_primary = false THEN 1 ELSE 0 END) > 1;

[User] Can you also include the insurance provider names for their non-primary plans?

[Assistant] SELECT p.first_name, p.last_name, ip.insurance_provider, COUNT(pi.plan_id) AS non_primary_plans_count FROM healthcare.patients p JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE pi.is_primary = false GROUP BY p.patient_id, p.first_name, p.last_name, ip.insurance_provider HAVING COUNT(pi.plan_id) > 1;


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )

[User] Find the wallet address, user ID, and the contract address of any contract where that wallet is listed as the deployer.

[Assistant]
SELECT w.address AS wallet_address, w.user_id, c.address AS contract_address
FROM web3.wallets w
JOIN web3.contracts c ON w.address = c.deployer_address;


System:
You are very professional for database language writing. 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.reservations (
    reservation_id character varying(64) NOT NULL,  -- unique identifier for the booking
    property_id character varying(64) NOT NULL, -- FK to properties table
    guest_id character varying(64) NOT NULL, -- FK to guests table (primary guest)
    room_id character varying(64), -- FK to rooms table (assigned room, might be null initially)
    room_type_id character varying(64) NOT NULL, -- FK to room_types table (booked room type)
    check_in_date date NOT NULL, -- scheduled check-in date
    check_out_date date NOT NULL, -- scheduled check-out date
    actual_check_in_ts timestamp with time zone, -- actual check-in time
    actual_check_out_ts timestamp with time zone, -- actual check-out time
    num_adults integer NOT NULL, -- number of adults
    num_children integer DEFAULT 0, -- number of children
    status character varying(50) NOT NULL, -- e.g., Pending, Confirmed, CheckedIn, CheckedOut, Cancelled, NoShow
    booking_source character varying(100), -- e.g., Website, OTA (Expedia, Booking.com), Phone, WalkIn
    rate_plan_id character varying(64), -- FK to rate_plans table (optional)
    total_amount numeric(12, 2), -- estimated or final total cost
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    special_requests text, -- specific guest requests for this booking
    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.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.reviews (
    review_id character varying(64) NOT NULL,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    PRIMARY KEY (review_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id)
)

[User] List all reservations made in the last 6 months, showing the reservation ID, guest ID, and status.

[Assistant] SELECT reservation_id, guest_id, status FROM hospitality_technology.reservations WHERE created_at >= current_date - interval '6 months';

[User] Actually, I only want reservations where the check-in date is in the future.

[Assistant] SELECT reservation_id, guest_id, status FROM hospitality_technology.reservations WHERE created_at >= current_date - interval '6 months' AND check_in_date > current_date;

[User] For these future reservations created recently, can you also show the property name and the room type name?

[Assistant] SELECT T1.reservation_id, T1.guest_id, T1.status, T2.property_name, T3.type_name FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.created_at >= current_date - interval '6 months' AND T1.check_in_date > current_date;


System:
You are very professional for database language writing. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments ( comment_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, parent_comment_id character varying(64), content text NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (comment_id) )
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_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) )
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 character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )

[User] Find users with push_notifications_enabled set to false who have unread notifications. Show their username and the count of unread notifications.

[Assistant] SELECT u.username, COUNT(n.notification_id) AS unread_count FROM social_media.user_settings s JOIN social_media.notifications n ON s.user_id = n.recipient_user_id AND n.read_at IS NULL JOIN social_media.users u ON u.user_id = s.user_id WHERE s.push_notifications_enabled = FALSE GROUP BY u.username;

[User] Also include their email and the timestamp of their latest unread notification.

[Assistant] SELECT u.username, u.email, COUNT(n.notification_id) AS unread_count, MAX(n.created_at) AS last_unread_at FROM social_media.user_settings s JOIN social_media.notifications n ON s.user_id = n.recipient_user_id AND n.read_at IS NULL JOIN social_media.users u ON u.user_id = s.user_id WHERE s.push_notifications_enabled = FALSE GROUP BY u.username, u.email;

[User] Now only show users with more than 3 unread notifications and sort by unread_count descending.

[Assistant] SELECT u.username, u.email, COUNT(n.notification_id) AS unread_count, MAX(n.created_at) AS last_unread_at FROM social_media.user_settings s JOIN social_media.notifications n ON s.user_id = n.recipient_user_id AND n.read_at IS NULL JOIN social_media.users u ON u.user_id = s.user_id WHERE s.push_notifications_enabled = FALSE GROUP BY u.username, u.email HAVING COUNT(n.notification_id) > 3 ORDER BY unread_count DESC;


System:
You are very professional for database language writing. 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.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] Find the claim ID and the total number of documents associated with each claim ID that has more than 10 documents.

[Assistant] SELECT claim_id, COUNT(*) FROM insurance.claim_documents GROUP BY claim_id HAVING COUNT(*) > 10;


System:
You are very professional for database language writing. 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 character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
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] List the first name, last name, prescription ID, diagnosis code, and diagnosis description for patients who have both an ongoing prescription and an active chronic diagnosis.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name, T2.prescription_id, T3.diagnosis_code, T3.description FROM healthcare.patients AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.diagnoses AS T3 ON T1.patient_id = T3.patient_id WHERE (T2.end_date IS NULL OR T2.end_date > CURRENT_DATE) AND T3.is_chronic IS TRUE AND T3.status = 'Active';

[User] Refine the results to include only those cases where the prescription started within 30 days before or on the diagnosis date.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name, T2.prescription_id, T3.diagnosis_code, T3.description FROM healthcare.patients AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.diagnoses AS T3 ON T1.patient_id = T3.patient_id WHERE (T2.end_date IS NULL OR T2.end_date > CURRENT_DATE) AND T3.is_chronic IS TRUE AND T3.status = 'Active' AND T2.start_date BETWEEN T3.diagnosis_date - INTERVAL '30 days' AND T3.diagnosis_date;

[User] Add the full names of the doctor who wrote the prescription and the doctor who made the diagnosis to the results.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name, T2.prescription_id, T3.diagnosis_code, T3.description, T4.first_name AS prescribing_doctor_first_name, T4.last_name AS prescribing_doctor_last_name, T5.first_name AS diagnosing_doctor_first_name, T5.last_name AS diagnosing_doctor_last_name FROM healthcare.patients AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.diagnoses AS T3 ON T1.patient_id = T3.patient_id JOIN healthcare.doctors AS T4 ON T2.doctor_id = T4.doctor_id JOIN healthcare.doctors AS T5 ON T3.doctor_id = T5.doctor_id WHERE (T2.end_date IS NULL OR T2.end_date > CURRENT_DATE) AND T3.is_chronic IS TRUE AND T3.status = 'Active' AND T2.start_date BETWEEN T3.diagnosis_date - INTERVAL '30 days' AND T3.diagnosis_date;

[User] Filter the results to only include diagnoses with a code type of 'ICD-9' and where either the prescribing or diagnosing doctor has a specialty in 'Cardiology'.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name, T2.prescription_id, T3.diagnosis_code, T3.description, T4.first_name AS prescribing_doctor_first_name, T4.last_name AS prescribing_doctor_last_name, T5.first_name AS diagnosing_doctor_first_name, T5.last_name AS diagnosing_doctor_last_name FROM healthcare.patients AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.diagnoses AS T3 ON T1.patient_id = T3.patient_id JOIN healthcare.doctors AS T4 ON T2.doctor_id = T4.doctor_id JOIN healthcare.doctors AS T5 ON T3.doctor_id = T5.doctor_id WHERE (T2.end_date IS NULL OR T2.end_date > CURRENT_DATE) AND T3.is_chronic IS TRUE AND T3.status = 'Active' AND T2.start_date BETWEEN T3.diagnosis_date - INTERVAL '30 days' AND T3.diagnosis_date AND T3.code_type = 'ICD-9' AND (T4.specialty = 'Cardiology' OR T5.specialty = 'Cardiology');


System:
You are very professional for database language writing. 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.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )

[User] I need a list of unique company names and the number of clients in each company.

[Assistant]
SELECT company_name, COUNT(*) AS client_count
FROM legal_services.clients
WHERE company_name IS NOT NULL
GROUP BY company_name;

[User] Only include companies where there are at least 2 clients.

[Assistant]
SELECT company_name, COUNT(*) AS client_count
FROM legal_services.clients
WHERE company_name IS NOT NULL
GROUP BY company_name
HAVING COUNT(*) >= 2;

[User] Also, show the email addresses of the clients in those companies.

[Assistant]
SELECT c.company_name, c.email
FROM legal_services.clients c
WHERE c.company_name IN (
  SELECT company_name
  FROM legal_services.clients
  WHERE company_name IS NOT NULL
  GROUP BY company_name
  HAVING COUNT(*) >= 2
)
ORDER BY c.company_name, c.email;

[User] Only show companies whose name contains the word 'Group'.

[Assistant]
SELECT c.company_name, c.email
FROM legal_services.clients c
WHERE c.company_name IN (
  SELECT company_name
  FROM legal_services.clients
  WHERE company_name IS NOT NULL AND company_name ILIKE '%Group%'
  GROUP BY company_name
  HAVING COUNT(*) >= 2
)
ORDER BY c.company_name, c.email;