[User] What is the average, minimum, and maximum interest_rate for each loan_type among active loans?

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

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

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

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

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

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


[User] Show me all room types with a base rate over $200 and max occupancy of at least 4, along with their property IDs and amenities.

[Assistant] SELECT room_type_id, property_id, type_name, base_rate, max_occupancy, amenities FROM hospitality_technology.room_types WHERE base_rate > 200 AND max_occupancy >= 4;

[User] Now, join this with the guests table to show only room types from properties where the guest's country code is 'USA'.

[Assistant] SELECT rt.room_type_id, rt.property_id, rt.type_name, rt.base_rate, rt.max_occupancy, rt.amenities FROM hospitality_technology.room_types rt JOIN hospitality_technology.guests g ON rt.property_id = g.property_id WHERE rt.base_rate > 200 AND rt.max_occupancy >= 4 AND g.country_code = 'USA';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id 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.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )


[User] How many hidden achievements are there?

[Assistant] SELECT COUNT(*) FROM gaming_technology.achievements WHERE hidden = true;

[User] Also, what is the average point value of all achievements that are not hidden?

[Assistant] SELECT AVG(points) FROM gaming_technology.achievements WHERE hidden = false;

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.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean )


[User] How many available services are there per department for each property? Include property_id, department, and the service count.

[Assistant]
SELECT
  property_id,
  department,
  COUNT(*) AS available_services_count
FROM hospitality_technology.services
WHERE is_available = TRUE
GROUP BY property_id, department;

[User] Also include the average price of these available services per department.

[Assistant]
SELECT
  property_id,
  department,
  COUNT(*) AS available_services_count,
  AVG(price) AS avg_service_price
FROM hospitality_technology.services
WHERE is_available = TRUE
GROUP BY property_id, department;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id.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.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.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] Find all contracts where the deployer address is the same as the contract address, indicating self-deployed contracts.

[Assistant] SELECT address, deployer_address FROM web3.contracts WHERE address = deployer_address;

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


[User] List all properties in the USA that have a phone number but no email address listed.

[Assistant] SELECT property_name, city, state_province FROM hospitality_technology.properties WHERE country_code = 'US' AND phone_number IS NOT NULL AND email_address IS NULL;

[User] The query should also include properties with empty email addresses, not just NULL.

[Assistant] SELECT property_name, city, state_province FROM hospitality_technology.properties WHERE country_code = 'US' AND phone_number IS NOT NULL AND (email_address IS NULL OR email_address = '');

[User] Now, add the property type and order the results by city name.

[Assistant] SELECT property_name, city, state_province, property_type FROM hospitality_technology.properties WHERE country_code = 'US' AND phone_number IS NOT NULL AND (email_address IS NULL OR email_address = '') ORDER BY city;

[User] Actually, I only need properties in California and New York.

[Assistant] SELECT property_name, city, state_province, property_type FROM hospitality_technology.properties WHERE country_code = 'US' AND phone_number IS NOT NULL AND (email_address IS NULL OR email_address = '') AND state_province IN ('California', 'New York') ORDER BY city;

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 )


[User] How many employees have a manager assigned to them?

[Assistant]
SELECT COUNT(*) AS employee_count
FROM government_services.employees
WHERE manager_employee_id IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )


[User] Show the ticker_symbol, security_name, and the number of loans that have that ticker_symbol as their collateral_description.

[Assistant]
SELECT s.ticker_symbol, s.security_name, COUNT(l.loan_id) AS collateral_loan_count
FROM financial_services.securities s
LEFT JOIN financial_services.loans l ON s.ticker_symbol = l.collateral_description
GROUP BY s.ticker_symbol, s.security_name;

[User] Only include securities that are used as collateral for at least 2 loans.

[Assistant]
SELECT s.ticker_symbol, s.security_name, COUNT(l.loan_id) AS collateral_loan_count
FROM financial_services.securities s
LEFT JOIN financial_services.loans l ON s.ticker_symbol = l.collateral_description
GROUP BY s.ticker_symbol, s.security_name
HAVING COUNT(l.loan_id) >= 2;

[User] Include the sector and order the result by collateral_loan_count descending.

