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

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

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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )


[User] How many tokens had a net positive flow according to smart_money_token_performance, and what is their average ROI?

[Assistant]
SELECT COUNT(*) AS token_count, AVG(roi) AS avg_roi
FROM smart_money_token_performance
WHERE net_flow > 0;

[User] Now, break this down by chain, and order the results by avg_roi descending.

[Assistant]
SELECT chain, COUNT(*) AS token_count, AVG(roi) AS avg_roi
FROM smart_money_token_performance
WHERE net_flow > 0
GROUP BY chain
ORDER BY avg_roi 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 project_fundraising_record ( id character varying(32) NOT NULL, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, top_3_coins text, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, market_cap double precision, volume_24h double precision, trend_rank bigint, token_num 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_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, token_symbol character varying(100), token_amount numeric(38,2), usd_value numeric(38,2), avg_price numeric(38,6), type int, address_amount integer, narrative character varying(100), chain character varying(100) )


[User] List all appointments scheduled in the next 30 days with appointment_id, client_id, case_id, and any invoice_id linked to that case.

[Assistant]
SELECT
  a.appointment_id,
  a.client_id,
  a.case_id,
  i.invoice_id
FROM legal_services.appointments AS a
LEFT JOIN legal_services.invoices AS i
  ON a.case_id = i.case_id
WHERE a.start_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days';

[User] Change to include only appointments with status 'Scheduled' and invoices that are not fully paid.

[Assistant]
SELECT
  a.appointment_id,
  a.client_id,
  a.case_id,
  i.invoice_id
FROM legal_services.appointments AS a
LEFT JOIN legal_services.invoices AS i
  ON a.case_id = i.case_id
WHERE a.start_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND a.status = 'Scheduled'
  AND (i.status IS NULL OR i.status <> 'Paid');

[User] Also include only those where the case_type is 'Corporate'.

[Assistant]
SELECT
  a.appointment_id,
  a.client_id,
  a.case_id,
  i.invoice_id
FROM legal_services.appointments AS a
JOIN legal_services.cases AS c
  ON a.case_id = c.case_id
LEFT JOIN legal_services.invoices AS i
  ON a.case_id = i.case_id
WHERE a.start_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND a.status = 'Scheduled'
  AND (i.status IS NULL OR i.status <> 'Paid')
  AND c.case_type = 'Corporate';

[User] Finally, order by start_time ascending and return only the first 10 rows.

[Assistant]
SELECT
  a.appointment_id,
  a.client_id,
  a.case_id,
  i.invoice_id
FROM legal_services.appointments AS a
JOIN legal_services.cases AS c
  ON a.case_id = c.case_id
LEFT JOIN legal_services.invoices AS i
  ON a.case_id = i.case_id
WHERE a.start_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND a.status = 'Scheduled'
  AND (i.status IS NULL OR i.status <> 'Paid')
  AND c.case_type = 'Corporate'
ORDER BY a.start_time ASC
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 legal_services.law_firms (
    firm_id character varying(64) NOT NULL,  -- unique identifier for the law firm
    firm_name character varying(200) NOT NULL, -- official name of the law firm
    address text NOT NULL, -- primary address of the firm
    phone character varying(32), -- firm's main phone number
    website character varying(255), -- firm's website URL
    founded_date date, -- date the firm was established
    managing_partner_id character varying(64), -- FK to lawyers table (optional)
    PRIMARY KEY (firm_id)
)
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)


[User] Find all blocks with difficulty above 5000 and include their timestamp.

[Assistant] SELECT block_id, timestamp FROM blockchain.blocks WHERE difficulty > 5000;

[User] Now show me the count of such blocks grouped by month in 2023.

[Assistant] SELECT DATE_TRUNC('month', timestamp) AS month, COUNT(*) AS block_count FROM blockchain.blocks WHERE difficulty > 5000 AND timestamp BETWEEN '2023-01-01' AND '2023-12-31' GROUP BY month ORDER BY month;

[User] Actually, I want to see the average difficulty for each of these months as well.

[Assistant] SELECT DATE_TRUNC('month', timestamp) AS month, COUNT(*) AS block_count, AVG(difficulty) AS avg_difficulty FROM blockchain.blocks WHERE difficulty > 5000 AND timestamp BETWEEN '2023-01-01' AND '2023-12-31' GROUP BY month ORDER BY month;

