[User] Which customers have policies that expired in the last month? Please show the customer ID, policy number, and expiration date.

[Assistant]
SELECT c.customer_id, p.policy_number, p.end_date
FROM insurance.customers c
JOIN insurance.policies p ON c.customer_id = p.customer_id
WHERE p.end_date >= (CURRENT_DATE - INTERVAL '1 month') AND p.end_date < CURRENT_DATE;

[User] Add the customer's email to the results.

[Assistant]
SELECT c.customer_id, c.email, p.policy_number, p.end_date
FROM insurance.customers c
JOIN insurance.policies p ON c.customer_id = p.customer_id
WHERE p.end_date >= (CURRENT_DATE - INTERVAL '1 month') AND p.end_date < CURRENT_DATE;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )


[User] Can you fetch all claims reported in the past 30 days, including claim_id, incident_date, reported_date, and estimated_loss?

[Assistant]
SELECT claim_id, incident_date, reported_date, estimated_loss
FROM insurance.claims
WHERE reported_date >= CURRENT_DATE - INTERVAL '30 days';

[User] Actually, I also need the beneficiaries of those policies, including their first and last names.

[Assistant]
SELECT c.claim_id, c.incident_date, c.reported_date, c.estimated_loss, b.first_name, b.last_name
FROM insurance.claims c
JOIN insurance.policy_beneficiaries b ON c.policy_id = b.policy_id
WHERE c.reported_date >= CURRENT_DATE - INTERVAL '30 days';

[User] Filter the results to only include claims that have been settled.

[Assistant]
SELECT c.claim_id, c.incident_date, c.reported_date, c.estimated_loss, b.first_name, b.last_name
FROM insurance.claims c
JOIN insurance.policy_beneficiaries b ON c.policy_id = b.policy_id
WHERE c.reported_date >= CURRENT_DATE - INTERVAL '30 days'
  AND c.status = 'Settled';

[User] Also, sort the output by settlement_amount descending and include the settlement_date.

[Assistant]
SELECT c.claim_id, c.incident_date, c.reported_date, c.estimated_loss, b.first_name, b.last_name, c.settlement_amount, c.settlement_date
FROM insurance.claims c
JOIN insurance.policy_beneficiaries b ON c.policy_id = b.policy_id
WHERE c.reported_date >= CURRENT_DATE - INTERVAL '30 days'
  AND c.status = 'Settled'
ORDER BY c.settlement_amount DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )


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

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

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


[User] Show me all customers who have missing contact information (either phone number or email is null), along with their state and city.

[Assistant] SELECT first_name, last_name, state, city FROM insurance.customers WHERE phone_number IS NULL OR email IS NULL;

[User] Now filter these to only show customers from Florida or New York who were created in the last year.

[Assistant] SELECT first_name, last_name, state, city FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '1 year';

[User] I also want to see when these customers were last updated (updated_at field).

[Assistant] SELECT first_name, last_name, state, city, updated_at FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '1 year';

[User] Finally, order the results by state first, then by the most recently updated customers first.

[Assistant] SELECT first_name, last_name, state, city, updated_at FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '1 year' ORDER BY state, updated_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 insurance.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)


[User] List all users with private profiles who have disabled push notifications, including their user_id and email_notifications_enabled status.

[Assistant]
SELECT user_id,
       email_notifications_enabled
FROM social_media.user_settings
WHERE private_profile = true
  AND push_notifications_enabled = 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 social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )


[User] List all trades for asset 'BTC' where the trade quantity is greater than 5.

[Assistant] SELECT trade_id, order_id, buyer_id, seller_id, quantity, price, traded_at FROM trading_platform.trades WHERE asset_id = 'BTC' AND quantity > 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 trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )


[User] Show me all insurance plans that have more than 5 patients enrolled as their primary insurance, along with the provider name and count of patients.

[Assistant] SELECT ip.plan_id, ip.plan_name, ip.insurance_provider, COUNT(pi.patient_id) AS patient_count FROM healthcare.insurance_plans ip JOIN healthcare.patient_insurance pi ON ip.plan_id = pi.plan_id WHERE pi.is_primary = true GROUP BY ip.plan_id, ip.plan_name, ip.insurance_provider HAVING COUNT(pi.patient_id) > 5 ORDER BY patient_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_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 (doctor_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.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, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )
CREATE TABLE healthcare.prescriptions ( prescription_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, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )


[User] Show me the list of posts with their content and the usernames of users who commented on them, for posts that are public.

[Assistant]
SELECT p.post_id, p.content, u.username AS commenter_username
FROM social_media.posts p
JOIN social_media.comments c ON p.post_id = c.post_id
JOIN social_media.users u ON c.user_id = u.user_id
WHERE p.visibility = 'public';

[User] I only want comments created after June 1, 2024 and also show the comment creation time.

[Assistant]
SELECT p.post_id, p.content, u.username AS commenter_username, c.created_at AS comment_created_at
FROM social_media.posts p
JOIN social_media.comments c ON p.post_id = c.post_id
JOIN social_media.users u ON c.user_id = u.user_id
WHERE p.visibility = 'public' AND c.created_at > '2024-06-01';

[User] Include only posts that have at least 3 such comments.

[Assistant]
SELECT result.post_id, result.content, result.commenter_username, result.comment_created_at
FROM (
    SELECT p.post_id, p.content, u.username AS commenter_username, c.created_at AS comment_created_at,
           COUNT(*) OVER(PARTITION BY p.post_id) AS comment_count
    FROM social_media.posts p
    JOIN social_media.comments c ON p.post_id = c.post_id
    JOIN social_media.users u ON c.user_id = u.user_id
    WHERE p.visibility = 'public' AND c.created_at > '2024-06-01'
) AS result
WHERE result.comment_count >= 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 social_media.users ( user_id.text, username.text, email.text, password_hash.text, full_name.text, profile_picture_url.text, bio.text, location.text, created_at.timestamp, updated_at.timestamp, is_verified.boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )


[User] Show me all customers (customer_id, first_name, last_name) who have made trades in the last 30 days, along with the total trade amount for each customer, sorted by total trade amount in descending order.

[Assistant] SELECT c.customer_id, c.first_name, c.last_name, SUM(t.total_amount) AS total_trade_amount FROM financial_services.customers c JOIN financial_services.accounts a ON c.customer_id = a.customer_id JOIN financial_services.trades t ON a.account_id = t.account_id WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days' GROUP BY c.customer_id, c.first_name, c.last_name ORDER BY total_trade_amount DESC;

[User] Now modify the query to only include trades executed on the 'NYSE' venue and include the trade count for each customer.

[Assistant] SELECT c.customer_id, c.first_name, c.last_name, SUM(t.total_amount) AS total_trade_amount, COUNT(t.trade_id) AS trade_count FROM financial_services.customers c JOIN financial_services.accounts a ON c.customer_id = a.customer_id JOIN financial_services.trades t ON a.account_id = t.account_id WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days' AND t.execution_venue = 'NYSE' GROUP BY c.customer_id, c.first_name, c.last_name ORDER BY total_trade_amount DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- hashed social security number (or national ID)
    address text NOT NULL, -- customer's primary address
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL,
    email character varying(128) UNIQUE, -- customer's email address
    phone_number character varying(32),
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of customer record creation
    status character varying(32) NOT NULL, -- e.g., Active, Inactive, Pending Verification
    risk_profile character varying(50), -- e.g., Low, Medium, High
    PRIMARY KEY (customer_id)
)
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.trades (
    trade_id character varying(64) NOT NULL, -- unique identifier for the trade
    account_id character varying(64) NOT NULL, -- investment account executing the trade
    security_id character varying(64) NOT NULL, -- security being traded
    order_id character varying(64), -- related order ID if applicable
    trade_type character varying(10) NOT NULL, -- 'Buy' or 'Sell'
    quantity numeric(19, 8) NOT NULL, -- number of units traded
    price_per_unit numeric(19, 8) NOT NULL, -- price per unit of the security
    total_amount numeric(19, 4) NOT NULL, -- total value of the trade (quantity * price)
    commission numeric(10, 4), -- commission fee charged for the trade
    trade_timestamp timestamp NOT NULL, -- exact time the trade was executed
    settlement_date date, -- date the trade settles
    status character varying(32) NOT NULL, -- e.g., Executed, Settled, Cancelled
    execution_venue character varying(100), -- where the trade was executed
    PRIMARY KEY (trade_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)
CREATE TABLE financial_services.market_data (
    data_point_id bigserial NOT NULL, -- auto-incrementing primary key
    security_id character varying(64) NOT NULL, -- identifier for the security
    data_timestamp timestamp NOT NULL, -- timestamp for the data point (e.g., end of day, intraday)
    open_price numeric(19, 8), -- opening price for the period
    high_price numeric(19, 8), -- highest price during the period
    low_price numeric(19, 8), -- lowest price during the period
    close_price numeric(19, 8) NOT NULL, -- closing price for the period
    adjusted_close_price numeric(19, 8), -- closing price adjusted for dividends and splits
    volume bigint, -- trading volume during the period
    source character varying(50), -- source of the market data (e.g., Bloomberg, Refinitiv)
    PRIMARY KEY (data_point_id),
    UNIQUE (security_id, data_timestamp), -- Ensure unique data point per security per time
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)


[User] List the names of services for which documents are set to expire in the next 90 days.

[Assistant] SELECT DISTINCT T1.service_name FROM government_services.services AS T1 JOIN applications AS T2 ON T1.service_id = T2.service_id JOIN government_services.documents AS T3 ON T2.application_id = T3.application_id WHERE T3.expiry_date IS NOT NULL AND T3.expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '90 days'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )


[User] Show each service's name along with the total number of appointments scheduled and the number of unique locations these appointments are scheduled at.

[Assistant]
SELECT s.service_name, COUNT(a.application_id) AS appointment_count, COUNT(DISTINCT ap.location_id) AS unique_location_count
FROM government_services.services s
JOIN government_services.applications a ON s.service_id = a.service_id
JOIN government_services.appointments ap ON a.application_id = ap.application_id
GROUP BY s.service_name;

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

[Assistant]
-- The appointments table is not present in the provided schema. If you want to count by another join, perhaps by documents or payments, please specify.
-- Alternatively, do you want appointment information replaced with application submissions per service and their associated location from service_locations?
SELECT s.service_name, COUNT(a.application_id) AS application_count, COUNT(DISTINCT sl.location_id) AS unique_location_count
FROM government_services.services s
JOIN government_services.applications a ON s.service_id = a.service_id
JOIN government_services.service_locations sl ON s.agency_id = sl.agency_id
GROUP BY s.service_name;

[User] Show only those services where application_count is greater than 50.

[Assistant]
SELECT s.service_name, COUNT(a.application_id) AS application_count, COUNT(DISTINCT sl.location_id) AS unique_location_count
FROM government_services.services s
JOIN government_services.applications a ON s.service_id = a.service_id
JOIN government_services.service_locations sl ON s.agency_id = sl.agency_id
GROUP BY s.service_name
HAVING COUNT(a.application_id) > 50;

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,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    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, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
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.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.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id text, 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 character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] Retrieve the number of drivers grouped by their status.

[Assistant]
SELECT status,
       COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status;

[User] Now, only show statuses where the driver_count is greater than 5 and order the results by driver_count descending.

[Assistant]
SELECT status,
       COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) > 5
ORDER BY driver_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 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] List all game titles and the count of online servers hosting each game.

[Assistant] SELECT T1.title, count(T2.server_id) FROM games AS T1 JOIN servers AS T2 ON T1.game_id = T2.game_id WHERE T2.status = 'online' GROUP BY T1.title;

[User] Only include games that have more than 2 online servers.

[Assistant] SELECT T1.title, count(T2.server_id) FROM games AS T1 JOIN servers AS T2 ON T1.game_id = T2.game_id WHERE T2.status = 'online' GROUP BY T1.title HAVING count(T2.server_id) > 2;

[User] Also, include the average current player count for these online servers per game.

[Assistant] SELECT T1.title, count(T2.server_id), avg(T2.current_players) FROM games AS T1 JOIN servers AS T2 ON T1.game_id = T2.game_id WHERE T2.status = 'online' GROUP BY T1.title HAVING count(T2.server_id) > 2;

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

[Assistant] SELECT T1.title, count(T2.server_id), avg(T2.current_players) FROM games AS T1 JOIN servers AS T2 ON T1.game_id = T2.game_id WHERE T2.status = 'online' GROUP BY T1.title HAVING count(T2.server_id) > 2 ORDER BY avg(T2.current_players) DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )


[User] List the case number, case name, and the full name of the client for cases that have uploaded documents.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

[User] Also include the full name of the lead lawyer for these cases.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name AS client_name ,  T4.full_name AS lawyer_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T4 ON T1.lead_lawyer_id  =  T4.lawyer_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )


[User] List all pairs of diagnoses that belong to the same medical record. Show record_id, diagnosis_id from the first entry as diag1_id, and diagnosis_id from the second entry as diag2_id.

[Assistant]
SELECT d1.record_id,
       d1.diagnosis_id AS diag1_id,
       d2.diagnosis_id AS diag2_id
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.record_id = d2.record_id
 AND d1.diagnosis_id < d2.diagnosis_id;

[User] Only include pairs where both diagnoses are chronic.

[Assistant]
SELECT d1.record_id,
       d1.diagnosis_id AS diag1_id,
       d2.diagnosis_id AS diag2_id
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.record_id = d2.record_id
 AND d1.diagnosis_id < d2.diagnosis_id
WHERE d1.is_chronic = TRUE
  AND d2.is_chronic = TRUE;

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


[User] For each developer, can you find the next developer in the same country using a self join, returning developer_ids and names?

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )


[User] List all pairs of tokens (show token_id for both) that share the same contract address, excluding pairs where the token_id is the same.

[Assistant] SELECT t1.token_id AS token_id1, t2.token_id AS token_id2, t1.contract_address FROM web3.tokens AS t1 JOIN web3.tokens AS t2 ON t1.contract_address = t2.contract_address WHERE t1.token_id < t2.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.tokens ( token_id character varying(64) NOT NULL, contract_address character varying(128) NOT NULL, token_name character varying(128) NOT NULL, token_symbol character varying(32) NOT NULL, decimals integer NOT NULL, total_supply numeric(38,14) NOT NULL, PRIMARY KEY (token_id) )


[User] Provide a count of how many peers were last seen on each distinct day recorded in the system.

[Assistant] SELECT DATE(last_seen), COUNT(*) FROM trading_platform.peers GROUP BY DATE(last_seen) ORDER BY DATE(last_seen);

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.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text, transaction_id text, output_index integer, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] Show me all properties in California with a star rating above 3.5, along with their room types and base rates.

[Assistant] SELECT p.property_name, p.city, p.star_rating, rt.type_name, rt.base_rate FROM hospitality_technology.properties p JOIN hospitality_technology.room_types rt ON p.property_id = rt.property_id WHERE p.state_province = 'California' AND p.star_rating > 3.5;

[User] Now, filter the results to only include room types with a max occupancy of at least 4 people.

[Assistant] SELECT p.property_name, p.city, p.star_rating, rt.type_name, rt.base_rate FROM hospitality_technology.properties p JOIN hospitality_technology.room_types rt ON p.property_id = rt.property_id WHERE p.state_province = 'California' AND p.star_rating > 3.5 AND rt.max_occupancy >= 4;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
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, 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 text, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity integer, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.reviews ( review_id 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 pairs of token transfers within the same transaction and for the same token, where the value of one transfer is exactly twice the value of the other. Show the transaction ID, token ID, and both transfer IDs and their values.

[Assistant]
SELECT
  t1.transaction_id,
  t1.token_id,
  t1.transfer_id AS transfer_id_1,
  t1.value AS value_1,
  t2.transfer_id AS transfer_id_2,
  t2.value AS value_2
FROM web3.token_transfers AS t1
JOIN web3.token_transfers AS t2
  ON t1.transaction_id = t2.transaction_id
  AND t1.token_id = t2.token_id
  AND t1.transfer_id < t2.transfer_id
WHERE
  t1.value = 2 * t2.value
  OR t2.value = 2 * t1.value;

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 all invoices where amount_paid is less than total_amount.

[Assistant]
SELECT *
FROM legal_services.invoices
WHERE amount_paid < total_amount;

[User] Only include those with due_date before today.

[Assistant]
SELECT *
FROM legal_services.invoices
WHERE amount_paid < total_amount
  AND due_date < CURRENT_DATE;

[User] Now also compute how many days each invoice is overdue as difference between CURRENT_DATE and due_date, and only show those overdue by more than 30 days.

[Assistant]
SELECT invoice_id,
       invoice_number,
       client_id,
       total_amount,
       amount_paid,
       due_date,
       CURRENT_DATE - due_date AS days_overdue
FROM legal_services.invoices
WHERE amount_paid < total_amount
  AND due_date < CURRENT_DATE
  AND CURRENT_DATE - due_date > 30;

[User] Finally, order the result by days_overdue descending.

[Assistant]
SELECT invoice_id,
       invoice_number,
       client_id,
       total_amount,
       amount_paid,
       due_date,
       CURRENT_DATE - due_date AS days_overdue
FROM legal_services.invoices
WHERE amount_paid < total_amount
  AND due_date < CURRENT_DATE
  AND CURRENT_DATE - due_date > 30
ORDER BY days_overdue DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )


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

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

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


[User] Retrieve the product_id, product_name, base_premium, and created_at for all active insurance products with a base_premium greater than 1000, ordered by base_premium descending.

[Assistant]
SELECT
  product_id,
  product_name,
  base_premium,
  created_at
FROM insurance.insurance_products
WHERE is_active = true
  AND base_premium > 1000
ORDER BY base_premium 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.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)


[User] Show me all contracts deployed on the 'ethereum' network along with their deployer addresses and the length of their ABI in characters, sorted by ABI length in descending order.

[Assistant] SELECT address, deployer_address, LENGTH(abi) AS abi_length FROM web3.contracts WHERE network_id = 'ethereum' ORDER BY abi_length DESC;

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


[User] List all pairs of law firms that were founded on the same month and day, showing their names, and the shared founding date. Exclude firms founded on January 1st.

[Assistant] SELECT t1.firm_name AS firm1_name, t2.firm_name AS firm2_name, t1.founded_date FROM legal_services.law_firms AS t1 JOIN legal_services.law_firms AS t2 ON MONTH(t1.founded_date) = MONTH(t2.founded_date) AND DAY(t1.founded_date) = DAY(t2.founded_date) AND t1.firm_id < t2.firm_id WHERE MONTH(t1.founded_date) <> 1 OR DAY(t1.founded_date) <> 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 legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )


[User] Find all medical records where the treatment plan includes 'physical therapy' and the patient has an active primary insurance plan, showing the patient ID, record date, and insurance provider details.

[Assistant] SELECT mr.patient_id, mr.record_date, ip.insurance_provider, ip.plan_name, pi.policy_number FROM healthcare.medical_records mr JOIN healthcare.patients p ON mr.patient_id = p.patient_id JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id AND pi.is_primary = true JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE mr.treatment_plan LIKE '%physical therapy%' AND (pi.expiration_date IS NULL OR pi.expiration_date > CURRENT_DATE);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.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 text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )


[User] For each employee who has verified more than one document, list their employee ID, the first document they verified, and the next document they verified, along with both verification timestamps.

[Assistant]
SELECT
  d1.verified_by_employee_id AS employee_id,
  d1.document_id AS first_verified_document,
  d1.verification_timestamp AS first_verification_time,
  d2.document_id AS next_verified_document,
  d2.verification_timestamp AS next_verification_time
FROM government_services.documents d1
JOIN government_services.documents d2
  ON d1.verified_by_employee_id = d2.verified_by_employee_id
  AND d2.verification_timestamp > d1.verification_timestamp
WHERE d1.verification_status = 'Verified'
  AND d2.verification_status = 'Verified';

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


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

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

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

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

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

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

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


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

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

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


[User] For each Bitcoin token tick, show me the creator address from the token_info_bitcoin table and the number of unique wallets currently holding that token.

[Assistant] SELECT ti.tick, ti.creator, COUNT(DISTINCT tb.wallet_address) AS unique_wallets FROM token_info_bitcoin ti JOIN token_balances_bitcoin tb ON ti.tick = tb.tick GROUP BY ti.tick, ti.creator;

[User] Now, only include ticks where there are more than 5 unique wallets, and order the result by the number of unique wallets descending.

[Assistant] SELECT ti.tick, ti.creator, COUNT(DISTINCT tb.wallet_address) AS unique_wallets FROM token_info_bitcoin ti JOIN token_balances_bitcoin tb ON ti.tick = tb.tick GROUP BY ti.tick, ti.creator HAVING COUNT(DISTINCT tb.wallet_address) > 5 ORDER BY unique_wallets 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 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 ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid.text, blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_balances (
    block_number bigint 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_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, 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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, 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 varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


[User] Count the total number of comments each user has made.

[Assistant] SELECT user_id, COUNT(*) AS comment_count FROM comments GROUP BY user_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 social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )


[User] Show me all token names and their contract addresses along with the wallet addresses of users who created wallets in the last 30 days, sorted by wallet creation date.

[Assistant] SELECT t.token_name, t.contract_address, w.address AS wallet_address FROM web3.tokens t JOIN web3.wallets w ON 1=1 WHERE w.created_at >= CURRENT_DATE - INTERVAL '30 days' ORDER BY w.created_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 web3.tokens ( token_id character varying(64) NOT NULL, contract_address character varying(128) NOT NULL, token_name character varying(128) NOT NULL, token_symbol character varying(32) NOT NULL, decimals integer NOT NULL, total_supply numeric(38,14) NOT NULL, PRIMARY KEY (token_id) )
CREATE TABLE web3.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )


[User] For each recipient address, count how many token transfers they have received.

[Assistant] SELECT to_address, COUNT(*) AS received_transfer_count FROM web3.token_transfers GROUP BY to_address;

[User] Only show addresses that have received more than 100 transfers.

[Assistant] SELECT to_address, COUNT(*) AS received_transfer_count FROM web3.token_transfers GROUP BY to_address HAVING COUNT(*) > 100;

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


[User] I need to identify pairs of verified documents submitted by the same citizen. For each pair, display the citizen_id, the earlier document_id with its verification timestamp, and the later document_id with its verification timestamp.

[Assistant]
SELECT
  d1.citizen_id,
  d1.document_id AS earlier_document_id,
  d1.verification_timestamp AS earlier_verification,
  d2.document_id AS later_document_id,
  d2.verification_timestamp AS later_verification
FROM government_services.documents d1
JOIN government_services.documents d2
  ON d1.citizen_id = d2.citizen_id
  AND d1.verification_timestamp < d2.verification_timestamp
WHERE d1.verification_status = 'Verified'
  AND d2.verification_status = 'Verified';


[User] What is the maintenance schedule for the platforms at the station with ID 'ST234' for the next month?

[Assistant] I'm sorry, but I don't have access to the maintenance schedule for the platforms at any station. The data I have only includes basic station information such as station ID, name, location, and number of platforms. For maintenance schedules, you may need to contact the station management or relevant authorities.

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


[User] Show me all pairs of cases led by the same lawyer, including both case names and the lead lawyer ID.

[Assistant]
SELECT c1.lead_lawyer_id,
       c1.case_name AS case_name_1,
       c2.case_name AS case_name_2
FROM legal_services.cases c1
JOIN legal_services.cases c2
  ON c1.lead_lawyer_id = c2.lead_lawyer_id
  AND c1.case_id < c2.case_id;

[User] Actually, only include pairs where the case types are also the same.

[Assistant]
SELECT c1.lead_lawyer_id,
       c1.case_name AS case_name_1,
       c2.case_name AS case_name_2
FROM legal_services.cases c1
JOIN legal_services.cases c2
  ON c1.lead_lawyer_id = c2.lead_lawyer_id
  AND c1.case_type = c2.case_type
  AND c1.case_id < c2.case_id;

[User] Also, show me the earliest opening date between the two cases for each pair.

[Assistant]
SELECT c1.lead_lawyer_id,
       c1.case_name AS case_name_1,
       c2.case_name AS case_name_2,
       LEAST(c1.date_opened, c2.date_opened) AS earliest_open_date
FROM legal_services.cases c1
JOIN legal_services.cases c2
  ON c1.lead_lawyer_id = c2.lead_lawyer_id
  AND c1.case_type = c2.case_type
  AND c1.case_id < c2.case_id;

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


[User] Show me the top 5 users who have created the most wallets, along with their email addresses and the creation date of their first wallet.

[Assistant] SELECT u.user_id, u.email, MIN(w.created_at) AS first_wallet_date, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.user_id, u.email ORDER BY wallet_count DESC LIMIT 5;

[User] Now modify the query to only include wallets created in the last 6 months.

[Assistant] SELECT u.user_id, u.email, MIN(w.created_at) AS first_wallet_date, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id WHERE w.created_at >= NOW() - INTERVAL '6 months' GROUP BY u.user_id, u.email ORDER BY wallet_count DESC LIMIT 5;

[User] Actually, I want to see the total balance across all wallets for each of these users, calculated from unspent UTXOs.

[Assistant] SELECT u.user_id, u.email, MIN(w.created_at) AS first_wallet_date, COUNT(w.wallet_id) AS wallet_count, COALESCE(SUM(ut.amount), 0) AS total_balance FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id LEFT JOIN trading_platform.utxos ut ON w.address = ut.address AND ut.spent = false WHERE w.created_at >= NOW() - INTERVAL '6 months' GROUP BY u.user_id, u.email ORDER BY wallet_count 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 trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)


[User] How many agents are currently active in each license state?

[Assistant]
SELECT license_state, COUNT(*) AS active_agent_count
FROM insurance.agents
WHERE status = 'Active'
GROUP BY license_state;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )


[User] List every diagnosis description paired with every insurance plan's website.

[Assistant] SELECT T1.description, T2.website FROM healthcare.diagnoses AS T1 CROSS JOIN healthcare.insurance_plans AS T2;

[User] Only include chronic diagnoses and plans whose website ends with '.org'.

[Assistant] SELECT T1.description, T2.website FROM healthcare.diagnoses AS T1 CROSS JOIN healthcare.insurance_plans AS T2 WHERE T1.is_chronic = true AND T2.website LIKE '%.org';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )


[User] Get the usernames of users who have created any public posts, and count how many public posts each user has made. Order the results by the post count in descending order.

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

[User] Actually, only include users who have posted more than 5 public posts.

[Assistant] SELECT u.username, COUNT(p.post_id) AS public_post_count FROM social_media.users u JOIN posts p ON u.user_id = p.user_id WHERE p.visibility = 'public' GROUP BY u.username HAVING COUNT(p.post_id) > 5 ORDER BY public_post_count DESC;

[User] Limit the result to the top 10 users by public post count.

[Assistant] SELECT u.username, COUNT(p.post_id) AS public_post_count FROM social_media.users u JOIN posts p ON u.user_id = p.user_id WHERE p.visibility = 'public' GROUP BY u.username HAVING COUNT(p.post_id) > 5 ORDER BY public_post_count DESC LIMIT 10;

[User] Can you also include their email address?

[Assistant] SELECT u.username, u.email, COUNT(p.post_id) AS public_post_count FROM social_media.users u JOIN posts p ON u.user_id = p.user_id WHERE p.visibility = 'public' GROUP BY u.username, u.email HAVING COUNT(p.post_id) > 5 ORDER BY public_post_count DESC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)


[User] For each event, display its event_id, the event_id of the previous event in the same transaction (if any), and the log_index of both events.

[Assistant]
SELECT curr.event_id   AS current_event_id,
       prev.event_id   AS previous_event_id,
       curr.log_index  AS current_log_index,
       prev.log_index  AS previous_log_index,
       curr.transaction_id
FROM web3.events curr
LEFT JOIN web3.events prev
  ON curr.transaction_id = prev.transaction_id
 AND curr.log_index = prev.log_index + 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 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] Can you list all SUI coins with 'active' status and their owner addresses and balances?

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

[User] Add the coin symbol and name from the sui_coins_metadata table.

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

[User] Only include coins where the description mentions 'utility'.

[Assistant]
SELECT sc.object_id, sc.coin_type, sc.owner, sc.balance, scm.symbol, scm.name
FROM sui_coins sc
LEFT JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'active' AND scm.description ILIKE '%utility%';

[User] Limit the output to the top 10 coins sorted by balance descending.

[Assistant]
SELECT sc.object_id, sc.coin_type, sc.owner, sc.balance, scm.symbol, scm.name
FROM sui_coins sc
LEFT JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'active' AND scm.description ILIKE '%utility%'
ORDER BY CAST(sc.balance AS BIGINT) 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 erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk integer )
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 nft_holder_historical ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk integer )
CREATE TABLE sui_coins ( object_id varchar, status varchar, coin_type varchar, balance varchar, owner varchar )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain varchar, contract_address varchar, name varchar, symbol varchar, deploy_block_number bigint, deploy_block_time bigint, erc_type varchar, owner varchar, traits varchar, description varchar, slug varchar, media_info varchar, image_url varchar, banner_image_url varchar, updated_at bigint, banner varchar, token_count bigint, floor_price varchar, floor_price_symbol varchar, floor_price_contract varchar, pk integer )
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )


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

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

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

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

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


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

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

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


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

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

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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.smart_contracts ( contract_id text PRIMARY KEY, creator_address text, code text, timestamp timestamp )