[Assistant]
SELECT s.ticker_symbol, s.security_name, s.sector, COUNT(l.loan_id) AS collateral_loan_count
FROM financial_services.securities s
LEFT JOIN financial_services.loans l ON s.ticker_symbol = l.collateral_description
GROUP BY s.ticker_symbol, s.security_name, s.sector
HAVING COUNT(l.loan_id) >= 2
ORDER BY collateral_loan_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )


[User] I want to see all time entries where the description contains the word 'draft' and that have not been billed yet.

[Assistant]
SELECT *
FROM legal_services.time_entries
WHERE description ILIKE '%draft%'
  AND is_billed = false;

[User] Only include entries that were logged in June 2024.

[Assistant]
SELECT *
FROM legal_services.time_entries
WHERE description ILIKE '%draft%'
  AND is_billed = false
  AND date_worked BETWEEN '2024-06-01' AND '2024-06-30';

[User] Now only show entries that are billable and where hours_spent is greater than 2.

[Assistant]
SELECT *
FROM legal_services.time_entries
WHERE description ILIKE '%draft%'
  AND is_billed = false
  AND is_billable = true
  AND date_worked BETWEEN '2024-06-01' AND '2024-06-30'
  AND hours_spent > 2;

[User] Please only include the entry_id, lawyer_id, date_worked, and hours_spent in the output.

[Assistant]
SELECT entry_id, lawyer_id, date_worked, hours_spent
FROM legal_services.time_entries
WHERE description ILIKE '%draft%'
  AND is_billed = false
  AND is_billable = true
  AND date_worked BETWEEN '2024-06-01' AND '2024-06-30'
  AND hours_spent > 2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)


[User] Can you provide the total number of accounts and the average balance for each account_type?

[Assistant]
SELECT account_type, COUNT(*) AS total_accounts, AVG(balance) AS avg_balance
FROM financial_services.accounts
GROUP BY account_type;

[User] Exclude account types with fewer than 5 accounts.

[Assistant]
SELECT account_type, COUNT(*) AS total_accounts, AVG(balance) AS avg_balance
FROM financial_services.accounts
GROUP BY account_type
HAVING COUNT(*) >= 5;

[User] Sort the result by avg_balance in descending order.

[Assistant]
SELECT account_type, COUNT(*) AS total_accounts, AVG(balance) AS avg_balance
FROM financial_services.accounts
GROUP BY account_type
HAVING COUNT(*) >= 5
ORDER BY avg_balance DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )


[User] Show the document ID, claim ID, and file name for all documents with a MIME type starting with 'image/'.

[Assistant] SELECT document_id, claim_id, file_name FROM insurance.claim_documents WHERE mime_type LIKE 'image/%';

[User] Can you also include the uploaded_by user and only show documents uploaded after January 1, 2023?

[Assistant] SELECT document_id, claim_id, file_name, uploaded_by FROM insurance.claim_documents WHERE mime_type LIKE 'image/%' AND uploaded_at >= '2023-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )


[User] Which users have participated in conversations that are not group chats? Please show their usernames and the conversation IDs.

[Assistant]
SELECT u.username, cp.conversation_id
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = FALSE;

[User] Actually, can you show the time when they joined each conversation as well?

[Assistant]
SELECT u.username, cp.conversation_id, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = FALSE;

[User] Only include users who joined after March 1, 2024.

[Assistant]
SELECT u.username, cp.conversation_id, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = FALSE
  AND cp.joined_at > '2024-03-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.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments (
    comment_id 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 text, user_id text, post_id text, comment_id text, created_at timestamp )
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 text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.conversation_participants (
    participant_id 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
)


[User] Which drivers have missing contact numbers or email addresses? Show their IDs and names.

[Assistant] SELECT driver_id, first_name, last_name FROM transportation.drivers WHERE contact_number IS NULL OR email IS NULL;

[User] Instead, show only those drivers who were hired after July 1, 2022.

[Assistant] SELECT driver_id, first_name, last_name FROM transportation.drivers WHERE (contact_number IS NULL OR email IS NULL) AND hire_date > '2022-07-01';

[User] Now, include their license expiry dates, and order by hire date ascending.

[Assistant] SELECT driver_id, first_name, last_name, license_expiry_date FROM transportation.drivers WHERE (contact_number IS NULL OR email IS NULL) AND hire_date > '2022-07-01' ORDER BY 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 transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )


[User] I want to list each public post along with its content, the author's username, and the total number of comments it has received. Order the results by comment count descending.

[Assistant]
SELECT p.post_id,
       u.username,
       p.content,
       COUNT(c.comment_id) AS comment_count
FROM social_media.posts AS p
JOIN social_media.users AS u
  ON p.user_id = u.user_id
LEFT JOIN social_media.comments AS c
  ON p.post_id = c.post_id
WHERE p.visibility = 'public'
GROUP BY p.post_id, u.username, p.content
ORDER BY comment_count DESC;

[User] Actually, can you filter this to only include posts created after '2024-01-01' that have at least 5 comments?

[Assistant]
SELECT p.post_id,
       u.username,
       p.content,
       COUNT(c.comment_id) AS comment_count
FROM social_media.posts AS p
JOIN social_media.users AS u
  ON p.user_id = u.user_id
LEFT JOIN social_media.comments AS c
  ON p.post_id = c.post_id
WHERE p.visibility = 'public'
  AND p.created_at > '2024-01-01'
GROUP BY p.post_id, u.username, p.content
HAVING COUNT(c.comment_id) >= 5
ORDER BY comment_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.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, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text PRIMARY KEY, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )


[User] For each token, show the token_id and the total number of unique addresses that have ever received it.

[Assistant]
SELECT token_id, COUNT(DISTINCT to_address) AS unique_recipients
FROM web3.token_transfers
GROUP BY token_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.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)


[User] List tokens on the 'Arbitrum' chain with a 24-hour trading volume greater than 1,000,000 USD. Show symbol, volume, and price.

[Assistant] SELECT token_symbol, volume_24h, price FROM token_dexpool_info WHERE chain = 'Arbitrum' AND volume_24h > 1000000

[User] Can you also include the liquidity for these tokens?

[Assistant] SELECT token_symbol, volume_24h, price, liquidity FROM token_dexpool_info WHERE chain = 'Arbitrum' AND volume_24h > 1000000

[User] Now, filter these results to only include tokens where the liquidity is also greater than $500,000. Order by volume descending and show the top 10.

[Assistant] SELECT token_symbol, volume_24h, price, liquidity FROM token_dexpool_info WHERE chain = 'Arbitrum' AND volume_24h > 1000000 AND liquidity > 500000 ORDER BY volume_24h DESC LIMIT 10

[User] Add the 24-hour price change percentage and only include tokens where the price change is positive.

[Assistant] SELECT token_symbol, volume_24h, price, liquidity, price_change_percentage_24h FROM token_dexpool_info WHERE chain = 'Arbitrum' AND volume_24h > 1000000 AND liquidity > 500000 AND price_change_percentage_24h > 0 ORDER BY volume_24h DESC LIMIT 10

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_6h double precision, price_change_percentage_24h double precision, makers_24h double precision, volume_24h double precision, liquidity double precision, market_cap double precision, trend_rank bigint )


[User] What is the total amount of all payments recorded?

[Assistant] SELECT SUM(amount) FROM government_services.payments;

[User] Now only include payments with status 'Completed'.

[Assistant] SELECT SUM(amount) FROM government_services.payments WHERE status = 'Completed';

[User] Also, only consider payments made in the year 2024.

[Assistant] SELECT SUM(amount) FROM government_services.payments WHERE status = 'Completed' AND EXTRACT(YEAR FROM payment_timestamp) = 2024;

[User] Group the results by payment method and show the total amount for each method for these completed 2024 payments.

[Assistant] SELECT payment_method, SUM(amount) FROM government_services.payments WHERE status = 'Completed' AND EXTRACT(YEAR FROM payment_timestamp) = 2024 GROUP BY payment_method;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )


[User] Which subscribers have more than one active insurance policy as of today? Show the subscriber_name and the count of such policies.

[Assistant] SELECT subscriber_name, COUNT(*) AS policy_count FROM healthcare.patient_insurance WHERE (expiration_date IS NULL OR expiration_date >= CURRENT_DATE) AND effective_date <= CURRENT_DATE GROUP BY subscriber_name HAVING COUNT(*) > 1;

[User] Can you also include only those where at least one of their policies is marked as primary?