[User] Can you modify this to also include the block_id with the highest difficulty for each month?

[Assistant] WITH monthly_stats AS (SELECT DATE_TRUNC('month', timestamp) AS month, COUNT(*) AS block_count, AVG(difficulty) AS avg_difficulty FROM blockchain.blocks WHERE difficulty > 5000 AND timestamp BETWEEN '2023-01-01' AND '2023-12-31' GROUP BY month) SELECT ms.month, ms.block_count, ms.avg_difficulty, (SELECT b.block_id FROM blockchain.blocks b WHERE DATE_TRUNC('month', b.timestamp) = ms.month AND b.difficulty > 5000 ORDER BY b.difficulty DESC LIMIT 1) AS highest_diff_block_id FROM monthly_stats ms ORDER BY ms.month;

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.blocks ( block_id text PRIMARY KEY, previous_block_id text, timestamp timestamp, nonce int, merkle_root text, difficulty int )
CREATE TABLE blockchain.addresses ( address_id text PRIMARY KEY, public_key text, balance numeric )
CREATE TABLE blockchain.smart_contracts ( contract_id text PRIMARY KEY, creator_address text, code text, timestamp timestamp )


[User] List the usernames and user IDs of all users whose bio contains the word 'developer'.

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

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.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_id)
)
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)


[User] Could you provide the total number of game sessions and the number of distinct players for each game genre? Display the genre, session count, and player count.

[Assistant] SELECT g.genre, COUNT(gs.session_id) AS session_count, COUNT(DISTINCT gs.player_id) AS player_count FROM gaming_technology.game_sessions AS gs JOIN gaming_technology.games AS g ON gs.game_id = g.game_id WHERE g.genre IS NOT NULL GROUP BY g.genre ORDER BY g.genre;

[User] Thanks. Can you modify the query to only include games that were released after the year 2020?

[Assistant] SELECT g.genre, COUNT(gs.session_id) AS session_count, COUNT(DISTINCT gs.player_id) AS player_count FROM gaming_technology.game_sessions AS gs JOIN gaming_technology.games AS g ON gs.game_id = g.game_id WHERE g.genre IS NOT NULL AND g.release_date >= '2021-01-01' GROUP BY g.genre ORDER BY g.genre;

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


[User] Show the agent_id, first name, and last name for all agents who were hired before January 1, 2020.

[Assistant] SELECT agent_id, first_name, last_name FROM insurance.agents WHERE hire_date < '2020-01-01';

[User] Additionally, only include agents who have a commission rate greater than 0.05.

[Assistant] SELECT agent_id, first_name, last_name FROM insurance.agents WHERE hire_date < '2020-01-01' AND commission_rate > 0.05;

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


[User] List all rooms, including their room number, the name of the property they belong to, and their room type name, specifically for rooms with 'Maintenance' status.

[Assistant] SELECT T1.room_number, T2.property_name, T3.type_name FROM rooms AS T1 JOIN properties AS T2 ON T1.property_id = T2.property_id JOIN room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.status = 'Maintenance'

[User] Also include the floor number and filter to only show rooms located on floors 5 or higher. Sort the results by property name and then by floor.

[Assistant] SELECT T1.room_number, T2.property_name, T3.type_name, T1.floor FROM rooms AS T1 JOIN properties AS T2 ON T1.property_id = T2.property_id JOIN room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.status = 'Maintenance' AND T1.floor >= 5 ORDER BY T2.property_name, T1.floor

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


[User] Summarize trade activity by account and execution venue, showing the total quantity of shares traded and the average commission paid.

[Assistant] SELECT account_id, execution_venue, SUM(quantity) AS total_quantity, AVG(commission) AS average_commission FROM financial_services.trades GROUP BY account_id, execution_venue;

[User] Refine that report to only include trades where the total_amount for a single trade was greater than 5000. Also, only show account/venue groups where the total quantity traded is at least 100.

[Assistant] SELECT account_id, execution_venue, SUM(quantity) AS total_quantity, AVG(commission) AS average_commission FROM financial_services.trades WHERE total_amount > 5000 GROUP BY account_id, execution_venue HAVING SUM(quantity) >= 100;

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.trades ( trade_id text, 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 )


