[User] Find transactions where the from_address is the same as the to_address (self-transactions) with values greater than 1 ETH (1e18 wei), showing transaction_id and value.

[Assistant] SELECT transaction_id, value FROM web3.transactions WHERE from_address = to_address AND value > 1000000000000000000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.transactions ( transaction_id text PRIMARY KEY, from_address text, to_address text, value numeric, gas_used int, gas_price numeric, block_number int, timestamp timestamp, input_data text, status text, nonce int )


[User] Show all rooms that are on floor 3.

[Assistant] SELECT room_id, property_id, room_number FROM hospitality_technology.rooms WHERE floor = 3;

[User] For these rooms, include the property name and room number.

[Assistant] SELECT r.room_number, p.property_name FROM hospitality_technology.rooms AS r JOIN hospitality_technology.properties AS p ON r.property_id = p.property_id WHERE r.floor = 3;

[User] Also, include the type name and current status for each room.

[Assistant] SELECT r.room_number, p.property_name, rt.type_name, r.status FROM hospitality_technology.rooms AS r JOIN hospitality_technology.properties AS p ON r.property_id = p.property_id JOIN hospitality_technology.room_types AS rt ON r.room_type_id = rt.room_type_id AND r.property_id = rt.property_id WHERE r.floor = 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )


[User] Show me all insurance plans that have more than 5 patients enrolled, along with the provider name and count of patients, sorted by patient count in descending order.

[Assistant] SELECT i.plan_name, i.insurance_provider, COUNT(p.patient_id) AS patient_count FROM healthcare.insurance_plans i JOIN healthcare.patients p ON i.plan_id = p.primary_insurance_id GROUP BY i.plan_id HAVING COUNT(p.patient_id) > 5 ORDER BY patient_count DESC;

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


[User] List all premium payments along with the full name of the agent who sold each policy and the name of the related insurance product.

[Assistant]
SELECT pp.payment_id, pp.amount_paid, pp.payment_date, a.first_name AS agent_first_name, a.last_name AS agent_last_name, ip.product_name
FROM insurance.premium_payments pp
JOIN insurance.policies p ON pp.policy_id = p.policy_id
JOIN insurance.agents a ON p.agent_id = a.agent_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id;

[User] Can you also add the agent's agency name and the policy number to the results?

[Assistant]
SELECT pp.payment_id, pp.amount_paid, pp.payment_date, a.first_name AS agent_first_name, a.last_name AS agent_last_name, a.agency_name, p.policy_number, ip.product_name
FROM insurance.premium_payments pp
JOIN insurance.policies p ON pp.policy_id = p.policy_id
JOIN insurance.agents a ON p.agent_id = a.agent_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id;

[User] Actually, only include payments made in 2024.

[Assistant]
SELECT pp.payment_id, pp.amount_paid, pp.payment_date, a.first_name AS agent_first_name, a.last_name AS agent_last_name, a.agency_name, p.policy_number, ip.product_name
FROM insurance.premium_payments pp
JOIN insurance.policies p ON pp.policy_id = p.policy_id
JOIN insurance.agents a ON p.agent_id = a.agent_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE EXTRACT(YEAR FROM pp.payment_date) = 2024;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )


[User] I’d like to find all pairs of securities that belong to the same sector.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector
WHERE a.security_id < b.security_id;

[User] Actually, only include pairs where the two securities are listed on different exchanges.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange;

[User] Also, I want the results sorted by sector, then by exchange_a.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange
ORDER BY a.sector, a.exchange;

[User] One more thing: include both exchanges in the ORDER BY so that within each sector it’s sorted by exchange_a then exchange_b.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange
ORDER BY a.sector, a.exchange, b.exchange;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.securities ( security_id text PRIMARY KEY, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )


[User] List users who have received notifications triggered by another user (non-system notifications). Show the recipient username, notification type, and the sender username.

[Assistant] SELECT T1.username AS recipient_username, T2.notification_type, T3.username AS sender_username FROM social_media.users AS T1 JOIN social_media.notifications AS T2 ON T1.user_id = T2.recipient_user_id JOIN social_media.users AS T3 ON T2.sender_user_id = T3.user_id;

[User] Refine the list from Turn 1 to only include notifications of type 'follow' or 'mention'.

[Assistant] SELECT T1.username AS recipient_username, T2.notification_type, T3.username AS sender_username FROM social_media.users AS T1 JOIN social_media.notifications AS T2 ON T1.user_id = T2.recipient_user_id JOIN social_media.users AS T3 ON T2.sender_user_id = T3.user_id WHERE T2.notification_type IN ('follow', 'mention');

[User] Further filter to only include notifications created in 2024 and order the results by notification creation time descending.

[Assistant] SELECT T1.username AS recipient_username, T2.notification_type, T3.username AS sender_username FROM social_media.users AS T1 JOIN social_media.notifications AS T2 ON T1.user_id = T2.recipient_user_id JOIN social_media.users AS T3 ON T2.sender_user_id = T3.user_id WHERE T2.notification_type IN ('follow', 'mention') AND EXTRACT(YEAR FROM T2.created_at) = 2024 ORDER BY T2.created_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_id)
)
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_id)
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)


[User] What is the total revenue generated by ticket sales at the station with ID 'ST101' for the past month?

[Assistant] I'm sorry, but I can't provide information on the revenue generated by ticket sales as this data is not available in the current database table. The table only contains details about station information such as name, location, and platform count. If you have another question or need assistance with something else related to the station data, I'm happy to help.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.stations ( station_id.text, station_name.text, city.text, state_province.text, country_code.text, address.text, timezone.text, number_of_platforms.integer, created_at.timestamp, last_updated_at.timestamp )


[User] For the 'DeFi' narrative, what is the average ROI and the total net inflow (usd_value where type=1) from smart money token inflow?

[Assistant]
SELECT AVG(sm.roi) AS avg_roi, SUM(smt.usd_value) AS total_net_inflow
FROM smart_money_token_inflow smt
JOIN smart_money_profit sm ON smt.chain = sm.chain
WHERE smt.narrative = 'DeFi' AND smt.type = 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE narrative_info ( narrative text, top_3_coins text, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, market_cap numeric, volume_24h numeric, trend_rank numeric, token_num numeric )
CREATE TABLE cex_token_balance ( snapshot_time text, chain text, address text, exchange text, token_address text, token_symbol text, balance numeric, usd_value numeric, price numeric )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )


[User] How many documents were uploaded in the year 2023?

[Assistant] SELECT count(*) FROM government_services.documents WHERE date_part('year', upload_timestamp) = 2023;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )


[User] What is the current market price of a Boeing 737 MAX aircraft?

[Assistant] I'm sorry, but I don't have access to the current market price of aircraft models. The data I have is limited to technical specifications and general information about aircraft models such as passenger capacity, range, and status. For pricing information, you may need to consult with manufacturers or industry reports.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE manufacturing.aircraft_models (
    model_id character varying(64) NOT NULL,  -- unique identifier for the aircraft model
    model_name character varying(128) NOT NULL, -- commercial name of the model (e.g., 737 MAX, A320neo)
    manufacturer character varying(128) NOT NULL, -- manufacturer name (e.g., Boeing, Airbus)
    passenger_capacity integer, -- typical passenger capacity
    max_range_km integer, -- maximum flight range in kilometers
    engine_type character varying(100), -- type of engines used
    wingspan_m numeric(6,2), -- wingspan in meters
    status character varying(50) NOT NULL, -- e.g., 'In Production', 'Development', 'Discontinued'
    first_flight_date date, -- date of the model's first flight
    PRIMARY KEY (model_id)
)


[User] For each player, show the player_id and the count of inventory items they acquired with a quantity greater than 1.

[Assistant] SELECT player_id, COUNT(inventory_id) AS items_qty_gt_1_count FROM gaming_technology.player_inventory WHERE quantity > 1 GROUP BY player_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )


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

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

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


[User] Show me all active managers along with their property IDs and the number of staff members they supervise, ordered by the number of supervised staff in descending order.

[Assistant] SELECT s.staff_id, s.property_id, s.first_name, s.last_name, COUNT(s2.staff_id) AS supervised_staff_count FROM hospitality_technology.staff s LEFT JOIN hospitality_technology.staff s2 ON s.staff_id = s2.manager_id WHERE s.position = 'Manager' AND s.is_active = true GROUP BY s.staff_id, s.property_id, s.first_name, s.last_name ORDER BY supervised_staff_count DESC;

[User] Now, include only managers who supervise at least 3 staff members and show their email addresses as well.

[Assistant] SELECT s.staff_id, s.property_id, s.first_name, s.last_name, s.work_email, COUNT(s2.staff_id) AS supervised_staff_count FROM hospitality_technology.staff s LEFT JOIN hospitality_technology.staff s2 ON s.staff_id = s2.manager_id WHERE s.position = 'Manager' AND s.is_active = true GROUP BY s.staff_id, s.property_id, s.first_name, s.last_name, s.work_email HAVING COUNT(s2.staff_id) >= 3 ORDER BY supervised_staff_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)


[User] Provide a count of appointments grouped by the booking method.

[Assistant] SELECT booking_method, COUNT(*) AS appointment_count FROM government_services.appointments GROUP BY booking_method;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.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.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    employee_id character varying(64), -- FK to employees table (optional, if assigned)
    location_id character varying(64), -- FK to service_locations table (if physical)
    service_id character varying(64), -- FK to services table (optional, if related to specific service)
    scheduled_start_time timestamp NOT NULL,
    scheduled_end_time timestamp,
    purpose text NOT NULL, -- reason for the appointment
    status character varying(30) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-Show
    booking_method character varying(50), -- e.g., Online, Phone, In-Person
    created_at timestamp NOT NULL, -- when the appointment was booked
    notes text,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE government_services.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    application_id character varying(64), -- FK to applications table (optional)
    message_subject character varying(255),
    message_body text NOT NULL,
    channel character varying(30) NOT NULL, -- e.g., Email, SMS, Portal Message, Mail
    sent_at timestamp NOT NULL,
    status character varying(30) NOT NULL, -- e.g., Queued, Sent, Delivered, Failed, Read
    related_entity_type character varying(50), -- e.g., Application, Appointment, Document Request
    related_entity_id character varying(64), -- ID of the related entity
    PRIMARY KEY (notification_id)
)


[User] What is the average ROI and average realized_ratio for each chain?

[Assistant]
SELECT chain,
       AVG(roi) AS avg_roi,
       AVG(realized_ratio) AS avg_realized_ratio
FROM smart_money_token_performance
GROUP BY chain;

[User] Now filter to only include chains where average ROI is above 0.5.

[Assistant]
WITH stats AS (
  SELECT chain,
         AVG(roi) AS avg_roi,
         AVG(realized_ratio) AS avg_realized_ratio
  FROM smart_money_token_performance
  GROUP BY chain
)
SELECT chain, avg_roi, avg_realized_ratio
FROM stats
WHERE avg_roi > 0.5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )


[User] List the number of employees hired in each department per year.

[Assistant]
SELECT
  department,
  EXTRACT(YEAR FROM hire_date) AS hire_year,
  COUNT(employee_id) AS employee_count
FROM financial_services.employees
WHERE
  hire_date IS NOT NULL
GROUP BY
  department,
  hire_year
ORDER BY
  department,
  hire_year;

[User] Now, only include departments that hired more than 5 employees in any given year.

[Assistant]
SELECT
  department,
  EXTRACT(YEAR FROM hire_date) AS hire_year,
  COUNT(employee_id) AS employee_count
FROM financial_services.employees
WHERE
  hire_date IS NOT NULL
GROUP BY
  department,
  hire_year
HAVING
  COUNT(employee_id) > 5
ORDER BY
  department,
  hire_year;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
CREATE TABLE financial_services.transactions ( transaction_id.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text )
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.employees ( employee_id text PRIMARY KEY, 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] Show me the first and last names of all customers who have filed a claim, along with the claim ID and incident date.

[Assistant]
SELECT c.first_name, c.last_name, cl.claim_id, cl.incident_date
FROM insurance.customers c
JOIN insurance.claims cl ON c.customer_id = cl.customer_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )


[User] Find all pairs of contracts that were deployed on the same network. Show both contract IDs, the network ID, and the deployment timestamps for both contracts.

[Assistant]
SELECT a.contract_id AS contract_id_1, b.contract_id AS contract_id_2, a.network_id, a.deployed_at AS deployed_at_1, b.deployed_at AS deployed_at_2
FROM web3.contracts a
JOIN web3.contracts b
  ON a.network_id = b.network_id AND a.contract_id < b.contract_id;

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


[User] List all document IDs, file names, and uploaded timestamps for documents that were uploaded on a weekend.

[Assistant] SELECT document_id, file_name, uploaded_at FROM insurance.claim_documents WHERE EXTRACT(DOW FROM uploaded_at) IN (0, 6);

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


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

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

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


[User] What is the current job satisfaction level or feedback from staff members working at a specific train station?

[Assistant] I'm sorry, but I can't provide information on job satisfaction levels or feedback from staff members as this data is not included in the staff table.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.staff ( staff_id.text, first_name.text, last_name.text, role.text, primary_station_id.text, employee_number.text, hire_date.date, contact_email.text, contact_phone.text, is_active.boolean )


[User] Can you narrow this down to only show cases where the case type is 'Criminal'?

[Assistant] SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE lead_lawyer_id = 'lawyer_abc' AND status = 'Open' AND case_type = 'Criminal';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )


[User] Show me document_id, application_id, and verification_status for all documents submitted by citizen 'cit123'.

[Assistant]
SELECT document_id,
       application_id,
       verification_status
FROM documents
WHERE citizen_id = 'cit123';

[User] I got an error: relation 'documents' does not exist.

[Assistant]
SELECT document_id,
       application_id,
       verification_status
FROM government_services.documents
WHERE citizen_id = 'cit123';

[User] Now, only include documents where verification_status = 'Pending'.

[Assistant]
SELECT document_id,
       application_id,
       verification_status
FROM government_services.documents
WHERE citizen_id = 'cit123'
  AND verification_status = 'Pending';

[User] Also, limit the results to files uploaded in 2024.

[Assistant]
SELECT document_id,
       application_id,
       verification_status
FROM government_services.documents
WHERE citizen_id = 'cit123'
  AND verification_status = 'Pending'
  AND upload_timestamp >= '2024-01-01'
  AND upload_timestamp < '2025-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id 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.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.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.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] What is the current number of passengers at station with ID 'ST123' right now?

[Assistant] I'm sorry, but I can't provide information on the current number of passengers at a station. The data I have access to only includes static details about stations such as their name, location, and number of platforms, not real-time passenger counts.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.stations (
    station_id character varying(64) NOT NULL,  -- Unique identifier for the station
    station_name character varying(128) NOT NULL, -- Name of the station
    city character varying(100) NOT NULL, -- City where the station is located
    state_province character varying(100), -- State or province
    country_code character varying(3) NOT NULL, -- ISO country code
    address text, -- Full address of the station
    timezone character varying(64) NOT NULL, -- Timezone ID (e.g., 'America/New_York')
    number_of_platforms integer NOT NULL DEFAULT 0, -- Total number of platforms
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- When the station record was created
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- When the station record was last updated
    PRIMARY KEY (station_id)
)


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

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

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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.market_data ( data_point_id bigint, security_id text, data_timestamp timestamp, open_price numeric, high_price numeric, low_price numeric, close_price numeric, adjusted_close_price numeric, volume bigint, source text )


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

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

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


[User] Find all medical records where the vitals JSON field contains a blood pressure reading with systolic higher than 140, and show the patient_id, record_date, and vitals.

[Assistant] SELECT patient_id, record_date, vitals FROM healthcare.medical_records WHERE (vitals->>'blood_pressure_systolic')::integer > 140;

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


[User] What is the maintenance schedule for platform 3 at station DEF for the next month?

[Assistant] I'm sorry, but I don't have access to the maintenance schedule for platforms. The data I have only includes static information about platform details such as ID, station, number, track, status, length, and accessibility. For maintenance schedules, you may need to consult the station management or relevant department.

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


[User] How many lawyers who are partners were hired in each year? Show the hire year and the count.

[Assistant] SELECT strftime('%Y', hire_date) AS hire_year ,  count(lawyer_id) FROM legal_services.lawyers WHERE is_partner  =  true GROUP BY hire_year

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


[User] Show me the count of available rooms for each property.

[Assistant] SELECT T1.property_name, count(T2.room_id) FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.rooms AS T2 ON T1.property_id = T2.property_id WHERE T2.status = 'Available' GROUP BY T1.property_name;

[User] Also, include the average base rate of available room types for each property.

[Assistant] SELECT T1.property_name, count(T2.room_id), avg(T3.base_rate) FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.rooms AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T2.room_type_id = T3.room_type_id WHERE T2.status = 'Available' GROUP BY T1.property_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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 text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, 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 int, num_children int, 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.payments ( payment_id text PRIMARY KEY, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


[User] List the token symbol, token name, and contract address for all tokens that have no recorded transfers in the token_transfers table.

[Assistant] SELECT T.token_symbol, T.token_name, T.contract_address FROM web3.tokens AS T LEFT JOIN token_transfers AS TT ON T.token_id = TT.token_id WHERE TT.transfer_id IS NULL;

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


[User] Can you provide the total number of cars associated with a specific train with train_id 'train_789'?

[Assistant] SCARD train:train_789:cars

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// Use Hashes for platform details. Key format: platform:<platform_id>
// HSET platform:plat_123 platform_id "plat_123" station_id "station_xyz" platform_number "1A" track_number "T1" status "Operational" length_meters 250.50 accessible 1

// To link platforms to stations (optional):
// SADD station:station_xyz:platforms platform:plat_123 platform:plat_456
// Use Hashes for train details. Key format: train:<train_id>
// HSET train:train_789 train_id "train_789" train_number "Acela 2151" model "Siemens Velaro" ... status "Active" ...

// To find train by train_number (optional index):
// SET train_number:"Acela 2151" train:train_789
// Use Hashes for car details. Key format: car:<car_id>
// HSET car:car_abc car_id "car_abc" train_id "train_789" car_number "C3" car_type "Passenger" class "Business" capacity 60 features "WiFi,Power Outlet"

// To link cars to trains (optional):
// SADD train:train_789:cars car:car_abc car:car_def
// Use Hashes for details. Key format: route_station:<route_station_id>
// HSET route_station:rs_ne_1 route_station_id "rs_ne_1" route_id "route_ne_corr" station_id "station_bos" sequence_order 1 ...

// To find stops for a route, use a Sorted Set (score by sequence_order):
// ZADD route:route_ne_corr:stops 1 route_station:rs_ne_1
// ZADD route:route_ne_corr:stops 2 route_station:rs_ne_2
// Use Hashes for schedule details. Key format: schedule:<schedule_id>
// HSET schedule:sched_1122 schedule_id "sched_1122" train_id "train_789" route_id "route_ne_corr" departure_datetime "2024-05-10T08:00:00-04:00" ... status "Scheduled"
// Use Hashes for details. Key format: schedule_stop:<stop_id>
// HSET schedule_stop:stop_sched1122_1 stop_id "stop_sched1122_1" schedule_id "sched_1122" station_id "station_bos" ...

// To find stops for a schedule, use a Sorted Set (score by sequence_order):
// ZADD schedule:sched_1122:stops 1 schedule_stop:stop_sched1122_1
// ZADD schedule:sched_1122:stops 2 schedule_stop:stop_sched1122_2
// Use Hashes for passenger details. Key format: passenger:<passenger_id>
// HSET passenger:pass_pqr passenger_id "pass_pqr" first_name "Alice" last_name "Smith" email "alice.smith@example.com" ...

// To find passenger by email (optional index):
// SET passenger_email:"alice.smith@example.com" passenger:pass_pqr
// Use Hashes for booking details. Key format: booking:<booking_id>
// HSET booking:book_zyx booking_id "book_zyx" passenger_id "pass_pqr" schedule_id "sched_1122" ... status "Confirmed" ...

// To link bookings to passengers/schedules (optional):
// SADD passenger:pass_pqr:bookings booking:book_zyx
// SADD schedule:sched_1122:bookings booking:book_zyx
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...

// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b
// Use Hashes for staff details. Key format: staff:<staff_id>
// HSET staff:staff_mno staff_id "staff_mno" first_name "Bob" ... employee_number "E12345" ... is_active 1

// To find staff by employee number (optional index):
// SET staff_employee_number:"E12345" staff:staff_mno
// Use Hashes for maintenance record details. Key format: maintenance_record:<record_id>
// HSET maintenance_record:maint_rec_001 record_id "maint_rec_001" asset_id "train_789" asset_type "Train" ... status "Completed"

// To link records to assets (optional):
// SADD train:train_789:maintenance maintenance_record:maint_rec_001
// SADD platform:plat_123:maintenance maintenance_record:maint_rec_002


[User] I need to find all bookings for a specific schedule with schedule_id 'sched_1122' and include the passenger and ticket details.

[Assistant]
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:book_*
HGETALL passenger:pass_*
SMEMBERS booking:book_*:tickets
HGETALL ticket:tkt_*

[User] Can you filter the tickets to show only those that are not checked in?

[Assistant]
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:book_*
HGETALL passenger:pass_*
SMEMBERS booking:book_*:tickets
HGET ticket:tkt_* is_checked_in
IF is_checked_in == 0 THEN
HGETALL ticket:tkt_*
ENDIF

[User] Can you also include the car details for each ticket?

[Assistant]
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:book_*
HGETALL passenger:pass_*
SMEMBERS booking:book_*:tickets
HGET ticket:tkt_* is_checked_in
IF is_checked_in == 0 THEN
HGETALL ticket:tkt_*
HGET ticket:tkt_* car_id
HGETALL car:car_*
ENDIF


[User] List the claim_id and the total number of documents uploaded for each claim, but only include claims with between 3 and 7 documents.

[Assistant] SELECT claim_id, COUNT(*) AS document_count FROM insurance.claim_documents GROUP BY claim_id HAVING COUNT(*) BETWEEN 3 AND 7;

[User] Can you also show the upload time of the most recent document for each claim in this list?

[Assistant] SELECT cd.claim_id, COUNT(*) AS document_count, MAX(cd.uploaded_at) AS latest_uploaded_at FROM insurance.claim_documents cd GROUP BY cd.claim_id HAVING COUNT(*) BETWEEN 3 AND 7;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )


[User] List each employee's first and last name along with the count of active services offered by their agency.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(s.service_id) AS active_service_count
FROM government_services.employees e
JOIN government_services.services s ON e.agency_id = s.agency_id AND s.is_active = TRUE
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Actually, only include employees whose service count is greater than 5.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(s.service_id) AS active_service_count
FROM government_services.employees e
JOIN government_services.services s ON e.agency_id = s.agency_id AND s.is_active = TRUE
GROUP BY e.employee_id, e.first_name, e.last_name
HAVING COUNT(s.service_id) > 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
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) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.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] List all maintenance logs for vehicles acquired in the year 2023. Include log ID, vehicle make, model, service date, and cost.

[Assistant] SELECT ml.log_id, v.make, v.model, ml.service_date, ml.cost FROM transportation.maintenance_logs AS ml JOIN transportation.vehicles AS v ON ml.vehicle_id = v.vehicle_id WHERE EXTRACT(YEAR FROM v.acquisition_date) = 2023;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )


[User] What is the number of guests per country, grouped by country_code?

[Assistant]
SELECT country_code,
       COUNT(*) AS guest_count
FROM hospitality_technology.guests
GROUP BY country_code;

[User] Only include countries that have at least 5 guests.

[Assistant]
SELECT country_code,
       COUNT(*) AS guest_count
FROM hospitality_technology.guests
GROUP BY country_code
HAVING COUNT(*) >= 5;

[User] Also include the most recently registered guest in each of those countries, showing their full name and created_at.

[Assistant]
WITH country_counts AS (
  SELECT country_code,
         COUNT(*) AS guest_count,
         MAX(created_at) AS last_reg
  FROM hospitality_technology.guests
  GROUP BY country_code
  HAVING COUNT(*) >= 5
)
SELECT cc.country_code,
       cc.guest_count,
       g.first_name || ' ' || g.last_name AS last_guest_name,
       g.created_at          AS last_registration
FROM country_counts cc
JOIN hospitality_technology.guests g
  ON g.country_code = cc.country_code
 AND g.created_at = cc.last_reg;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )


[User] Return the usernames and emails of users who have bios that mention the word 'travel'.

[Assistant]
SELECT username, email
FROM social_media.users
WHERE bio ILIKE '%travel%';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id.text, username.text, email.text, password_hash.text, full_name.text, profile_picture_url.text, bio.text, location.text, created_at.timestamp, updated_at.timestamp, is_verified.boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )


[User] For each event recorded, list its ID, name, and the status and value of the transaction in which it occurred.

[Assistant] SELECT E.event_id, E.event_name, E.transaction_id, T.status, T.value FROM web3.events AS E JOIN web3.transactions AS T ON E.transaction_id = T.transaction_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
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 text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] Find the names of service locations where services categorized as 'Licensing' have had appointments scheduled.

[Assistant] SELECT DISTINCT T1.location_name FROM service_locations AS T1 JOIN appointments AS T2 ON T1.location_id = T2.location_id JOIN services AS T3 ON T2.service_id = T3.service_id WHERE T3.category = 'Licensing';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
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 character varying(64) NOT NULL, -- unique identifier for the appointment
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    employee_id character varying(64), -- FK to employees table (optional, if assigned)
    location_id character varying(64), -- FK to service_locations table (if physical)
    service_id character varying(64), -- FK to services table (optional, if related to specific service)
    scheduled_start_time timestamp NOT NULL,
    scheduled_end_time timestamp,
    purpose text NOT NULL, -- reason for the appointment
    status character varying(30) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-Show
    booking_method character varying(50), -- e.g., Online, Phone, In-Person
    created_at timestamp NOT NULL, -- when the appointment was booked
    notes text,
    PRIMARY KEY (appointment_id)
)


[User] List the service_id, service_name, and agency_id for all active services that have an online application URL provided.

[Assistant]
SELECT service_id,
       service_name,
       agency_id
FROM government_services.services
WHERE is_active = TRUE
  AND online_application_url IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    employee_id character varying(64), -- FK to employees table (optional, if assigned)
    location_id character varying(64), -- FK to service_locations table (if physical)
    service_id character varying(64), -- FK to services table (optional, if related to specific service)
    scheduled_start_time timestamp NOT NULL,
    scheduled_end_time timestamp,
    purpose text NOT NULL, -- reason for the appointment
    status character varying(30) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-Show
    booking_method character varying(50), -- e.g., Online, Phone, In-Person
    created_at timestamp NOT NULL, -- when the appointment was booked
    notes text,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] List all patients who have insurance plans with group numbers, showing their patient IDs and the count of such plans per patient.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id;

[User] Actually, I only need patients who have more than 2 such plans.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;

[User] Can you also include the earliest effective date among these plans for each patient?

[Assistant] SELECT patient_id, COUNT(*) AS plan_count, MIN(effective_date) AS earliest_effective_date FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List each wallet that has received tokens of more than one distinct token type. Show wallet_id, address, the number of distinct tokens received as distinct_token_count, and the total received value, ordered by total_received_value descending.

[Assistant]
SELECT w.wallet_id,
       w.address,
       COUNT(DISTINCT t.token_id) AS distinct_token_count,
       SUM(tt.value)            AS total_received_value
FROM web3.wallets w
JOIN web3.token_transfers tt
  ON w.address = tt.to_address
JOIN web3.tokens t
  ON tt.token_id = t.token_id
GROUP BY w.wallet_id, w.address
HAVING COUNT(DISTINCT t.token_id) > 1
ORDER BY total_received_value DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.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 character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)


[User] What are the specific tools or equipment used during the maintenance with record_id 'REC456'?

[Assistant] I'm sorry, but I can't provide information about the specific tools or equipment used during a maintenance record. The data in the maintenance_records table does not include details about tools or equipment used.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id text PRIMARY KEY, asset_id text, asset_type text, maintenance_type text, staff_id text, start_datetime timestamp, end_datetime timestamp, description text, cost numeric, status text )


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

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

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


[User] Give me the total billed amount for each invoice in 2024.

[Assistant] SELECT invoice_id, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE AND EXTRACT(YEAR FROM date_worked) = 2024 GROUP BY invoice_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )


[User] Return the count of comments for each hashtag.

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

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