[Assistant] SELECT subscriber_name, COUNT(*) AS policy_count FROM healthcare.patient_insurance WHERE (expiration_date IS NULL OR expiration_date >= CURRENT_DATE) AND effective_date <= CURRENT_DATE GROUP BY subscriber_name HAVING COUNT(*) > 1 AND SUM(CASE WHEN is_primary = true THEN 1 ELSE 0 END) >= 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 healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List the first name and last name of citizens along with their application reference number, status, and the agency name for services categorized as 'Healthcare'.

[Assistant]
SELECT c.first_name, c.last_name, a.reference_number, a.status, ag.agency_name
FROM government_services.citizens c
JOIN government_services.applications a ON c.citizen_id = a.citizen_id
JOIN government_services.services s ON a.service_id = s.service_id
JOIN government_services.agencies ag ON s.agency_id = ag.agency_id
WHERE s.category = 'Healthcare';

[User] Also include only those agencies with a jurisdiction_level of 'State'.

[Assistant]
SELECT c.first_name, c.last_name, a.reference_number, a.status, ag.agency_name
FROM government_services.citizens c
JOIN government_services.applications a ON c.citizen_id = a.citizen_id
JOIN government_services.services s ON a.service_id = s.service_id
JOIN government_services.agencies ag ON s.agency_id = ag.agency_id
WHERE s.category = 'Healthcare'
  AND ag.jurisdiction_level = 'State';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )


[User] Identify agents who have sold overlapping policies. Return agent_id, policy_number1, policy_number2, and their coverage dates.

[Assistant]
SELECT p1.agent_id,
       p1.policy_number AS policy_number1,
       p2.policy_number AS policy_number2,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)       AS overlap_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.agent_id = p2.agent_id
 AND p1.policy_id < p2.policy_id
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date;

[User] Actually, only consider policies that are currently Active for both entries.

[Assistant]
SELECT p1.agent_id,
       p1.policy_number AS policy_number1,
       p2.policy_number AS policy_number2,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)       AS overlap_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.agent_id = p2.agent_id
 AND p1.policy_id < p2.policy_id
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date
WHERE p1.status = 'Active'
  AND p2.status = 'Active';

[User] Also, exclude entries where agent_id is null.

[Assistant]
SELECT p1.agent_id,
       p1.policy_number AS policy_number1,
       p2.policy_number AS policy_number2,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)       AS overlap_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.agent_id = p2.agent_id
 AND p1.policy_id < p2.policy_id
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date
WHERE p1.status = 'Active'
  AND p2.status = 'Active'
  AND p1.agent_id IS NOT NULL;

[User] Finally, sort by agent_id ascending and limit to 5 results.

[Assistant]
SELECT p1.agent_id,
       p1.policy_number AS policy_number1,
       p2.policy_number AS policy_number2,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)       AS overlap_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.agent_id = p2.agent_id
 AND p1.policy_id < p2.policy_id
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date
WHERE p1.status = 'Active'
  AND p2.status = 'Active'
  AND p1.agent_id IS NOT NULL
ORDER BY p1.agent_id ASC
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 insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)


[User] Show me the total number of bookings and total fare collected per trip. Only include trips that have collected more than 500 in total fare.

[Assistant]
SELECT trip_id, COUNT(*) AS booking_count, SUM(fare) AS total_fare
FROM transportation.bookings
GROUP BY trip_id
HAVING SUM(fare) > 500;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.bookings (
    booking_id character varying(64) NOT NULL,  -- unique identifier for the booking
    passenger_id character varying(64) NOT NULL, -- identifier of the passenger making the booking
    trip_id character varying(64) NOT NULL, -- identifier of the trip being booked
    seat_number character varying(16), -- assigned seat number (if applicable)
    booking_time timestamp with time zone NOT NULL, -- time when the booking was made
    status character varying(32) NOT NULL, -- e.g., Confirmed, Cancelled, Pending Payment
    fare numeric(10, 2) NOT NULL, -- price paid for the booking
    payment_transaction_id character varying(128), -- reference to the payment transaction
    special_requests text, -- any special requests from the passenger
    PRIMARY KEY (booking_id)
)


[User] List all transaction IDs that contain at least one UTXO marked as spent.

[Assistant] SELECT DISTINCT transaction_id FROM utxos WHERE spent = TRUE;

[User] Now, for those transaction IDs, also include the total count of spent UTXOs they contain.