[User] Can you show me each user's address and the date their wallet was created?

[Assistant] SELECT user_id, address, created_at FROM trading_platform.wallets;

[User] Now, can you show only wallets created after '2024-01-01' and include the user_id and address?

[Assistant] SELECT user_id, address, created_at FROM trading_platform.wallets WHERE created_at > '2024-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )


[User] Show me the first name, last name, and email for all clients registered in January 2023.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1;

[User] Only show those who have provided a phone number.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1 AND phone IS NOT NULL;

[User] Also, exclude any clients whose status is 'inactive'.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1 AND phone IS NOT NULL AND status != 'inactive';

[User] Order the results by last name, then first name.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1 AND phone IS NOT NULL AND status != 'inactive' ORDER BY last_name, first_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 legal_services.clients (
    client_id character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_id)
)


[User] List all customers who reside in New York and were created in the system before 2023.

[Assistant] SELECT customer_id, first_name, last_name, created_at FROM insurance.customers WHERE state = 'NY' AND created_at < '2023-01-01';

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


[User] List all guests who have not provided their date of birth, along with their email if available.

[Assistant] SELECT guest_id, first_name, last_name, email FROM hospitality_technology.guests WHERE date_of_birth IS NULL;

[User] Now, filter these results to only include guests from the USA.

[Assistant] SELECT guest_id, first_name, last_name, email FROM hospitality_technology.guests WHERE date_of_birth IS NULL AND country_code = 'USA';

[User] The query is missing their city information. Can you include that as well?

[Assistant] SELECT guest_id, first_name, last_name, email, city FROM hospitality_technology.guests WHERE date_of_birth IS NULL AND country_code = 'USA';

[User] Actually, I need to see the results ordered by created_at in descending order.

[Assistant] SELECT guest_id, first_name, last_name, email, city, created_at FROM hospitality_technology.guests WHERE date_of_birth IS NULL AND country_code = 'USA' ORDER BY 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 hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )


[User] List all token transfers with values greater than 1000, including the token ID and transaction ID.

[Assistant] SELECT transfer_id, token_id, transaction_id, value FROM web3.token_transfers WHERE value > 1000;

[User] Actually, I also need to see the event names associated with these transactions.

[Assistant] SELECT tt.transfer_id, tt.token_id, tt.transaction_id, tt.value, e.event_name FROM web3.token_transfers tt LEFT JOIN web3.events e ON tt.transaction_id = e.transaction_id WHERE tt.value > 1000;

[User] There's a typo in your SQL, it should be 'token_transfers' not 'token_transfers'. Also, sort the results by value in descending order.

[Assistant] SELECT tt.transfer_id, tt.token_id, tt.transaction_id, tt.value, e.event_name FROM web3.token_transfers tt LEFT JOIN web3.events e ON tt.transaction_id = e.transaction_id WHERE tt.value > 1000 ORDER BY tt.value DESC;

[User] Now filter to only show transfers that have at least one associated event.

[Assistant] SELECT tt.transfer_id, tt.token_id, tt.transaction_id, tt.value, e.event_name FROM web3.token_transfers tt JOIN web3.events e ON tt.transaction_id = e.transaction_id WHERE tt.value > 1000 ORDER BY tt.value DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.events ( event_id text PRIMARY KEY, contract_id text, event_name text, data text, emitted_at timestamp, transaction_id text, log_index int )
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )


[User] List all premium payments for policy 'POL123'. Show payment ID, payment date, amount paid, and status.

[Assistant] SELECT payment_id, payment_date, amount_paid, status FROM insurance.premium_payments WHERE policy_id = 'POL123';

[User] Only show payments made on or after January 1, 2024.

[Assistant] SELECT payment_id, payment_date, amount_paid, status FROM insurance.premium_payments WHERE policy_id = 'POL123' AND payment_date >= '2024-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)


[User] Show me each loyalty program ID along with the full names of all passengers enrolled in that program.

[Assistant] SELECT loyalty_program_id, first_name, last_name FROM transportation.passengers WHERE loyalty_program_id IS NOT NULL ORDER BY loyalty_program_id, last_name, first_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 transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)


[User] What is the schedule of trains arriving at platform 1A at station XYZ on December 25th, 2023?

[Assistant] I'm sorry, but I can't provide information about train schedules or specific arrival times as this data is not included in the platform management table. For train schedules, please refer to the train timetable or contact the station's customer service.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.platforms (
    platform_id character varying(64) NOT NULL, -- Unique identifier for the platform
    station_id character varying(64) NOT NULL, -- Foreign key referencing stations
    platform_number character varying(10) NOT NULL, -- Platform identifier (e.g., '1A', '5')
    track_number character varying(10), -- Associated track number, if different
    status character varying(32) NOT NULL DEFAULT 'Operational', -- e.g., Operational, Maintenance, Closed
    length_meters numeric(8,2), -- Length of the platform in meters
    accessible boolean NOT NULL DEFAULT false, -- Is the platform accessible (e.g., wheelchair)?
    PRIMARY KEY (platform_id),
    FOREIGN KEY (station_id) REFERENCES train_station_management.stations(station_id)
)


[User] Get a list of room types along with their property name and the count of rooms currently Available for each type.

[Assistant]
SELECT rt.type_name, p.property_name, COUNT(r.room_id) AS available_rooms_count
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.rooms r ON rt.room_type_id = r.room_type_id
  AND r.status = 'Available'
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
GROUP BY rt.type_name, p.property_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.room_types ( room_type_id character varying(64) NOT NULL, 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, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_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.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] List all ERC20 tokens where the price is between $1 and $10, including their names, symbols, and contract addresses.

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price BETWEEN 1 AND 10;

[User] I think there's an error in your query - it should be joining with token_prices_latest on address not contract_address. Also, can you add the current price to the results?

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price BETWEEN 1 AND 10;

[User] Now filter these results to only show tokens with decimals equal to 18 and sort by name alphabetically.

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price BETWEEN 1 AND 10 AND tm.decimals = 18 ORDER BY tm.name ASC;

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


[User] Show me all claims handled by agent 'AG123' along with their settlement details and policy IDs.

[Assistant] SELECT claim_id, policy_id, settlement_amount, settlement_date FROM insurance.claims WHERE claim_handler_id = 'AG123';

[User] Now filter these to only show claims that were settled for more than $5,000 and include the incident description.

[Assistant] SELECT claim_id, policy_id, settlement_amount, settlement_date, description FROM insurance.claims WHERE claim_handler_id = 'AG123' AND settlement_amount > 5000;

[User] I also want to see how long it took to settle these claims (difference between reported_date and settlement_date in days).

[Assistant] SELECT claim_id, policy_id, settlement_amount, settlement_date, description, EXTRACT(DAY FROM (settlement_date - reported_date)) AS days_to_settle FROM insurance.claims WHERE claim_handler_id = 'AG123' AND settlement_amount > 5000;

[User] Finally, order the results by the longest settlement time first and include only claims that took more than 30 days to settle.

[Assistant] SELECT claim_id, policy_id, settlement_amount, settlement_date, description, EXTRACT(DAY FROM (settlement_date - reported_date)) AS days_to_settle FROM insurance.claims WHERE claim_handler_id = 'AG123' AND settlement_amount > 5000 AND (settlement_date - reported_date) > INTERVAL '30 days' ORDER BY days_to_settle 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.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) )


[User] For each fundraising round in 2022 and 2023, list the round name, the year, the total investment_value, and the count of distinct projects. Also include the average market_cap of associated tokens by matching project_name to token_symbol in token_basic_info.

[Assistant]
SELECT p.rounds_name,
  SUBSTRING(p.investment_date FROM 1 FOR 4) AS year,
  SUM(p.investment_value) AS total_investment,
  COUNT(DISTINCT p.project_id) AS project_count,
  AVG(t.market_cap) AS avg_market_cap
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) = LOWER(t.token_symbol)
WHERE SUBSTRING(p.investment_date FROM 1 FOR 4) IN ('2022','2023')
GROUP BY p.rounds_name, SUBSTRING(p.investment_date FROM 1 FOR 4);

[User] The join returns no rows. Please change the join to match when token_symbol is contained within project_name, case-insensitive.

