[User] Show me the number of game servers in each region and the average maximum number of players they can accommodate. Exclude any servers that are currently offline.

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region;

[User] Please filter the results to only include regions that have more than 5 active servers.

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region HAVING COUNT(server_id) > 5;

[User] Can you also include the total number of current players across all active servers in each of those regions?

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players, SUM(current_players) AS total_current_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region HAVING COUNT(server_id) > 5;

[User] Order the final results by the total number of current players in descending order.

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players, SUM(current_players) AS total_current_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region HAVING COUNT(server_id) > 5 ORDER BY total_current_players 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 gaming_technology.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player
    username character varying(100) NOT NULL UNIQUE, -- player's chosen display name
    email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery
    password_hash text NOT NULL, -- securely hashed password
    registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created
    last_login timestamp with time zone, -- timestamp of the last successful login
    country_code character(2), -- player's country (ISO 3166-1 alpha-2)
    status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended)
    profile_data jsonb, -- flexible field for avatar url, bio, preferences etc.
    PRIMARY KEY (player_id)
)
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)


[User] List all clients along with their case_number and case_type for cases that are currently 'Open'.

[Assistant]
SELECT c.first_name, c.last_name, c.email, cs.case_number, cs.case_type
FROM legal_services.clients AS c
JOIN legal_services.cases AS cs
  ON c.client_id = cs.client_id
WHERE cs.status = 'Open';

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.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.documents ( document_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, document_name character varying(255) NOT NULL, document_type character varying(100), storage_path text NOT NULL, uploaded_by_lawyer_id character varying(64), upload_timestamp timestamp NOT NULL, version integer DEFAULT 1, description text, PRIMARY KEY (document_id) )
CREATE TABLE legal_services.time_entries ( entry_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, date_worked date NOT NULL, hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), billing_rate numeric(10, 2) NOT NULL, description text NOT NULL, is_billable boolean DEFAULT true, is_billed boolean DEFAULT false, invoice_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (entry_id) )
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )


[User] Show me all rooms with their room number, the type name, and the maximum occupancy for each room.

[Assistant]
SELECT r.room_id, r.room_number, rt.type_name, rt.max_occupancy
FROM hospitality_technology.rooms r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_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 hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)


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

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

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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)


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

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

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

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

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


[User] How many documents of each type exist in the system? Show the document type and the count.

[Assistant]
SELECT document_type, COUNT(*) AS document_count
FROM legal_services.documents
group BY document_type;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )


[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] Can you count how many times each user has commented on posts created by users they are following?

[Assistant] SELECT c.user_id AS commenter_user_id, f.following_user_id, COUNT(*) AS comment_count FROM social_media.comments c JOIN social_media.follows f ON c.user_id = f.follower_user_id AND c.post_id IN (SELECT post_id FROM social_media.comments WHERE user_id = f.following_user_id) GROUP BY c.user_id, f.following_user_id;

[User] Actually, I only want to see users who have commented more than 3 times on posts created by the users they follow.

[Assistant] SELECT c.user_id AS commenter_user_id, f.following_user_id, COUNT(*) AS comment_count FROM social_media.comments c JOIN social_media.follows f ON c.user_id = f.follower_user_id AND c.post_id IN (SELECT post_id FROM social_media.comments WHERE user_id = f.following_user_id) GROUP BY c.user_id, f.following_user_id HAVING COUNT(*) > 3;

[User] Can you order the results by comment_count in descending order?

[Assistant] SELECT c.user_id AS commenter_user_id, f.following_user_id, COUNT(*) AS comment_count FROM social_media.comments c JOIN social_media.follows f ON c.user_id = f.follower_user_id AND c.post_id IN (SELECT post_id FROM social_media.comments WHERE user_id = f.following_user_id) GROUP BY c.user_id, f.following_user_id HAVING COUNT(*) > 3 ORDER BY comment_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 social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )


[User] What are the personal contact details of the staff member associated with staff_id 'STAFF789' who worked on a specific maintenance record?

[Assistant] I'm sorry, but I can't provide personal contact details of staff members as this information is not stored in the maintenance_records table and is outside the scope of the available data.

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, 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] List all medical records, showing the record ID, record date, and the full name of the doctor who created the record. Include the patient ID as well.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, d.first_name, d.last_name FROM healthcare.medical_records mr JOIN doctors d ON mr.doctor_id = d.doctor_id;