[Assistant] SELECT transaction_id, COUNT(*) FROM utxos WHERE spent = TRUE GROUP BY transaction_id;

[User] Actually, I only want transaction IDs that have exactly one spent UTXO. Show the ID and the count (which should be 1).

[Assistant] SELECT transaction_id, COUNT(*) FROM utxos WHERE spent = TRUE GROUP BY transaction_id HAVING COUNT(*) = 1;

[User] Instead of listing them, just tell me how many transaction IDs meet that criteria (have exactly one spent UTXO).

[Assistant] SELECT COUNT(*) FROM (SELECT transaction_id FROM utxos WHERE spent = TRUE GROUP BY transaction_id HAVING COUNT(*) = 1) AS subquery;

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


[User] Find, for each token, how many unique recipient addresses it has. Show token_symbol, contract_address, and recipient_count, ordered by recipient_count descending.

[Assistant]
SELECT t.token_symbol,
       t.contract_address,
       COUNT(DISTINCT tt.to_address) AS recipient_count
FROM web3.tokens t
JOIN web3.token_transfers tt
  ON t.token_id = tt.token_id
GROUP BY t.token_symbol, t.contract_address
ORDER BY recipient_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 web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)


[User] Show the plan name and insurance provider for all insurance plans along with the total number of unique patients enrolled in each plan.

[Assistant]
SELECT ip.plan_name, ip.insurance_provider, COUNT(DISTINCT pi.patient_id) AS enrolled_patient_count
FROM healthcare.insurance_plans ip
JOIN healthcare.patients_insurance pi ON ip.plan_id = pi.plan_id
GROUP BY ip.plan_name, ip.insurance_provider;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )


[User] List all reviews for properties with a star rating of at least 4.5. Include the property_name, review_id, rating_overall, and review_date.

[Assistant]
SELECT p.property_name, r.review_id, r.rating_overall, r.review_date
FROM hospitality_technology.reviews r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE p.star_rating >= 4.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 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.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.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] Can you show a list of all distinct medication IDs along with the count of prescriptions for each medication, including only medications that have been prescribed more than 50 times? Also, please display the total quantity dispensed for each medication.

[Assistant]
SELECT medication_id, COUNT(*) AS prescription_count, SUM(quantity_dispensed) AS total_quantity_dispensed
FROM healthcare.prescriptions
GROUP BY medication_id
HAVING COUNT(*) > 50;

[User] Actually, I want to see the average quantity dispensed per prescription for each medication as well. Can you add that to the results?

[Assistant]
SELECT medication_id, COUNT(*) AS prescription_count, SUM(quantity_dispensed) AS total_quantity_dispensed, AVG(quantity_dispensed) AS avg_quantity_per_prescription
FROM healthcare.prescriptions
GROUP BY medication_id
HAVING COUNT(*) > 50;

[User] Also, please sort the results by the average quantity per prescription in descending order.

[Assistant]
SELECT medication_id, COUNT(*) AS prescription_count, SUM(quantity_dispensed) AS total_quantity_dispensed, AVG(quantity_dispensed) AS avg_quantity_per_prescription
FROM healthcare.prescriptions
GROUP BY medication_id
HAVING COUNT(*) > 50
ORDER BY avg_quantity_per_prescription DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.prescriptions (
    prescription_id character varying(64) NOT NULL, -- unique identifier for the prescription
    record_id character varying(64) NOT NULL, -- FK linking to the medical record where it was prescribed
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to prescribing doctor
    medication_id character varying(64) NOT NULL, -- FK to medications table
    dosage character varying(100) NOT NULL, -- e.g., '100mg', '1 tablet'
    frequency character varying(100) NOT NULL, -- e.g., 'Once daily', 'Twice a day with meals'
    route character varying(50), -- e.g., 'Oral', 'Topical', 'Intravenous'
    start_date date NOT NULL, -- date prescription begins
    end_date date, -- date prescription ends (if applicable)
    quantity_dispensed numeric(10,2), -- amount dispensed (e.g., number of tablets)
    refills_allowed integer NOT NULL DEFAULT 0, -- number of allowed refills
    prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (prescription_id)
)


[User] Find all pairs of events that occurred in the same transaction but at different log indices, showing both event_ids, their event_names, the transaction_id, and each log_index.

[Assistant]
SELECT a.event_id AS event_id1,
       a.event_name AS event_name1,
       b.event_id AS event_id2,
       b.event_name AS event_name2,
       a.transaction_id,
       a.log_index AS log_index1,
       b.log_index AS log_index2
FROM web3.events a
JOIN web3.events b
  ON a.transaction_id = b.transaction_id
 AND a.log_index < b.log_index;

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, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )


[User] Calculate the total value of unspent UTXOs for each user whose KYC status has been 'approved'.

[Assistant] SELECT kyc.user_id, SUM(u.amount) FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status = 'approved' AND u.spent = false GROUP BY kyc.user_id;

[User] Refine that to only show users where this total value exceeds 1000.

[Assistant] SELECT kyc.user_id, SUM(u.amount) FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status = 'approved' AND u.spent = false GROUP BY kyc.user_id HAVING SUM(u.amount) > 1000;

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.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )


[User] For each trip, provide the trip ID, the name of the vehicle's make and model, and the total quantity of fuel used during that trip.

[Assistant]
SELECT t.trip_id, v.make, v.model, SUM(f.quantity) AS total_fuel_used
FROM transportation.trips t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
GROUP BY t.trip_id, v.make, v.model;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )


[User] Show me all active managers along with their first and last names, and the count of staff members they supervise, ordered by the supervised staff count in descending order.

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

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

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

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


[User] List policy IDs, policy numbers, start dates, and premium amounts for policies issued in the last 90 days with a premium amount greater than 5000.

[Assistant] SELECT policy_id, policy_number, start_date, premium_amount FROM insurance.policies WHERE issued_at >= CURRENT_DATE - INTERVAL '90 days' AND premium_amount > 5000;

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 PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )


[User] For each relationship type among policy beneficiaries, count how many beneficiaries exist of that type. Provide relationship and count, ordered by count descending.

[Assistant]
SELECT relationship,
       COUNT(*) AS beneficiary_count
FROM insurance.policy_beneficiaries
GROUP BY relationship
ORDER BY beneficiary_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.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] For each user, show their username and the timestamp of their most recent notification. Include users who have never received notifications.

[Assistant] SELECT T1.username, max(T2.sent_at) FROM users AS T1 LEFT JOIN trading_platform.notifications AS T2 ON T1.user_id = T2.user_id GROUP BY T1.username

[User] Could you also include the total number of notifications for each user?

[Assistant] SELECT T1.username, count(T2.notification_id), max(T2.sent_at) FROM users AS T1 LEFT JOIN trading_platform.notifications AS T2 ON T1.user_id = T2.user_id GROUP BY T1.username

[User] Actually, only show users whose latest notification is unread.

[Assistant] WITH LatestNotification AS ( SELECT user_id, sent_at, read_at, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY sent_at DESC) AS rn FROM trading_platform.notifications ) SELECT T1.username, T2.sent_at FROM users AS T1 JOIN LatestNotification AS T2 ON T1.user_id = T2.user_id WHERE T2.rn = 1 AND T2.read_at IS NULL

[User] Also, include the count of unread notifications for these users.

[Assistant] WITH LatestNotification AS ( SELECT user_id, sent_at, read_at, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY sent_at DESC) AS rn FROM trading_platform.notifications ) SELECT T1.username, count(CASE WHEN T3.read_at IS NULL THEN T3.notification_id ELSE NULL END), T2.sent_at FROM users AS T1 JOIN LatestNotification AS T2 ON T1.user_id = T2.user_id AND T2.rn = 1 AND T2.read_at IS NULL JOIN trading_platform.notifications AS T3 ON T1.user_id = T3.user_id GROUP BY T1.username, T2.sent_at

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


[User] List all SUI coins with status 'exists', including their coin_type, balance, and owner address.

[Assistant]
SELECT object_id, coin_type, balance, owner
FROM sui_coins
WHERE status = 'exists';

[User] Add their symbol and name by joining with sui_coins_metadata.

[Assistant]
SELECT sc.object_id, sc.coin_type, sc.balance, sc.owner, scm.symbol, scm.name
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'exists';

[User] Only include coins where balance is greater than 1000000 and the metadata status is also 'exists'.

[Assistant]
SELECT sc.object_id, sc.coin_type, sc.balance, sc.owner, scm.symbol, scm.name
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'exists' AND scm.status = 'exists' AND CAST(sc.balance AS bigint) > 1000000;

[User] Add the coin's description from sui_coins_metadata and order the results by balance descending.

[Assistant]
SELECT sc.object_id, sc.coin_type, sc.balance, sc.owner, scm.symbol, scm.name, scm.description
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'exists' AND scm.status = 'exists' AND CAST(sc.balance AS bigint) > 1000000
ORDER BY CAST(sc.balance AS bigint) 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_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances_historical (
    block_number bigint NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract
    amount varchar NOT NULL, -- Wallet's on-chain balance at the corresponding block height
    pk integer NOT NULL  -- Partition key for the table(floor(block_number / 7200))
)
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE sui_coins ( object_id varchar, status varchar, coin_type varchar, balance varchar, owner varchar )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE token_balances (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar NOT NULL, -- Token tick
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_info_avalanche (
    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(20) 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)
    minted decimal(38,0) NOT NULL, -- Sum of minted amount
    holders decimal(38,0) NOT NULL, -- Count of holders
    txs decimal(38,0) NOT NULL, -- Count of transactions
    updated_timestamp timestamp(3) NOT NULL, -- Timestamp of update
    completed_timestamp timestamp(3) NOT NULL, -- Timestamp of minted completed
    id varchar(255) NOT NULL  -- id fields for the functionType  in contract asc20
)


[User] List the user IDs, theme, and updated_at for users who have disabled email notifications, enabled push notifications, and have a private profile.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = TRUE AND private_profile = TRUE;

[User] Now, only include those whose theme is set to 'light'.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = TRUE AND private_profile = TRUE AND theme = 'light';

[User] Order these results by the updated_at timestamp in descending order.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = TRUE AND private_profile = TRUE AND theme = 'light' ORDER BY updated_at DESC;

[User] Limit the results to the top 5.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = TRUE AND private_profile = TRUE AND theme = 'light' ORDER BY updated_at 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 social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )


[User] Show me the top 5 ERC20 tokens with the highest total supply, along with their names and contract addresses, but only include tokens with decimals equal to 18.

[Assistant] SELECT name, contract_address, total_supply FROM token_metas WHERE is_erc20 = 1 AND decimals = 18 ORDER BY CAST(total_supply AS decimal) DESC LIMIT 5;

[User] Can you join this with the token_prices_latest table to include the current price of each token?

[Assistant] SELECT tm.name, tm.contract_address, tm.total_supply, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tm.decimals = 18 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] I think there's a typo in your query - it should be 'total_supply' not 'total_supply'. Also, can you add the symbol to the results?

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address, tm.total_supply, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tm.decimals = 18 ORDER BY CAST(tm.total_supply AS decimal) 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 token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] For each patient, show their full name and the count of insurance plans they are enrolled in, as well as their earliest policy effective date.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(pi.plan_id) AS plan_count, MIN(pi.effective_date) AS earliest_effective_date
FROM healthcare.patients p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
GROUP BY p.patient_id, p.first_name, p.last_name;

[User] Only include patients with more than one insurance plan.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(pi.plan_id) AS plan_count, MIN(pi.effective_date) AS earliest_effective_date
FROM healthcare.patients p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
GROUP BY p.patient_id, p.first_name, p.last_name
HAVING COUNT(pi.plan_id) > 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 healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    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 (patient_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.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List all users who have created wallets in the last 30 days, showing their usernames and wallet addresses.

[Assistant] SELECT u.username, w.address FROM web3.users u JOIN web3.wallets w ON u.user_id = w.user_id WHERE w.created_at >= NOW() - INTERVAL '30 days';

[User] Actually, I also need to see the email addresses of these users.

[Assistant] SELECT u.username, u.email, w.address FROM web3.users u JOIN web3.wallets w ON u.user_id = w.user_id WHERE w.created_at >= NOW() - INTERVAL '30 days';

[User] Now filter to only show users whose email domain is 'gmail.com'.

[Assistant] SELECT u.username, u.email, w.address FROM web3.users u JOIN web3.wallets w ON u.user_id = w.user_id WHERE w.created_at >= NOW() - INTERVAL '30 days' AND u.email LIKE '%@gmail.com';

[User] Finally, sort the results by the wallet creation date in descending order.

[Assistant] SELECT u.username, u.email, w.address, w.created_at FROM web3.users u JOIN web3.wallets w ON u.user_id = w.user_id WHERE w.created_at >= NOW() - INTERVAL '30 days' AND u.email LIKE '%@gmail.com' ORDER BY w.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 web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id text PRIMARY KEY, from_address text, to_address text, value numeric, gas_used int, gas_price numeric, block_number int, timestamp timestamp, input_data text, status text, nonce int )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id.text, token_id.text, from_address.text, to_address.text, value.numeric, transaction_id.text, log_index.integer )
CREATE TABLE web3.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE web3.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )


[User] Show me all properties in California with a star rating above 4.0, along with the count of available rooms at each property.

[Assistant] SELECT p.property_id, p.property_name, p.city, p.star_rating, COUNT(r.room_id) AS available_rooms_count FROM hospitality_technology.properties p LEFT JOIN hospitality_technology.rooms r ON p.property_id = r.property_id WHERE p.state_province = 'California' AND p.star_rating > 4.0 AND r.status = 'available' GROUP BY p.property_id, p.property_name, p.city, p.star_rating ORDER BY available_rooms_count DESC;

[User] Now, include only properties with more than 10 available rooms and show the average base rate of their room types.

[Assistant] SELECT p.property_id, p.property_name, p.city, p.star_rating, COUNT(r.room_id) AS available_rooms_count, AVG(rt.base_rate) AS avg_base_rate FROM hospitality_technology.properties p LEFT JOIN hospitality_technology.rooms r ON p.property_id = r.property_id LEFT JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE p.state_province = 'California' AND p.star_rating > 4.0 AND r.status = 'available' GROUP BY p.property_id, p.property_name, p.city, p.star_rating HAVING COUNT(r.room_id) > 10 ORDER BY available_rooms_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id.text, property_id.text, guest_id.text, room_id.text, room_type_id.text, check_in_date.date, check_out_date.date, actual_check_in_ts.timestamp, actual_check_out_ts.timestamp, num_adults.integer, num_children.integer, status.text, booking_source.text, rate_plan_id.text, total_amount.numeric, amount_paid.numeric, special_requests.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id 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] Which bed types are offered in each property and how many different room types are associated with each bed type?

[Assistant] SELECT property_id, bed_type, COUNT(DISTINCT room_type_id) AS room_type_count FROM hospitality_technology.room_types GROUP BY property_id, bed_type;

[User] Now, show only bed types that are available for at least 3 different room types within the same property.

[Assistant] SELECT property_id, bed_type, COUNT(DISTINCT room_type_id) AS room_type_count FROM hospitality_technology.room_types GROUP BY property_id, bed_type HAVING COUNT(DISTINCT room_type_id) >= 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.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 )


[User] Show me all guests from 'CA' along with their full name and email address.

[Assistant] SELECT guest_id, CONCAT(first_name, ' ', last_name) AS full_name, email FROM hospitality_technology.guests WHERE country_code = 'CA';

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


[User] List pairs of distinct servers that share the same ip_address. Show server1_name, server2_name, and the shared ip_address.

[Assistant]
SELECT s1.server_name AS server1_name,
       s2.server_name AS server2_name,
       s1.ip_address
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.ip_address = s2.ip_address
 AND s1.server_id < s2.server_id;

[User] Exclude pairs where both servers have status = 'offline'.

[Assistant]
SELECT s1.server_name AS server1_name,
       s2.server_name AS server2_name,
       s1.ip_address
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.ip_address = s2.ip_address
 AND s1.server_id < s2.server_id
WHERE NOT (s1.status = 'offline' AND s2.status = 'offline');

[User] Only include pairs where at least one server is 'online'.

[Assistant]
SELECT s1.server_name AS server1_name,
       s2.server_name AS server2_name,
       s1.ip_address
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.ip_address = s2.ip_address
 AND s1.server_id < s2.server_id
WHERE (s1.status = 'online' OR s2.status = 'online');

[User] Finally, only show pairs where the two servers host different games.

[Assistant]
SELECT s1.server_name AS server1_name,
       s2.server_name AS server2_name,
       s1.ip_address
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.ip_address = s2.ip_address
 AND s1.server_id < s2.server_id
WHERE (s1.status = 'online' OR s2.status = 'online')
  AND s1.game_id <> s2.game_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )