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

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

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

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

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

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

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

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

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


[User] How many likes were given to comments in June 2024?

[Assistant]
SELECT COUNT(*) AS comment_likes_count
FROM social_media.likes
WHERE comment_id IS NOT NULL
  AND DATE_TRUNC('month', created_at) = '2024-06-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 social_media.comments ( comment_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, parent_comment_id character varying(64), content text NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (comment_id) )
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
CREATE TABLE social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )


[User] List the names of service locations and categories of active services offered by the same agency.

[Assistant]
SELECT sl.location_name, s.category
FROM government_services.service_locations AS sl
JOIN government_services.services AS s
  ON sl.agency_id = s.agency_id
WHERE s.is_active = TRUE;

[User] Please exclude service locations that are not accessible.

[Assistant]
SELECT sl.location_name, s.category
FROM government_services.service_locations AS sl
JOIN government_services.services AS s
  ON sl.agency_id = s.agency_id
WHERE s.is_active = TRUE
  AND sl.is_accessible = 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.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, 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.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)


[User] Get the total trading volume and average close_price for each data source over the last quarter.

[Assistant]
SELECT source,
       SUM(volume) AS total_volume,
       AVG(close_price) AS avg_close_price
FROM financial_services.market_data
WHERE data_timestamp >= DATE_TRUNC('quarter', CURRENT_DATE - INTERVAL '3 months')
  AND data_timestamp < DATE_TRUNC('quarter', CURRENT_DATE)
GROUP BY source;

[User] Exclude any sources that have fewer than 100 data points in that period.

[Assistant]
SELECT source,
       SUM(volume) AS total_volume,
       AVG(close_price) AS avg_close_price,
       COUNT(*) AS point_count
FROM financial_services.market_data
WHERE data_timestamp >= DATE_TRUNC('quarter', CURRENT_DATE - INTERVAL '3 months')
  AND data_timestamp < DATE_TRUNC('quarter', CURRENT_DATE)
GROUP BY source
HAVING COUNT(*) >= 100;

[User] Finally, sort by total_volume descending and limit to the top 5 sources.

[Assistant]
SELECT source,
       SUM(volume) AS total_volume,
       AVG(close_price) AS avg_close_price
FROM financial_services.market_data
WHERE data_timestamp >= DATE_TRUNC('quarter', CURRENT_DATE - INTERVAL '3 months')
  AND data_timestamp < DATE_TRUNC('quarter', CURRENT_DATE)
GROUP BY source
HAVING COUNT(*) >= 100
ORDER BY total_volume DESC
LIMIT 5;

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


[User] Show employees hired before 2020 along with their manager's full name.

[Assistant] SELECT e.first_name, e.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.hire_date < '2020-01-01';

[User] Only include employees whose manager's job title is 'Branch Manager'.

[Assistant] SELECT e.first_name, e.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.hire_date < '2020-01-01' AND m.job_title = 'Branch Manager';

[User] Also, only show employees who are 'Active'.

[Assistant] SELECT e.first_name, e.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.hire_date < '2020-01-01' AND m.job_title = 'Branch Manager' AND e.status = 'Active';

[User] Include the employee's job title and order the results by hire date ascending.

[Assistant] SELECT e.first_name, e.last_name, e.job_title, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.hire_date < '2020-01-01' AND m.job_title = 'Branch Manager' AND e.status = 'Active' ORDER BY e.hire_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 financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)


[User] For each asset, calculate the total quantity and average price of orders that have status 'filled'.

[Assistant]
SELECT o.asset_id,
       SUM(o.quantity) AS total_quantity,
       AVG(o.price)     AS average_price
FROM trading_platform.orders o
WHERE o.status = 'filled'
GROUP BY o.asset_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications (
    notification_id character varying(64) NOT NULL,  -- unique identifier for the notification
    user_id character varying(64) NOT NULL, -- identifier of the user receiving the notification
    message text NOT NULL, -- message of the notification
    sent_at timestamp NOT NULL, -- time when the notification was sent
    read_at timestamp, -- time when the notification was read
    PRIMARY KEY (notification_id)
)


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

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

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

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

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

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

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


[User] Find all wallets created by users in the last 7 days along with any tokens that have a total supply greater than 10 million, showing the wallet address and token details.

[Assistant] SELECT w.address AS wallet_address, t.token_name, t.token_symbol, t.total_supply, t.contract_address FROM web3.wallets w JOIN web3.tokens t ON t.total_supply > 10000000 WHERE w.created_at >= CURRENT_DATE - INTERVAL '7 days';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.tokens ( token_id character varying(64) NOT NULL, contract_address character varying(128) NOT NULL, token_name character varying(128) NOT NULL, token_symbol character varying(32) NOT NULL, decimals integer NOT NULL, total_supply numeric(38,14) NOT NULL, PRIMARY KEY (token_id) )
CREATE TABLE web3.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )


[User] Can you show me the count of items and the average cost_amount for each item_type and rarity?

[Assistant]
SELECT item_type, rarity, COUNT(*) AS item_count, AVG(cost_amount) AS avg_cost_amount
FROM gaming_technology.in_game_items
GROUP BY item_type, rarity;

[User] Actually, could you also include the minimum and maximum cost_amount in the results?

[Assistant]
SELECT item_type, rarity, COUNT(*) AS item_count, AVG(cost_amount) AS avg_cost_amount, MIN(cost_amount) AS min_cost_amount, MAX(cost_amount) AS max_cost_amount
FROM gaming_technology.in_game_items
GROUP BY item_type, rarity;

[User] Now I only want to see groups where the average cost_amount is greater than 50.

[Assistant]
SELECT item_type, rarity, COUNT(*) AS item_count, AVG(cost_amount) AS avg_cost_amount, MIN(cost_amount) AS min_cost_amount, MAX(cost_amount) AS max_cost_amount
FROM gaming_technology.in_game_items
GROUP BY item_type, rarity
HAVING AVG(cost_amount) > 50;

[User] Finally, exclude any groups where rarity is null.

[Assistant]
SELECT item_type, rarity, COUNT(*) AS item_count, AVG(cost_amount) AS avg_cost_amount, MIN(cost_amount) AS min_cost_amount, MAX(cost_amount) AS max_cost_amount
FROM gaming_technology.in_game_items
WHERE rarity IS NOT NULL
GROUP BY item_type, rarity
HAVING AVG(cost_amount) > 50
ORDER BY avg_cost_amount DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )


[User] For each guest, calculate their total spending on delivered service orders and the total number of those orders.

[Assistant]
SELECT g.guest_id,
       g.first_name || ' ' || g.last_name AS full_name,
       SUM(so.total_price) AS total_spent,
       COUNT(*) AS total_orders
FROM hospitality_technology.guests g
JOIN hospitality_technology.service_orders so
  ON g.guest_id = so.guest_id
WHERE so.status = 'delivered'
GROUP BY g.guest_id, full_name;

[User] I need the breakdown by month for the current year. Show guest ID, month, total spent, and total orders.

[Assistant]
SELECT so.guest_id,
       DATE_TRUNC('month', so.delivery_timestamp) AS month,
       SUM(so.total_price) AS total_spent,
       COUNT(*) AS total_orders
FROM hospitality_technology.service_orders so
WHERE so.status = 'delivered'
  AND so.delivery_timestamp >= '2024-01-01'
  AND so.delivery_timestamp < '2025-01-01'
GROUP BY so.guest_id, month
ORDER BY month;

[User] Also include the guest’s email and only show months where total spent is greater than 500.

[Assistant]
SELECT sub.guest_id,
       g.email,
       sub.month,
       sub.total_spent,
       sub.total_orders
FROM (
  SELECT so.guest_id,
         DATE_TRUNC('month', so.delivery_timestamp) AS month,
         SUM(so.total_price) AS total_spent,
         COUNT(*) AS total_orders
  FROM hospitality_technology.service_orders so
  WHERE so.status = 'delivered'
    AND so.delivery_timestamp >= '2024-01-01'
    AND so.delivery_timestamp < '2025-01-01'
  GROUP BY so.guest_id, month
) sub
JOIN hospitality_technology.guests g
  ON sub.guest_id = g.guest_id
WHERE sub.total_spent > 500
ORDER BY sub.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 hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.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] Find all pairs of transactions where both transactions have the same nonce and from_address, but different transaction_id. Show both transaction IDs, the shared from_address, shared nonce, and their block numbers.

[Assistant]
SELECT t1.transaction_id AS transaction_id_1, t2.transaction_id AS transaction_id_2, t1.from_address, t1.nonce, t1.block_number AS block_number_1, t2.block_number AS block_number_2
FROM web3.transactions t1
JOIN web3.transactions t2
  ON t1.from_address = t2.from_address
 AND t1.nonce = t2.nonce
 AND t1.transaction_id < t2.transaction_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_id)
)


[User] Find all documents of type 'Correspondence' uploaded in 2023. Show the document name, upload timestamp, and the name of the case it belongs to.

[Assistant] SELECT T1.document_name, T1.upload_timestamp, T2.case_name FROM legal_services.documents AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id WHERE T1.document_type = 'Correspondence' AND EXTRACT(YEAR FROM T1.upload_timestamp) = 2023;

[User] Now, only show the documents for cases handled by lawyer with ID 'lawyer_001'.

[Assistant] SELECT T1.document_name, T1.upload_timestamp, T2.case_name FROM legal_services.documents AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id WHERE T1.document_type = 'Correspondence' AND EXTRACT(YEAR FROM T1.upload_timestamp) = 2023 AND T2.lead_lawyer_id = 'lawyer_001';

[User] Additionally, include the first and last name of the lawyer who actually uploaded the document, and sort the results by upload timestamp descending.

[Assistant] SELECT T1.document_name, T1.upload_timestamp, T2.case_name, T3.first_name, T3.last_name FROM legal_services.documents AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id JOIN legal_services.lawyers AS T3 ON T1.uploaded_by_lawyer_id = T3.lawyer_id WHERE T1.document_type = 'Correspondence' AND EXTRACT(YEAR FROM T1.upload_timestamp) = 2023 AND T2.lead_lawyer_id = 'lawyer_001' ORDER BY T1.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.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_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] Retrieve each agent's ID, full name, and the count of 'Pending' policies they have sold with a premium_amount greater than 2000. Order the results by the policy count descending.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       COUNT(p.policy_id) AS pending_policy_count
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE p.status = 'Pending'
  AND p.premium_amount > 2000
GROUP BY a.agent_id, agent_name
ORDER BY pending_policy_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 insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] List all wallets holding the NFT with contract_address '0xabc123' and token_id '100' and the amount held.

[Assistant]
SELECT wallet_address, amount
FROM nft_holders
WHERE contract_address = '0xabc123'
  AND token_id = '100';

[User] Also include the NFT name from nft_metadata by joining on contract_address and token_id.

[Assistant]
SELECT nh.wallet_address,
       nh.amount,
       nm.name
FROM nft_holders nh
JOIN nft_metadata nm ON nh.contract_address = nm.contract_address
                   AND nh.token_id = nm.token_id
WHERE nh.contract_address = '0xabc123'
  AND nh.token_id = '100';

[User] Finally, add the collection name from nft_collections where blockchain is 'Ethereum'.

[Assistant]
SELECT nh.wallet_address,
       nh.amount,
       nm.name,
       nc.name AS collection_name
FROM nft_holders nh
JOIN nft_metadata nm ON nh.contract_address = nm.contract_address
                   AND nh.token_id = nm.token_id
JOIN nft_collections nc ON nh.contract_address = nc.contract_address
                      AND nc.blockchain = 'Ethereum'
WHERE nh.contract_address = '0xabc123'
  AND nh.token_id = '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 erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata ( object_id varchar NOT NULL, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id varchar NOT NULL, status varchar NOT NULL, collection_type varchar NOT NULL, package_id varchar NOT NULL, previous_transaction varchar NOT NULL, display varchar NOT NULL, owner varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( 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 NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_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(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(255) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities_bitcoin ( 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(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )


[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] For each developer, can you find the next developer in the same country using a self join, returning developer_ids and names?

[Assistant]
SELECT d1.developer_id   AS current_dev,
       d1.name           AS current_name,
       d2.developer_id   AS next_dev,
       d2.name           AS next_name,
       d2.founded_year - d1.founded_year AS years_diff
FROM developers d1
JOIN developers d2
  ON d1.country = d2.country
  AND d2.founded_year > d1.founded_year;

[User] Exclude developers who don't have a next developer, and ensure we only pick the closest next by founded_year.

[Assistant]
SELECT d1.developer_id   AS current_dev,
       d1.name           AS current_name,
       d2.developer_id   AS next_dev,
       d2.name           AS next_name,
       d2.founded_year - d1.founded_year AS years_diff
FROM developers d1
JOIN LATERAL (
  SELECT d2.developer_id, d2.name, d2.founded_year
  FROM developers d2
  WHERE d2.country = d1.country
    AND d2.founded_year > d1.founded_year
  ORDER BY d2.founded_year ASC
  LIMIT 1
) d2 ON true;

[User] Finally, only include pairs where the difference in founded years is at most 5 years.

[Assistant]
SELECT d1.developer_id   AS current_dev,
       d1.name           AS current_name,
       d2.developer_id   AS next_dev,
       d2.name           AS next_name,
       d2.founded_year - d1.founded_year AS years_diff
FROM developers d1
JOIN LATERAL (
  SELECT d2.developer_id, d2.name, d2.founded_year
  FROM developers d2
  WHERE d2.country = d1.country
    AND d2.founded_year > d1.founded_year
  ORDER BY d2.founded_year ASC
  LIMIT 1
) d2 ON true
WHERE (d2.founded_year - d1.founded_year) <= 5
ORDER BY d1.developer_id, years_diff 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 gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )


[User] List all staff members who have responded to at least one review in the last 6 months, including their first and last names and the count of responses.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, COUNT(r.review_id) AS response_count
FROM hospitality_technology.reviews AS r
JOIN hospitality_technology.staff AS s
  ON r.response_staff_id = s.staff_id
WHERE r.response_date >= CURRENT_DATE - INTERVAL '6 months'
GROUP BY s.staff_id, s.first_name, s.last_name;

[User] Actually, only include responses to public reviews.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, COUNT(r.review_id) AS response_count
FROM hospitality_technology.reviews AS r
JOIN hospitality_technology.staff AS s
  ON r.response_staff_id = s.staff_id
WHERE r.response_date >= CURRENT_DATE - INTERVAL '6 months'
  AND r.is_public = TRUE
GROUP BY s.staff_id, s.first_name, s.last_name;

[User] Also include the average response time in days for each staff member.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name,
       COUNT(r.review_id) AS response_count,
       AVG(EXTRACT(EPOCH FROM (r.response_date - r.review_date)) / 86400) AS avg_response_days
FROM hospitality_technology.reviews AS r
JOIN hospitality_technology.staff AS s
  ON r.response_staff_id = s.staff_id
WHERE r.response_date >= CURRENT_DATE - INTERVAL '6 months'
  AND r.is_public = TRUE
GROUP BY s.staff_id, s.first_name, s.last_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


[User] Show me the top 10 transactions by gas price, including the from_address, to_address, and block_number, sorted in descending order.

[Assistant] SELECT from_address, to_address, block_number, gas_price FROM web3.transactions ORDER BY gas_price 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 web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )


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

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

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

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

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

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

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


[User] Show me the name and type for all the locations.

[Assistant] SELECT name, type FROM transportation.locations

[User] Now, filter this list to only include locations whose type is either 'Distribution Center' or 'Warehouse'.

[Assistant] SELECT name, type FROM transportation.locations WHERE type IN ('Distribution Center', 'Warehouse')

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.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )


[User] Show me all events emitted by contracts where the event name contains 'Approval', along with the contract ID and transaction ID, sorted by emitted timestamp in descending order.

[Assistant] SELECT event_id, contract_id, event_name, transaction_id, emitted_at FROM web3.events WHERE event_name LIKE '%Approval%' ORDER BY emitted_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)


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

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

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


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

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

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


[User] For each property, show the most expensive room type by base_rate, including the property name, room type name, and the highest base_rate.

[Assistant]
SELECT p.property_name,
       rt.type_name,
       MAX(rt.base_rate) AS max_base_rate
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p
  ON rt.property_id = p.property_id
GROUP BY 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 text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, 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 the top 5 users who have interacted with DApps, along with the count of distinct DApps they interacted with and their wallet addresses.

[Assistant] SELECT w.user_id, COUNT(DISTINCT d.dapp_id) AS dapp_count, w.address FROM trading_platform.wallets w JOIN trading_platform.dapps d ON 1=1 GROUP BY w.user_id, w.address ORDER BY dapp_count DESC LIMIT 5;

[User] This query doesn't properly show DApp interactions. Please modify it to correctly join with a table that records user-DApp interactions.

[Assistant] I notice there's no interaction table in the provided schema. Without a table recording user-DApp interactions, I cannot generate this query accurately. Would you like to see users who have wallets and DApps separately instead?

[User] You're right. Instead, show me users who have wallets but have never interacted with any DApps, along with their wallet addresses.

[Assistant] SELECT w.user_id, w.address FROM trading_platform.wallets w WHERE NOT EXISTS (SELECT 1 FROM trading_platform.dapps d WHERE 1=1) GROUP BY w.user_id, w.address;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.assets ( asset_id.text, name.text, symbol.text, type.text )
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )


[User] List all Sui NFT collections where the owner is not null, including their name and collection_type.

[Assistant] SELECT name, collection_type FROM sui_nfts WHERE owner IS NOT NULL;

[User] Can you also include the display field and filter to only show collections with a package_id starting with '0x'?

[Assistant] SELECT name, collection_type, display FROM sui_nfts WHERE owner IS NOT NULL AND package_id LIKE '0x%';

[User] Now sort these results by name in ascending order and limit to 10.

[Assistant] SELECT name, collection_type, display FROM sui_nfts WHERE owner IS NOT NULL AND package_id LIKE '0x%' ORDER BY name 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 token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
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_metadata ( object_id varchar NOT NULL, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_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_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_bitcoin (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_bitcoin (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(255) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities_bitcoin (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(62) NOT NULL, -- Address sending the inscription
    to_address varchar(62) NOT NULL  -- Address receiving the inscription
)
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )


[User] Count the number of logs for each action type.

[Assistant]
SELECT action,
       COUNT(*) AS count
FROM trading_platform.logs
GROUP BY action;

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.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )


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

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

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


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

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

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


[User] Provide every combination of medication name and insurance plan name.

[Assistant]
SELECT m.medication_name, p.plan_name
FROM healthcare.medications AS m
CROSS JOIN healthcare.insurance_plans AS p;

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.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )


[User] Show me all wallet addresses that belong to user_id 'U1001', along with their private keys.

[Assistant] SELECT address_id, private_key FROM blockchain.wallets WHERE user_id = 'U1001';

[User] Now join this with another table to show the count of transactions for each of these wallet addresses.

[Assistant] Note: The schema only includes the wallets table. Without a transactions table in the schema, this query cannot be executed. Please provide the transactions table structure if you need this analysis.

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.wallets ( wallet_id text, user_id text, address_id text, private_key text )


[User] How many diagnoses does each status have grouped by is_chronic flag?

[Assistant] SELECT is_chronic, status, COUNT(*) AS count FROM healthcare.diagnoses GROUP BY is_chronic, status;

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.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )


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

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

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

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

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

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

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

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

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


[User] I want to get the list of users and their total number of public posts made in the last month, including user_id and post_count.

[Assistant]
SELECT user_id, COUNT(*) AS post_count
FROM social_media.posts
WHERE visibility = 'public'
  AND created_at >= CURRENT_DATE - INTERVAL '1 month'
GROUP BY user_id;

[User] Actually, include only users whose email_notifications_enabled is true.

[Assistant]
SELECT p.user_id, COUNT(*) AS post_count
FROM social_media.posts p
JOIN social_media.user_settings u
  ON p.user_id = u.user_id
WHERE p.visibility = 'public'
  AND p.created_at >= CURRENT_DATE - INTERVAL '1 month'
  AND u.email_notifications_enabled = true
GROUP BY p.user_id;

[User] Also only consider posts that have media_type 'image'.

[Assistant]
SELECT p.user_id, COUNT(*) AS post_count
FROM social_media.posts p
JOIN social_media.user_settings u
  ON p.user_id = u.user_id
WHERE p.visibility = 'public'
  AND p.created_at >= CURRENT_DATE - INTERVAL '1 month'
  AND u.email_notifications_enabled = true
  AND p.media_type = 'image'
GROUP BY p.user_id;

[User] Order the results by post_count descending and limit to the top 10.

[Assistant]
SELECT p.user_id, COUNT(*) AS post_count
FROM social_media.posts p
JOIN social_media.user_settings u
  ON p.user_id = u.user_id
WHERE p.visibility = 'public'
  AND p.created_at >= CURRENT_DATE - INTERVAL '1 month'
  AND u.email_notifications_enabled = true
  AND p.media_type = 'image'
GROUP BY p.user_id
ORDER BY post_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 social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )


[User] List all room types that have at least one service in the 'Spa' category, including the room type name, property name, and service name.

[Assistant]
SELECT DISTINCT rt.type_name, p.property_name, s.service_name
FROM hospitality_technology.room_types AS rt
JOIN hospitality_technology.properties AS p ON rt.property_id = p.property_id
JOIN hospitality_technology.services AS s ON rt.property_id = s.property_id
WHERE s.category = 'Spa';

[User] Actually, only show room types with a base_rate above 200.

[Assistant]
SELECT DISTINCT rt.type_name, p.property_name, s.service_name
FROM hospitality_technology.room_types AS rt
JOIN hospitality_technology.properties AS p ON rt.property_id = p.property_id
JOIN hospitality_technology.services AS s ON rt.property_id = s.property_id
WHERE s.category = 'Spa'
  AND rt.base_rate > 200;

[User] Also sort the results by base_rate descending and limit to 10.

[Assistant]
SELECT DISTINCT rt.type_name, p.property_name, s.service_name
FROM hospitality_technology.room_types AS rt
JOIN hospitality_technology.properties AS p ON rt.property_id = p.property_id
JOIN hospitality_technology.services AS s ON rt.property_id = s.property_id
WHERE s.category = 'Spa'
  AND rt.base_rate > 200
ORDER BY rt.base_rate 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 hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults int, num_children int, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )


[User] For each doctor, count how many diagnoses they have recorded in total. Display doctor ID and the total count.

[Assistant] SELECT doctor_id, COUNT(*) AS total_diagnoses FROM healthcare.diagnoses GROUP BY doctor_id;

[User] Modify the query to also show the number of unique patients they have diagnosed, and filter the results to only include doctors who have diagnosed more than 10 distinct patients.

[Assistant] SELECT doctor_id, COUNT(*) AS total_diagnoses, COUNT(DISTINCT patient_id) AS unique_patients FROM healthcare.diagnoses GROUP BY doctor_id HAVING COUNT(DISTINCT patient_id) > 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)


[User] Find all users whose usernames contain numbers and have email addresses from either Gmail or Yahoo.

[Assistant] SELECT user_id, username, email FROM blockchain.users WHERE username ~ '[0-9]' AND (email LIKE '%@gmail.com' OR email LIKE '%@yahoo.com');

[User] Now, order these results by username length in descending order.

[Assistant] SELECT user_id, username, email FROM blockchain.users WHERE username ~ '[0-9]' AND (email LIKE '%@gmail.com' OR email LIKE '%@yahoo.com') ORDER BY LENGTH(username) DESC;

[User] Can you modify this to only show the top 5 longest usernames?

[Assistant] SELECT user_id, username, email FROM blockchain.users WHERE username ~ '[0-9]' AND (email LIKE '%@gmail.com' OR email LIKE '%@yahoo.com') ORDER BY LENGTH(username) DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.nodes ( node_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE blockchain.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    PRIMARY KEY (user_id)
)