[User] Refine this to only include records where the chief_complaint is not null or empty and the doctor's specialty is 'Cardiology'.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, d.first_name, d.last_name FROM healthcare.medical_records mr JOIN doctors d ON mr.doctor_id = d.doctor_id WHERE (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') AND d.specialty = 'Cardiology';

[User] Also, sort the results by record_date in descending order and limit the output to the top 10 records.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, d.first_name, d.last_name FROM healthcare.medical_records mr JOIN doctors d ON mr.doctor_id = d.doctor_id WHERE (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') AND d.specialty = 'Cardiology' ORDER BY mr.record_date DESC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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 average, minimum, and maximum interest_rate for each loan_type among active loans?

[Assistant]
SELECT loan_type,
       AVG(interest_rate) AS avg_interest_rate,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate
FROM financial_services.loans
WHERE status = 'Active'
GROUP BY loan_type;

[User] Exclude loan types with fewer than 5 active loans.

[Assistant]
SELECT loan_type,
       AVG(interest_rate) AS avg_interest_rate,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate
FROM financial_services.loans
WHERE status = 'Active'
GROUP BY loan_type
HAVING COUNT(*) >= 5;

[User] Sort the result by average_interest_rate descending and only return the top 5 loan types.

[Assistant]
SELECT loan_type,
       AVG(interest_rate) AS avg_interest_rate,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate
FROM financial_services.loans
WHERE status = 'Active'
GROUP BY loan_type
HAVING COUNT(*) >= 5
ORDER BY avg_interest_rate DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.loans (
    loan_id character varying(64) NOT NULL, -- unique identifier for the loan, could be same as account_id
    account_id character varying(64) NOT NULL UNIQUE, -- link to the general account record
    loan_type character varying(50) NOT NULL, -- e.g., Mortgage, Personal, Auto, Student
    principal_amount numeric(19, 4) NOT NULL, -- original loan amount
    current_principal_balance numeric(19, 4) NOT NULL, -- remaining principal
    interest_rate numeric(6, 4) NOT NULL, -- annual interest rate
    term_months integer NOT NULL, -- loan term in months
    origination_date date NOT NULL, -- date the loan was disbursed
    maturity_date date NOT NULL, -- date the loan is due to be fully repaid
    monthly_payment numeric(12, 4), -- scheduled monthly payment amount
    collateral_description text, -- description of collateral, if secured loan
    status character varying(32) NOT NULL, -- e.g., Active, Paid Off, Defaulted
    PRIMARY KEY (loan_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id)
)


[User] Show the usernames of users who have liked a comment made by a user they are following.

[Assistant] SELECT DISTINCT T1.username FROM social_media.users AS T1 JOIN likes AS T2 ON T1.user_id = T2.user_id JOIN comments AS T3 ON T2.target_entity_id = T3.comment_id JOIN social_media.users AS T4 ON T3.user_id = T4.user_id JOIN follows AS T5 ON T1.user_id = T5.follower_user_id AND T4.user_id = T5.followed_user_id WHERE T2.target_entity_type = 'comment';

[User] Include the content of the comment and the username of the commenter.

[Assistant] SELECT T1.username AS liker_username, T4.username AS commenter_username, T3.content AS comment_content FROM social_media.users AS T1 JOIN likes AS T2 ON T1.user_id = T2.user_id JOIN comments AS T3 ON T2.target_entity_id = T3.comment_id JOIN social_media.users AS T4 ON T3.user_id = T4.user_id JOIN follows AS T5 ON T1.user_id = T5.follower_user_id AND T4.user_id = T5.followed_user_id WHERE T2.target_entity_type = 'comment';

[User] Filter to only show likes made in June 2024 and order by like creation time descending.

[Assistant] SELECT T1.username AS liker_username, T4.username AS commenter_username, T3.content AS comment_content, T2.created_at AS like_time FROM social_media.users AS T1 JOIN likes AS T2 ON T1.user_id = T2.user_id JOIN comments AS T3 ON T2.target_entity_id = T3.comment_id JOIN social_media.users AS T4 ON T3.user_id = T4.user_id JOIN follows AS T5 ON T1.user_id = T5.follower_user_id AND T4.user_id = T5.followed_user_id WHERE T2.target_entity_type = 'comment' AND T2.created_at >= '2024-06-01' AND T2.created_at < '2024-07-01' 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 text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )


[User] List all active policies, showing the policy number, the customer's full name, and the agent's full name who sold the policy.

[Assistant] SELECT T1.policy_number, T2.first_name, T2.last_name, T3.first_name, T3.last_name FROM policies AS T1 JOIN customers AS T2 ON T1.customer_id = T2.customer_id JOIN agents AS T3 ON T1.agent_id = T3.agent_id WHERE T1.status = 'active'

[User] Can you also add the product name and the policy's premium amount to the results?

[Assistant] SELECT T1.policy_number, T2.first_name AS customer_first_name, T2.last_name AS customer_last_name, T3.first_name AS agent_first_name, T3.last_name AS agent_last_name, T4.product_name, T1.premium_amount FROM policies AS T1 JOIN customers AS T2 ON T1.customer_id = T2.customer_id JOIN agents AS T3 ON T1.agent_id = T3.agent_id JOIN insurance_products AS T4 ON T1.product_id = T4.product_id WHERE T1.status = 'active'

[User] Actually, filter those results to only include policies with a premium amount greater than 5000 and only sold by agents whose license state is 'CA'.

[Assistant] SELECT T1.policy_number, T2.first_name AS customer_first_name, T2.last_name AS customer_last_name, T3.first_name AS agent_first_name, T3.last_name AS agent_last_name, T4.product_name, T1.premium_amount FROM policies AS T1 JOIN customers AS T2 ON T1.customer_id = T2.customer_id JOIN agents AS T3 ON T1.agent_id = T3.agent_id JOIN insurance_products AS T4 ON T1.product_id = T4.product_id WHERE T1.status = 'active' AND T1.premium_amount > 5000 AND T3.license_state = 'CA'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )


[User] List all appointments scheduled in the next 7 days along with the appointment_id, appointment_time, patient's full name, doctor's full name, and the patient's primary insurance plan_name.

[Assistant]
SELECT ap.appointment_id,
       ap.appointment_time,
       pt.first_name || ' ' || pt.last_name AS patient_name,
       d.first_name || ' ' || d.last_name AS doctor_name,
       ip.plan_name
FROM healthcare.appointments ap
JOIN healthcare.patients pt ON ap.patient_id = pt.patient_id
JOIN healthcare.doctors d ON ap.doctor_id = d.doctor_id
JOIN healthcare.patient_insurance pi ON pt.patient_id = pi.patient_id AND pi.is_primary = TRUE
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE ap.appointment_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '7 days';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] Find all smart contracts where the code length is greater than 1000 characters.

[Assistant] SELECT contract_id, creator_address, timestamp FROM blockchain.smart_contracts WHERE LENGTH(code) > 1000;

[User] Now group these by creator_address and show the count of such contracts per creator.

[Assistant] SELECT creator_address, COUNT(*) AS long_code_contracts FROM blockchain.smart_contracts WHERE LENGTH(code) > 1000 GROUP BY creator_address;

[User] Can you order the results by the count in descending order?

[Assistant] SELECT creator_address, COUNT(*) AS long_code_contracts FROM blockchain.smart_contracts WHERE LENGTH(code) > 1000 GROUP BY creator_address ORDER BY long_code_contracts DESC;

[User] Now show only creators who have more than 3 such contracts.

[Assistant] SELECT creator_address, COUNT(*) AS long_code_contracts FROM blockchain.smart_contracts WHERE LENGTH(code) > 1000 GROUP BY creator_address HAVING COUNT(*) > 3 ORDER BY long_code_contracts 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 blockchain.smart_contracts ( contract_id text PRIMARY KEY, creator_address text, code text, timestamp timestamp )


[User] Show the total number of customers in each state.

[Assistant]
SELECT
  state,
  COUNT(customer_id)
FROM insurance.customers
GROUP BY
  state;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.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 character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )


[User] Show me all contracts deployed on the 'ethereum' network along with their deployer addresses and deployment timestamps, sorted by the most recent deployments first.

[Assistant] SELECT address, deployer_address, deployed_at FROM web3.contracts WHERE network_id = 'ethereum' ORDER BY deployed_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.contracts ( contract_id text, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text )


[User] Show the number of policies sold by each agent, including the agent's first and last name, specifically for policies related to 'auto' products.

[Assistant] SELECT T1.first_name, T1.last_name, count(T2.policy_id) FROM insurance.agents AS T1 JOIN insurance.policies AS T2 ON T1.agent_id = T2.agent_id JOIN insurance.insurance_products AS T3 ON T2.product_id = T3.product_id WHERE T3.product_type = 'auto' GROUP BY T1.agent_id, T1.first_name, T1.last_name;

[User] Can you also include agents who haven't sold any policies for 'auto' products, showing 0 for their policy count?

[Assistant] SELECT T1.first_name, T1.last_name, count(T2.policy_id) FROM insurance.agents AS T1 LEFT JOIN insurance.policies AS T2 ON T1.agent_id = T2.agent_id LEFT JOIN insurance.insurance_products AS T3 ON T2.product_id = T3.product_id AND T3.product_type = 'auto' GROUP BY T1.agent_id, T1.first_name, T1.last_name;

[User] Now, only include agents who are currently 'active' and have sold at least one policy for 'auto' products.

[Assistant] SELECT T1.first_name, T1.last_name, count(T2.policy_id) FROM insurance.agents AS T1 JOIN insurance.policies AS T2 ON T1.agent_id = T2.agent_id JOIN insurance.insurance_products AS T3 ON T2.product_id = T3.product_id WHERE T3.product_type = 'auto' AND T1.status = 'active' GROUP BY T1.agent_id, T1.first_name, T1.last_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 insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
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.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )


[User] Find the full names and emails of citizens who have received notifications with the status 'Sent' related to a document. Also show the document_id for each notification.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name, c.contact_email, n.related_entity_id AS document_id
FROM government_services.notifications n
JOIN government_services.citizens c ON n.citizen_id = c.citizen_id
WHERE n.status = 'Sent' AND n.related_entity_type = 'Document';

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.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


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

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

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


[User] Show me the top 3 tokens by USD value inflow where smart money was buying (type = 1), along with their token symbol and narrative from the smart_money_token_inflow table.

[Assistant] SELECT token_symbol, narrative, usd_value FROM smart_money_token_inflow WHERE type = 1 ORDER BY usd_value DESC LIMIT 3;

[User] Can you filter these results to only include tokens from the Ethereum chain?

[Assistant] SELECT token_symbol, narrative, usd_value FROM smart_money_token_inflow WHERE type = 1 AND chain = 'Ethereum' ORDER BY usd_value DESC LIMIT 3;

[User] Now include the 24-hour trading volume for these tokens from the token_dexpool_info table.

[Assistant] SELECT s.token_symbol, s.narrative, s.usd_value, t.volume_24h FROM smart_money_token_inflow s JOIN token_dexpool_info t ON s.token_symbol = t.token_symbol WHERE s.type = 1 AND s.chain = 'Ethereum' AND t.chain = 'Ethereum' ORDER BY s.usd_value DESC LIMIT 3;

[User] Actually, I only want tokens with a 24-hour trading volume over $500,000.

[Assistant] SELECT s.token_symbol, s.narrative, s.usd_value, t.volume_24h FROM smart_money_token_inflow s JOIN token_dexpool_info t ON s.token_symbol = t.token_symbol WHERE s.type = 1 AND s.chain = 'Ethereum' AND t.chain = 'Ethereum' AND t.volume_24h > 500000 ORDER BY s.usd_value DESC LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, token_address character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, highest_price_24h double precision, lowest_price_24h double precision, market_cap double precision, market_cap_rank bigint, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank bigint )
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_6h double precision, price_change_percentage_24h double precision, makers_24h double precision, volume_24h double precision, liquidity double precision, market_cap double precision, trend_rank bigint )
CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL, chain character varying(128) NOT NULL, address character varying(128) NOT NULL, exchange character varying(512) NOT NULL, token_address character varying(128) NOT NULL, token_symbol character varying(512), balance numeric(38,10), usd_value numeric(38,14), price double precision )
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] List all hashtags that have never been associated with any post, showing hashtag_id and tag_name.

[Assistant]
SELECT h.hashtag_id, h.tag_name
FROM social_media.hashtags h
LEFT JOIN social_media.post_hashtags ph ON h.hashtag_id = ph.hashtag_id
WHERE ph.post_hashtag_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 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.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
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, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )


[User] Show me all claims with police reports that were filed in the last 3 months, along with their policy details and estimated loss amounts.

[Assistant] SELECT cl.claim_id, cl.policy_id, cl.estimated_loss, cl.incident_date, cl.reported_date, p.premium_amount, p.coverage_limit FROM insurance.claims cl JOIN insurance.policies p ON cl.policy_id = p.policy_id WHERE cl.police_report_number IS NOT NULL AND cl.reported_date >= CURRENT_DATE - INTERVAL '3 months';

[User] I also want to see the customer's name and the product type for these policies.

[Assistant] SELECT cl.claim_id, cl.policy_id, cl.estimated_loss, cl.incident_date, cl.reported_date, p.premium_amount, p.coverage_limit, c.first_name AS customer_first_name, c.last_name AS customer_last_name, pr.product_type FROM insurance.claims cl JOIN insurance.policies p ON cl.policy_id = p.policy_id JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.products pr ON p.product_id = pr.product_id WHERE cl.police_report_number IS NOT NULL AND cl.reported_date >= CURRENT_DATE - INTERVAL '3 months';

[User] Now filter these results to only show claims where the estimated loss is above $10,000 and sort them by estimated loss in descending order.

[Assistant] SELECT cl.claim_id, cl.policy_id, cl.estimated_loss, cl.incident_date, cl.reported_date, p.premium_amount, p.coverage_limit, c.first_name AS customer_first_name, c.last_name AS customer_last_name, pr.product_type FROM insurance.claims cl JOIN insurance.policies p ON cl.policy_id = p.policy_id JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.products pr ON p.product_id = pr.product_id WHERE cl.police_report_number IS NOT NULL AND cl.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND cl.estimated_loss > 10000 ORDER BY cl.estimated_loss DESC;

[User] Finally, include the count of premium payments made for each of these policies and show only policies with at least 3 payments.

[Assistant] SELECT cl.claim_id, cl.policy_id, cl.estimated_loss, cl.incident_date, cl.reported_date, p.premium_amount, p.coverage_limit, c.first_name AS customer_first_name, c.last_name AS customer_last_name, pr.product_type, COUNT(pp.payment_id) AS payment_count FROM insurance.claims cl JOIN insurance.policies p ON cl.policy_id = p.policy_id JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.products pr ON p.product_id = pr.product_id LEFT JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id WHERE cl.police_report_number IS NOT NULL AND cl.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND cl.estimated_loss > 10000 GROUP BY cl.claim_id, cl.policy_id, cl.estimated_loss, cl.incident_date, cl.reported_date, p.premium_amount, p.coverage_limit, c.first_name, c.last_name, pr.product_type HAVING COUNT(pp.payment_id) >= 3 ORDER BY cl.estimated_loss DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.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.premium_payments ( payment_id.text, policy_id.text, customer_id.text, payment_date.timestamp, amount_paid.numeric, payment_method.text, transaction_reference.text, due_date.date, payment_period_start.date, payment_period_end.date, status.text )


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

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

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

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

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

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

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

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

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


[User] What is the total market cap for all tokens listed on the 'Polygon' chain?

[Assistant] SELECT SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon';

[User] Only sum the market cap for tokens on 'Polygon' that have a 24-hour volume greater than 500000.

[Assistant] SELECT SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon' AND volume_24h > 500000;

[User] Also show the number of unique tokens that meet these criteria.

[Assistant] SELECT COUNT(DISTINCT token_symbol), SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon' AND volume_24h > 500000;

[User] Can you show the total market cap and token count for *each* chain that meets these volume criteria, ordered by total market cap descending?

[Assistant] SELECT chain, COUNT(DISTINCT token_symbol) AS token_count, SUM(market_cap) AS total_market_cap FROM token_dexpool_info WHERE volume_24h > 500000 GROUP BY chain ORDER BY total_market_cap DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )


[User] List the token symbol and name for all tokens whose associated contract address has emitted at least one event. Also include the contract address.

[Assistant] SELECT T.token_symbol, T.token_name, T.contract_address FROM web3.tokens AS T JOIN contracts AS C ON T.contract_address = C.address JOIN events AS E ON C.contract_id = E.contract_id GROUP BY T.token_symbol, T.token_name, T.contract_address;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.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] What are the safety ratings or crash statistics for the Boeing 787 Dreamliner?

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

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


[User] Provide a summary of transactions by status, showing the count and the total amount for each status.

[Assistant] SELECT status, COUNT(*) AS transaction_count, SUM(amount) AS total_amount FROM financial_services.transactions GROUP BY status;

[User] Only include statuses where the total transaction count exceeds 5.

[Assistant] SELECT status, COUNT(*) AS transaction_count, SUM(amount) AS total_amount FROM financial_services.transactions GROUP BY status HAVING COUNT(*) > 5;

[User] Sort the results by transaction count descending.

[Assistant] SELECT status, COUNT(*) AS transaction_count, SUM(amount) AS total_amount FROM financial_services.transactions GROUP BY status HAVING COUNT(*) > 5 ORDER BY transaction_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 financial_services.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.accounts ( account_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, account_number character varying(128) NOT NULL UNIQUE, account_type character varying(50) NOT NULL, balance numeric(19, 4) NOT NULL DEFAULT 0.00, currency character varying(3) NOT NULL, opened_date date NOT NULL, status character varying(32) NOT NULL, interest_rate numeric(5, 4), last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (account_id), FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id) )
CREATE TABLE financial_services.transactions ( transaction_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, related_account_id character varying(64), transaction_type character varying(50) NOT NULL, amount numeric(19, 4) NOT NULL, currency character varying(3) NOT NULL, transaction_date timestamp NOT NULL, effective_date date NOT NULL, description text, status character varying(32) NOT NULL, reference_number character varying(128), PRIMARY KEY (transaction_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id) )
CREATE TABLE financial_services.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data (
    data_point_id bigserial NOT NULL, -- auto-incrementing primary key
    security_id character varying(64) NOT NULL, -- identifier for the security
    data_timestamp timestamp NOT NULL, -- timestamp for the data point (e.g., end of day, intraday)
    open_price numeric(19, 8), -- opening price for the period
    high_price numeric(19, 8), -- highest price during the period
    low_price numeric(19, 8), -- lowest price during the period
    close_price numeric(19, 8) NOT NULL, -- closing price for the period
    adjusted_close_price numeric(19, 8), -- closing price adjusted for dividends and splits
    volume bigint, -- trading volume during the period
    source character varying(50), -- source of the market data (e.g., Bloomberg, Refinitiv)
    PRIMARY KEY (data_point_id),
    UNIQUE (security_id, data_timestamp), -- Ensure unique data point per security per time
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)
CREATE TABLE financial_services.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(100) NOT NULL, department character varying(100), branch_id character varying(64), email character varying(128) NOT NULL UNIQUE, phone_extension character varying(20), hire_date date NOT NULL, termination_date date, manager_id character varying(64), status character varying(32) NOT NULL, PRIMARY KEY (employee_id), FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id) )
CREATE TABLE financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )


[User] List all service orders for spa services with their guest names and total prices, ordered by total price in descending order.

[Assistant] SELECT g.first_name, g.last_name, so.order_id, so.total_price FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id WHERE so.service_id LIKE 'SPA%' ORDER BY so.total_price DESC;

[User] Now, include only orders with a total price over $100 and show the property ID where the service was ordered.

[Assistant] SELECT g.first_name, g.last_name, so.order_id, so.total_price, r.property_id FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.reservations r ON so.reservation_id = r.reservation_id WHERE so.service_id LIKE 'SPA%' AND so.total_price > 100 ORDER BY so.total_price DESC;

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

[Assistant] SELECT g.first_name, g.last_name, so.order_id, so.total_price, r.property_id, s.service_name FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.reservations r ON so.reservation_id = r.reservation_id JOIN hospitality_technology.services s ON so.service_id = s.service_id WHERE so.service_id LIKE 'SPA%' AND so.total_price > 100 ORDER BY so.total_price DESC;

[User] Actually, I only need orders from properties in California, and order by property ID first, then by total price.

[Assistant] SELECT g.first_name, g.last_name, so.order_id, so.total_price, r.property_id, s.service_name FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.reservations r ON so.reservation_id = r.reservation_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.properties p ON r.property_id = p.property_id WHERE so.service_id LIKE 'SPA%' AND so.total_price > 100 AND p.state_province = 'California' ORDER BY r.property_id, so.total_price 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.room_types ( room_type_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, type_name character varying(100) NOT NULL, description text, base_rate numeric(10, 2) NOT NULL, max_occupancy integer NOT NULL, bed_type character varying(50), area_sqft numeric(8,2), amenities text, PRIMARY KEY (room_type_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.guests (
    guest_id character varying(64) NOT NULL,  -- unique identifier for the guest profile
    first_name character varying(100) NOT NULL, -- guest's first name
    last_name character varying(100) NOT NULL, -- guest's last name
    email character varying(255) UNIQUE, -- guest's email address (unique identifier?)
    phone_number character varying(30), -- guest's phone number
    date_of_birth date, -- guest's date of birth
    address_line1 character varying(255), -- guest's home address
    city character varying(100),
    state_province character varying(100),
    postal_code character varying(20),
    country_code character varying(3),
    preferences text, -- notes on guest preferences (e.g., allergies, room location)
    loyalty_member_id character varying(64) UNIQUE, -- FK to loyalty_members table
    communication_consent boolean DEFAULT true, -- consent for marketing communications
    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)
)
CREATE TABLE hospitality_technology.reservations (
    reservation_id character varying(64) NOT NULL,  -- unique identifier for the booking
    property_id character varying(64) NOT NULL, -- FK to properties table
    guest_id character varying(64) NOT NULL, -- FK to guests table (primary guest)
    room_id character varying(64), -- FK to rooms table (assigned room, might be null initially)
    room_type_id character varying(64) NOT NULL, -- FK to room_types table (booked room type)
    check_in_date date NOT NULL, -- scheduled check-in date
    check_out_date date NOT NULL, -- scheduled check-out date
    actual_check_in_ts timestamp with time zone, -- actual check-in time
    actual_check_out_ts timestamp with time zone, -- actual check-out time
    num_adults integer NOT NULL, -- number of adults
    num_children integer DEFAULT 0, -- number of children
    status character varying(50) NOT NULL, -- e.g., Pending, Confirmed, CheckedIn, CheckedOut, Cancelled, NoShow
    booking_source character varying(100), -- e.g., Website, OTA (Expedia, Booking.com), Phone, WalkIn
    rate_plan_id character varying(64), -- FK to rate_plans table (optional)
    total_amount numeric(12, 2), -- estimated or final total cost
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    special_requests text, -- specific guest requests for this booking
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (reservation_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


[User] For each vehicle, list its vehicle_id, license_plate, and any older vehicle of the same type (showing older_vehicle_id and older year).

[Assistant]
SELECT cur.vehicle_id,
       cur.license_plate,
       old.vehicle_id AS older_vehicle_id,
       old.year       AS older_vehicle_year
FROM transportation.vehicles cur
JOIN transportation.vehicles old
  ON cur.type = old.type
 AND old.year < cur.year
ORDER BY cur.vehicle_id, old.year DESC;

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


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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )


[User] Find all pairs of tokens that have the same contract_address but different token_symbols. Show both token_ids, each token's symbol, and the shared contract_address.

[Assistant] SELECT t1.token_id AS token_id_1, t2.token_id AS token_id_2, t1.token_symbol AS symbol_1, t2.token_symbol AS symbol_2, t1.contract_address FROM web3.tokens t1 JOIN web3.tokens t2 ON t1.contract_address = t2.contract_address AND t1.token_id < t2.token_id AND t1.token_symbol <> t2.token_symbol;

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 text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )


[User] List the document ID, document type, and the full name of the citizen who submitted the document, but only for documents submitted for applications with a status of 'Approved'.

[Assistant] SELECT T1.document_id, T1.document_type, T3.first_name, T3.last_name FROM government_services.documents AS T1 JOIN government_services.applications AS T2 ON T1.application_id = T2.application_id JOIN government_services.citizens AS T3 ON T1.citizen_id = T3.citizen_id WHERE T2.status = 'Approved';

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.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 )


[User] List all pairs of citizens who registered on the same date. Include each citizen's full name and the shared registration date.

[Assistant]
SELECT c1.first_name || ' ' || c1.last_name AS full_name_1,
       c2.first_name || ' ' || c2.last_name AS full_name_2,
       DATE(c1.registration_date) AS registration_date
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON DATE(c1.registration_date) = DATE(c2.registration_date)
  AND c1.citizen_id < c2.citizen_id;

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


[User] How many unique patient records are there for each gender?

[Assistant] SELECT gender, COUNT(DISTINCT patient_id) AS patient_count FROM healthcare.patients GROUP BY gender;

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 )


[User] List all medical records created in the last 7 days, including patient_id, doctor_id, and record_date.

[Assistant] SELECT patient_id, doctor_id, record_date FROM healthcare.medical_records WHERE created_at >= CURRENT_DATE - INTERVAL '7 days';

[User] Actually, I only need records where the treatment_plan is not empty.

[Assistant] SELECT patient_id, doctor_id, record_date FROM healthcare.medical_records WHERE created_at >= CURRENT_DATE - INTERVAL '7 days' AND treatment_plan IS NOT NULL AND treatment_plan != '';

[User] Can you also sort them by record_date in descending order?

[Assistant] SELECT patient_id, doctor_id, record_date FROM healthcare.medical_records WHERE created_at >= CURRENT_DATE - INTERVAL '7 days' AND treatment_plan IS NOT NULL AND treatment_plan != '' ORDER BY record_date 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.medical_records ( record_id.text, patient_id.text, appointment_id.text, doctor_id.text, record_date.timestamp, chief_complaint.text, present_illness_history.text, past_medical_history.text, physical_examination_notes.text, assessment.text, treatment_plan.text, vitals.json, created_at.timestamp )


[User] List all appointments that are currently scheduled and show their appointment time.

[Assistant] SELECT appointment_id, patient_id, doctor_id, appointment_time FROM healthcare.appointments WHERE status = 'Scheduled';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )


[User] For each game, I need a breakdown of how many sessions each server has hosted and what percentage of that game's total sessions each server represents. Display game_id, server_id, server_name, session_count, and session_percentage.

[Assistant]
```sql
SELECT
  gs.game_id,
  s.server_id,
  s.server_name,
  COUNT(*) AS session_count,
  ROUND(
    COUNT(*) * 100.0
    / SUM(COUNT(*)) OVER (PARTITION BY gs.game_id),
    2
  ) AS session_percentage
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.servers s
  ON gs.server_id = s.server_id
GROUP BY
  gs.game_id,
  s.server_id,
  s.server_name;
```

[User] Exclude any servers that have hosted fewer than 10 sessions.

[Assistant]
```sql
SELECT
  gs.game_id,
  s.server_id,
  s.server_name,
  COUNT(*) AS session_count,
  ROUND(
    COUNT(*) * 100.0
    / SUM(COUNT(*)) OVER (PARTITION BY gs.game_id),
    2
  ) AS session_percentage
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.servers s
  ON gs.server_id = s.server_id
GROUP BY
  gs.game_id,
  s.server_id,
  s.server_name
HAVING
  COUNT(*) >= 10;
```

[User] Also order the results by game_id and then by session_percentage descending.

[Assistant]
```sql
SELECT
  gs.game_id,
  s.server_id,
  s.server_name,
  COUNT(*) AS session_count,
  ROUND(
    COUNT(*) * 100.0
    / SUM(COUNT(*)) OVER (PARTITION BY gs.game_id),
    2
  ) AS session_percentage
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.servers s
  ON gs.server_id = s.server_id
GROUP BY
  gs.game_id,
  s.server_id,
  s.server_name
HAVING
  COUNT(*) >= 10
ORDER BY
  gs.game_id,
  session_percentage DESC;
```

[User] Actually, I only care about servers in the 'Europe' and 'Asia' regions. Can you filter the query accordingly?

[Assistant]
```sql
SELECT
  gs.game_id,
  s.server_id,
  s.server_name,
  COUNT(*) AS session_count,
  ROUND(
    COUNT(*) * 100.0
    / SUM(COUNT(*)) OVER (PARTITION BY gs.game_id),
    2
  ) AS session_percentage
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.servers s
  ON gs.server_id = s.server_id
WHERE
  s.region IN ('Europe', 'Asia')
GROUP BY
  gs.game_id,
  s.server_id,
  s.server_name
HAVING
  COUNT(*) >= 10
ORDER BY
  gs.game_id,
  session_percentage 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 gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
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) )