[Assistant]
SELECT p.rounds_name,
  SUBSTRING(p.investment_date FROM 1 FOR 4) AS year,
  SUM(p.investment_value) AS total_investment,
  COUNT(DISTINCT p.project_id) AS project_count,
  AVG(t.market_cap) AS avg_market_cap
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) LIKE '%' || LOWER(t.token_symbol) || '%'
WHERE SUBSTRING(p.investment_date FROM 1 FOR 4) IN ('2022','2023')
GROUP BY p.rounds_name, SUBSTRING(p.investment_date FROM 1 FOR 4);

[User] Now only include rounds where the total investment_value exceeds 5000000.

[Assistant]
SELECT p.rounds_name,
  SUBSTRING(p.investment_date FROM 1 FOR 4) AS year,
  SUM(p.investment_value) AS total_investment,
  COUNT(DISTINCT p.project_id) AS project_count,
  AVG(t.market_cap) AS avg_market_cap
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) LIKE '%' || LOWER(t.token_symbol) || '%'
WHERE SUBSTRING(p.investment_date FROM 1 FOR 4) IN ('2022','2023')
GROUP BY p.rounds_name, SUBSTRING(p.investment_date FROM 1 FOR 4)
HAVING SUM(p.investment_value) > 5000000;

[User] Finally, order the results by total_investment descending.

[Assistant]
SELECT p.rounds_name,
  SUBSTRING(p.investment_date FROM 1 FOR 4) AS year,
  SUM(p.investment_value) AS total_investment,
  COUNT(DISTINCT p.project_id) AS project_count,
  AVG(t.market_cap) AS avg_market_cap
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) LIKE '%' || LOWER(t.token_symbol) || '%'
WHERE SUBSTRING(p.investment_date FROM 1 FOR 4) IN ('2022','2023')
GROUP BY p.rounds_name, SUBSTRING(p.investment_date FROM 1 FOR 4)
HAVING SUM(p.investment_value) > 5000000
ORDER BY total_investment 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 project_fundraising_record ( id character varying(32) NOT NULL, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
 "CREATE TABLE narrative_info (",
    "narrative character varying(512) NOT NULL, -- the id of narrative",
    "top_3_coins text, -- the top 3 tokens in the narrative",
    "price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative",
    "price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative",
    "price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative",
    "market_cap double precision, -- the market cap of the narrative",
    "volume_24h double precision, -- the trade volume of the narrative",
    "trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative",
    "token_num bigint, -- total token number in the narrative",
    ",PRIMARY KEY (narrative));"

CREATE TABLE 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) )
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )
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] I want to find the total number of ERC1155 "approval-for-all" events per contract. Show contract_address and the approval_count.

[Assistant]
SELECT contract_address, COUNT(*) AS approval_count
FROM erc1155_approval_for_all
GROUP BY contract_address;

[User] Also show the number of unique wallet holders currently holding any token from those contracts by joining to nft_holders.

[Assistant]
SELECT a.contract_address,
       a.approval_count,
       COALESCE(b.holder_count, 0) AS holder_count
FROM (
  SELECT contract_address, COUNT(*) AS approval_count
  FROM erc1155_approval_for_all
  GROUP BY contract_address
) a
LEFT JOIN (
  SELECT contract_address, COUNT(DISTINCT wallet_address) AS holder_count
  FROM nft_holders
  GROUP BY contract_address
) b
  ON a.contract_address = b.contract_address;

[User] Filter to only include contracts where holder_count is greater than 50.

[Assistant]
SELECT a.contract_address,
       a.approval_count,
       b.holder_count
FROM (
  SELECT contract_address, COUNT(*) AS approval_count
  FROM erc1155_approval_for_all
  GROUP BY contract_address
) a
JOIN (
  SELECT contract_address, COUNT(DISTINCT wallet_address) AS holder_count
  FROM nft_holders
  GROUP BY contract_address
  HAVING COUNT(DISTINCT wallet_address) > 50
) b
  ON a.contract_address = b.contract_address;

[User] Sort results by approval_count descending and limit to the top 10.

[Assistant]
SELECT a.contract_address,
       a.approval_count,
       b.holder_count
FROM (
  SELECT contract_address, COUNT(*) AS approval_count
  FROM erc1155_approval_for_all
  GROUP BY contract_address
) a
JOIN (
  SELECT contract_address, COUNT(DISTINCT wallet_address) AS holder_count
  FROM nft_holders
  GROUP BY contract_address
  HAVING COUNT(DISTINCT wallet_address) > 50
) b
  ON a.contract_address = b.contract_address
ORDER BY a.approval_count DESC
LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE erc20_balances_historical ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_metadata (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    token_id varchar NOT NULL, -- The number of the token
    contract_name varchar NOT NULL, -- contract_name fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    amount bigint NOT NULL, -- amount fields for the functionType  in contract
    minter varchar NOT NULL, -- minter fields for the functionType  in contract
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    mint_block_number bigint NOT NULL, -- mint_block_number fields for the functionType  in contract
    mint_time bigint NOT NULL, -- mint_time fields for the functionType  in contract
    mint_transaction_hash varchar NOT NULL, -- mint_transaction_hash fields for the functionType  in contract
    mint_price varchar NOT NULL, -- mint_price fields for the functionType  in contract
    token_uri varchar NOT NULL, -- token_uri fields for the functionType  in contract
    metadata varchar NOT NULL, -- metadata fields for the functionType  in contract
    name varchar NOT NULL, -- name fields for the functionType  in contract
    image_uri varchar NOT NULL, -- image_uri fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    status varchar NOT NULL, -- status fields for the functionType  in contract
    rarity_score real NOT NULL, -- rarity_score fields for the functionType  in contract
    rarity_rank integer NOT NULL, -- rarity_rank fields for the functionType  in contract
    unique_attribute_count integer NOT NULL, -- unique_attribute_count fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(mint_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )


[User] For each service location, find its nearest accessible location by geographic distance.

[Assistant]
SELECT sl.location_id,
       sl.location_name,
       nearest.location_id   AS nearest_location_id,
       nearest.location_name AS nearest_location_name
FROM government_services.service_locations sl
JOIN LATERAL (
  SELECT sl2.location_id,
         sl2.location_name
  FROM government_services.service_locations sl2
  WHERE sl2.is_accessible = TRUE
    AND sl2.location_id <> sl.location_id
  ORDER BY ((sl.latitude - sl2.latitude)^2 + (sl.longitude - sl2.longitude)^2) ASC
  LIMIT 1
) AS nearest ON TRUE;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )


[User] Show each citizen's first and last notification IDs based on sent_at.

[Assistant]
WITH bounds AS (
  SELECT citizen_id,
         MIN(sent_at) AS first_sent,
         MAX(sent_at) AS last_sent
  FROM government_services.notifications
  GROUP BY citizen_id
)
SELECT n1.citizen_id,
       n1.notification_id AS first_notification_id,
       n2.notification_id AS last_notification_id
FROM bounds b
JOIN government_services.notifications n1
  ON n1.citizen_id = b.citizen_id
 AND n1.sent_at = b.first_sent
JOIN government_services.notifications n2
  ON n2.citizen_id = b.citizen_id
 AND n2.sent_at = b.last_sent;

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


[User] Show me all available spa services (category = 'Wellness') with their names and prices, ordered by price in descending order.

[Assistant] SELECT service_name, price FROM hospitality_technology.services WHERE category = 'Wellness' AND is_available = true ORDER BY price DESC;

[User] Now, include only services from properties with ID starting with 'PROP1' and show their property IDs as well.

[Assistant] SELECT service_name, price, property_id FROM hospitality_technology.services WHERE category = 'Wellness' AND is_available = true AND property_id LIKE 'PROP1%' ORDER BY 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.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 names of services and the total number of times each service has been ordered. Only include services that have been ordered at least once.

[Assistant] SELECT T1.service_name, count(T2.order_id) AS order_count FROM hospitality_technology.services AS T1 JOIN hospitality_technology.service_orders AS T2 ON T1.service_id = T2.service_id GROUP BY T1.service_name;

[User] Now, filter this list to only show services from the 'Food & Beverage' or 'Activities' categories, and sort by the order count in descending order.

[Assistant] SELECT T1.service_name, count(T2.order_id) AS order_count FROM hospitality_technology.services AS T1 JOIN hospitality_technology.service_orders AS T2 ON T1.service_id = T2.service_id WHERE T1.category IN ('Food & Beverage', 'Activities') GROUP BY T1.service_name ORDER BY order_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.room_types ( room_type_id character varying(64) NOT NULL, 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, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_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 character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, bill_id character varying(64), amount numeric(12,2) NOT NULL, currency_code character varying(3) NOT NULL, payment_method character varying(50) NOT NULL, card_type character varying(50), card_last_four character varying(4), transaction_ref character varying(128), payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, status character varying(50) NOT NULL, staff_id_processed character varying(64), notes text, PRIMARY KEY (payment_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] Show me all appointments for doctor 'doctor_100' in June 2024, including the appointment time and the patient ID.

[Assistant]
SELECT appointment_id, patient_id, appointment_time
FROM healthcare.appointments
WHERE doctor_id = 'doctor_100'
  AND appointment_time >= '2024-06-01'::timestamp
  AND appointment_time < '2024-07-01'::timestamp;

[User] Can you also add the appointment status and sort by appointment_time ascending?

[Assistant]
SELECT appointment_id, patient_id, appointment_time, status
FROM healthcare.appointments
WHERE doctor_id = 'doctor_100'
  AND appointment_time >= '2024-06-01'::timestamp
  AND appointment_time < '2024-07-01'::timestamp
ORDER BY appointment_time ASC;

[User] Now, only include the appointments with status 'Completed'.

[Assistant]
SELECT appointment_id, patient_id, appointment_time, status
FROM healthcare.appointments
WHERE doctor_id = 'doctor_100'
  AND appointment_time >= '2024-06-01'::timestamp
  AND appointment_time < '2024-07-01'::timestamp
  AND status = 'Completed'
ORDER BY appointment_time ASC;

[User] I got an empty result, but I expected at least one appointment. Could you check if the status value is in lowercase instead?

[Assistant]
SELECT appointment_id, patient_id, appointment_time, status
FROM healthcare.appointments
WHERE doctor_id = 'doctor_100'
  AND appointment_time >= '2024-06-01'::timestamp
  AND appointment_time < '2024-07-01'::timestamp
  AND LOWER(status) = 'completed'
ORDER BY appointment_time ASC;

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.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)


[User] List all pairs of properties located in the same city, showing each pair's property IDs and names along with the city.

[Assistant]
SELECT p1.property_id AS property_id_1,
       p1.property_name AS property_name_1,
       p2.property_id AS property_id_2,
       p2.property_name AS property_name_2,
       p1.city
FROM hospitality_technology.properties p1
JOIN hospitality_technology.properties p2
  ON p1.city = p2.city
 AND p1.property_id < p2.property_id;

[User] Only include pairs in cities that have more than two properties.

[Assistant]
SELECT p1.property_id AS property_id_1,
       p1.property_name AS property_name_1,
       p2.property_id AS property_id_2,
       p2.property_name AS property_name_2,
       p1.city
FROM hospitality_technology.properties p1
JOIN hospitality_technology.properties p2
  ON p1.city = p2.city
 AND p1.property_id < p2.property_id
WHERE p1.city IN (
  SELECT city
  FROM hospitality_technology.properties
  GROUP BY city
  HAVING COUNT(*) > 2
);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )


[User] List the vehicle_id, make, model, and total maintenance cost for each vehicle that has undergone maintenance, ordering by total maintenance cost descending.

[Assistant]
SELECT m.vehicle_id, v.make, v.model, SUM(m.cost) AS total_maintenance_cost
FROM transportation.maintenance_logs m
JOIN transportation.vehicles v ON m.vehicle_id = v.vehicle_id
GROUP BY m.vehicle_id, v.make, v.model
ORDER BY total_maintenance_cost DESC;

[User] Now further include the count of maintenance entries per vehicle and only include vehicles with more than 3 maintenance logs.

[Assistant]
SELECT m.vehicle_id, v.make, v.model, COUNT(*) AS maintenance_count, SUM(m.cost) AS total_maintenance_cost
FROM transportation.maintenance_logs m
JOIN transportation.vehicles v ON m.vehicle_id = v.vehicle_id
GROUP BY m.vehicle_id, v.make, v.model
HAVING COUNT(*) > 3
ORDER BY total_maintenance_cost 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 text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.maintenance_logs ( log_id text, vehicle_id text, service_date date, odometer_reading integer, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
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] How many customers are there for each status?

[Assistant] SELECT status, COUNT(*) FROM financial_services.customers GROUP BY status

[User] Only show statuses where the count is greater than 50.

[Assistant] SELECT status, COUNT(*) FROM financial_services.customers GROUP BY status HAVING COUNT(*) > 50

[User] Sort the results by the count in descending order.

[Assistant] SELECT status, COUNT(*) FROM financial_services.customers GROUP BY status HAVING COUNT(*) > 50 ORDER BY COUNT(*) DESC

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


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

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

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


[User] List all agents who have been terminated, showing their full name, agency name, and termination date.

[Assistant]
SELECT first_name, last_name, agency_name, termination_date
FROM insurance.agents
WHERE 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 insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )


[User] Show prescriptions with their corresponding chief complaint from the medical record. Return prescription_id, record_id, and chief_complaint.

[Assistant]
SELECT p.prescription_id, p.record_id, mr.chief_complaint
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id;

[User] Only include prescriptions where chief_complaint contains 'fever' and the route is 'Oral'.

[Assistant]
SELECT p.prescription_id, p.record_id, mr.chief_complaint
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id
WHERE mr.chief_complaint ILIKE '%fever%'
  AND p.route = 'Oral';

[User] Also include the medication_name by joining the medications table and sort the results by prescription_date ascending.

[Assistant]
SELECT p.prescription_id,
       p.record_id,
       mr.chief_complaint,
       m.medication_name
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id
LEFT JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE mr.chief_complaint ILIKE '%fever%'
  AND p.route = 'Oral'
ORDER BY p.prescription_date ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] List all smart money addresses with a profit over $500,000, including their chain and last trade time.

[Assistant] SELECT address, chain, last_trade_time FROM smart_money_profit WHERE profit > 500000;

[User] I only want to see addresses from Ethereum or Binance chains.

[Assistant] SELECT address, chain, last_trade_time FROM smart_money_profit WHERE profit > 500000 AND chain IN ('Ethereum', 'Binance');

[User] Can you also include their rank and order by rank instead?

[Assistant] SELECT address, chain, last_trade_time, rank FROM smart_money_profit WHERE profit > 500000 AND chain IN ('Ethereum', 'Binance') ORDER BY rank;

[User] Actually, just show me the top 3 by rank.

[Assistant] SELECT address, chain, last_trade_time, rank FROM smart_money_profit WHERE profit > 500000 AND chain IN ('Ethereum', 'Binance') ORDER BY rank 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 smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )


[User] Show me all documents uploaded by lawyers from law firms located in 'New York'. Include the document name, upload timestamp, the first and last name of the uploading lawyer, and the firm name.

[Assistant] SELECT d.document_name, d.upload_timestamp, l.first_name AS lawyer_first_name, l.last_name AS lawyer_last_name, lf.firm_name FROM documents AS d JOIN lawyers AS l ON d.uploaded_by_lawyer_id = l.lawyer_id JOIN law_firms AS lf ON l.firm_id = lf.firm_id WHERE lf.address LIKE '%New York%';

[User] Okay, but only show documents where the document type is 'Contract'.

[Assistant] SELECT d.document_name, d.upload_timestamp, l.first_name AS lawyer_first_name, l.last_name AS lawyer_last_name, lf.firm_name FROM documents AS d JOIN lawyers AS l ON d.uploaded_by_lawyer_id = l.lawyer_id JOIN law_firms AS lf ON l.firm_id = lf.firm_id WHERE lf.address LIKE '%New York%' AND d.document_type = 'Contract';

[User] Also, sort the results by upload timestamp descending and include the document version.

[Assistant] SELECT d.document_name, d.upload_timestamp, d.version, l.first_name AS lawyer_first_name, l.last_name AS lawyer_last_name, lf.firm_name FROM documents AS d JOIN lawyers AS l ON d.uploaded_by_lawyer_id = l.lawyer_id JOIN law_firms AS lf ON l.firm_id = lf.firm_id WHERE lf.address LIKE '%New York%' AND d.document_type = 'Contract' ORDER BY d.upload_timestamp DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )