[User] List the first and last name of each citizen along with the city and state of the service location for their agency.

[Assistant]
SELECT c.first_name, c.last_name, sl.city, sl.state
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.employees e ON p.application_id IS NOT NULL AND e.agency_id IS NOT NULL
JOIN government_services.service_locations sl ON e.agency_id = sl.agency_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
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.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )


[User] Get a count of available rooms per room type across all properties.

[Assistant] SELECT T2.type_name, COUNT(T1.room_id) AS available_room_count FROM hospitality_technology.rooms AS T1 INNER JOIN hospitality_technology.room_types AS T2 ON T1.room_type_id = T2.room_type_id WHERE T1.status = 'Available' GROUP BY T2.room_type_id, T2.type_name;

[User] Filter the results to only include room types with more than 50 available rooms. Also include the average base rate for these types.

[Assistant] SELECT T2.type_name, COUNT(T1.room_id) AS available_room_count, AVG(T2.base_rate) AS average_base_rate FROM hospitality_technology.rooms AS T1 INNER JOIN hospitality_technology.room_types AS T2 ON T1.room_type_id = T2.room_type_id WHERE T1.status = 'Available' GROUP BY T2.room_type_id, T2.type_name HAVING COUNT(T1.room_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 hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id text, 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 character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.reservations (
    reservation_id character varying(64) NOT NULL,  -- unique identifier for the booking
    property_id character varying(64) NOT NULL, -- FK to properties table
    guest_id character varying(64) NOT NULL, -- FK to guests table (primary guest)
    room_id character varying(64), -- FK to rooms table (assigned room, might be null initially)
    room_type_id character varying(64) NOT NULL, -- FK to room_types table (booked room type)
    check_in_date date NOT NULL, -- scheduled check-in date
    check_out_date date NOT NULL, -- scheduled check-out date
    actual_check_in_ts timestamp with time zone, -- actual check-in time
    actual_check_out_ts timestamp with time zone, -- actual check-out time
    num_adults integer NOT NULL, -- number of adults
    num_children integer DEFAULT 0, -- number of children
    status character varying(50) NOT NULL, -- e.g., Pending, Confirmed, CheckedIn, CheckedOut, Cancelled, NoShow
    booking_source character varying(100), -- e.g., Website, OTA (Expedia, Booking.com), Phone, WalkIn
    rate_plan_id character varying(64), -- FK to rate_plans table (optional)
    total_amount numeric(12, 2), -- estimated or final total cost
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    special_requests text, -- specific guest requests for this booking
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (reservation_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments ( payment_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, bill_id character varying(64), amount numeric(12,2) NOT NULL, currency_code character varying(3) NOT NULL, payment_method character varying(50) NOT NULL, card_type character varying(50), card_last_four character varying(4), transaction_ref character varying(128), payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, status character varying(50) NOT NULL, staff_id_processed character varying(64), notes text, PRIMARY KEY (payment_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id) )


[User] List the full names and email addresses of staff members who have delivered at least one service order in the past 30 days, along with the count of orders they delivered. Sort by count descending.

[Assistant]
SELECT st.staff_id,
       st.first_name || ' ' || st.last_name AS full_name,
       st.work_email,
       COUNT(so.order_id) AS delivered_count
FROM hospitality_technology.staff st
JOIN hospitality_technology.service_orders so
  ON st.staff_id = so.staff_id_delivered
WHERE so.status = 'Delivered'
  AND so.delivery_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY st.staff_id, st.first_name, st.last_name, st.work_email
ORDER BY delivered_count DESC;

[User] Actually, only include staff who delivered more than 5 orders in that period.

[Assistant]
SELECT st.staff_id,
       st.first_name || ' ' || st.last_name AS full_name,
       st.work_email,
       COUNT(so.order_id) AS delivered_count
FROM hospitality_technology.staff st
JOIN hospitality_technology.service_orders so
  ON st.staff_id = so.staff_id_delivered
WHERE so.status = 'Delivered'
  AND so.delivery_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY st.staff_id, st.first_name, st.last_name, st.work_email
HAVING COUNT(so.order_id) > 5
ORDER BY delivered_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id text, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity integer, unit_price numeric, total_price numeric, status text, notes text, bill_id text )


[User] Show me all invoices where the amount paid is exactly equal to the total amount.

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

[User] Instead, show only the invoice_number, client_id, and payment_date for these invoices, and sort by payment_date descending.

[Assistant] SELECT invoice_number, client_id, payment_date FROM legal_services.invoices WHERE amount_paid = total_amount ORDER BY payment_date DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)


[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] Show me, for each item, the total number of times it has been acquired and the earliest date it was acquired. Also, show the number of unique players who have acquired each item.

[Assistant] SELECT item_id, COUNT(*) AS total_acquisitions, MIN(acquired_at) AS earliest_acquired, COUNT(DISTINCT player_id) AS unique_players FROM gaming_technology.player_inventory GROUP BY item_id;

[User] Now, could you limit the results to only items that have been acquired by at least 3 unique players?

[Assistant] SELECT item_id, COUNT(*) AS total_acquisitions, MIN(acquired_at) AS earliest_acquired, COUNT(DISTINCT player_id) AS unique_players FROM gaming_technology.player_inventory GROUP BY item_id HAVING COUNT(DISTINCT player_id) >= 3;

[User] Also, sort the results by total_acquisitions in descending order.

[Assistant] SELECT item_id, COUNT(*) AS total_acquisitions, MIN(acquired_at) AS earliest_acquired, COUNT(DISTINCT player_id) AS unique_players FROM gaming_technology.player_inventory GROUP BY item_id HAVING COUNT(DISTINCT player_id) >= 3 ORDER BY total_acquisitions DESC;

[User] Finally, limit the output to the top 5 items.

[Assistant] SELECT item_id, COUNT(*) AS total_acquisitions, MIN(acquired_at) AS earliest_acquired, COUNT(DISTINCT player_id) AS unique_players FROM gaming_technology.player_inventory GROUP BY item_id HAVING COUNT(DISTINCT player_id) >= 3 ORDER BY total_acquisitions 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 gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )


[User] What is the average difficulty and the maximum nonce value for all blocks recorded?

[Assistant] SELECT AVG(difficulty), MAX(nonce) FROM blockchain.blocks

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id text, previous_block_id text, timestamp timestamp, nonce integer, merkle_root text, difficulty integer )


[User] Find all patients who have been prescribed medications with dosage greater than 50mg, along with their medication details and prescribing doctor's name.

[Assistant] SELECT p.patient_id, p.first_name, p.last_name, pr.dosage, pr.medication_id, pr.start_date, doc.first_name AS doctor_first_name, doc.last_name AS doctor_last_name FROM healthcare.patients p JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id JOIN healthcare.doctors doc ON pr.doctor_id = doc.doctor_id WHERE CAST(SUBSTRING_INDEX(pr.dosage, 'mg', 1) AS UNSIGNED) > 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 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.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )


[User] Find the wallet address, user ID, and the contract address of any contract where that wallet is listed as the deployer.

[Assistant]
SELECT w.address AS wallet_address, w.user_id, c.address AS contract_address
FROM web3.wallets w
JOIN web3.contracts c ON w.address = c.deployer_address;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.contracts ( contract_id 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) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )


[User] List each case_number along with the total number of documents associated with it.

[Assistant]
SELECT c.case_number,
       COUNT(d.document_id) AS document_count
FROM legal_services.cases c
JOIN legal_services.documents d
  ON c.case_id = d.case_id
GROUP BY c.case_number;

[User] Include cases that have no documents as well, displaying the document_count as zero.

[Assistant]
SELECT c.case_number,
       COUNT(d.document_id) AS document_count
FROM legal_services.cases c
LEFT JOIN legal_services.documents d
  ON c.case_id = d.case_id
GROUP BY c.case_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 legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )


[User] List all medical record entries where the treatment_plan mentions a medication name. Return patient_id, record_id, and the matching medication_name.

[Assistant]
SELECT mr.patient_id,
       mr.record_id,
       m.medication_name
FROM healthcare.medical_records AS mr
JOIN healthcare.medications AS m
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%';

[User] Actually, only include medications manufactured by 'Pfizer'.

[Assistant]
SELECT mr.patient_id,
       mr.record_id,
       m.medication_name
FROM healthcare.medical_records AS mr
JOIN healthcare.medications AS m
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE m.manufacturer = 'Pfizer';

[User] Also sort the results by record_date descending.

[Assistant]
SELECT mr.patient_id,
       mr.record_id,
       m.medication_name
FROM healthcare.medical_records AS mr
JOIN healthcare.medications AS m
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE m.manufacturer = 'Pfizer'
ORDER BY mr.record_date DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    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, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id 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, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


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

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

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


[User] How many claims were reported in the last 90 days?

[Assistant] SELECT COUNT(*) FROM claims WHERE reported_date >= 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 insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id.text, policy_id.text, customer_id.text, first_name.text, last_name.text, relationship.text, percentage_share.numeric, contact_info.text, added_at.timestamp )


[User] List usernames and the length of their 'bio' field for users whose 'is_verified' status is true.

[Assistant] SELECT username, LENGTH(bio) AS bio_length FROM social_media.users WHERE is_verified IS 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 social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )


[User] Find the total number of documents uploaded by each citizen along with their first and last names.

[Assistant]
SELECT c.citizen_id, c.first_name, c.last_name, COUNT(d.document_id) AS document_count
FROM government_services.citizens c
LEFT JOIN government_services.documents d ON c.citizen_id = d.citizen_id
GROUP BY c.citizen_id, c.first_name, c.last_name;

[User] Actually, I only want to include those citizens who have uploaded documents in the last 30 days.

[Assistant]
SELECT c.citizen_id, c.first_name, c.last_name, COUNT(d.document_id) AS document_count
FROM government_services.citizens c
JOIN government_services.documents d ON c.citizen_id = d.citizen_id
WHERE d.upload_timestamp >= NOW() - INTERVAL '30 days'
GROUP BY c.citizen_id, c.first_name, c.last_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.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.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )


[User] List all auto loans (loan_id, principal_amount, interest_rate) where the current principal balance is less than 40% of the original principal amount, along with the account_id and the difference between principal_amount and current_principal_balance.

[Assistant] SELECT loan_id, principal_amount, interest_rate, account_id, (principal_amount - current_principal_balance) AS amount_paid FROM financial_services.loans WHERE loan_type = 'Auto' AND current_principal_balance < (0.4 * principal_amount);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.loans ( loan_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL UNIQUE, loan_type character varying(50) NOT NULL, principal_amount numeric(19, 4) NOT NULL, current_principal_balance numeric(19, 4) NOT NULL, interest_rate numeric(6, 4) NOT NULL, term_months integer NOT NULL, origination_date date NOT NULL, maturity_date date NOT NULL, monthly_payment numeric(12, 4), collateral_description text, status character varying(32) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id) )


[User] For each address, show the total amount contained in UTXOs that have been spent.

[Assistant] SELECT address, SUM(amount) FROM utxos WHERE spent = TRUE GROUP BY address;

[User] Only include addresses where this total spent amount is greater than 500 and order the results by the total amount descending.

[Assistant] SELECT address, SUM(amount) FROM utxos WHERE spent = TRUE GROUP BY address HAVING SUM(amount) > 500 ORDER BY SUM(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 trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)


[User] Display each product alongside the most recently updated product of the same type. Return original_id, original_updated_at, recent_id, recent_updated_at, and product_type.

[Assistant] SELECT p.product_id AS original_id, p.updated_at AS original_updated_at, r.product_id AS recent_id, r.updated_at AS recent_updated_at, p.product_type FROM insurance.insurance_products p JOIN (SELECT product_type, MAX(updated_at) AS max_updated FROM insurance.insurance_products GROUP BY product_type) m ON p.product_type = m.product_type JOIN insurance.insurance_products r ON r.product_type = p.product_type AND r.updated_at = m.max_updated;

[User] Actually, exclude entries where original or recent updated_at is null.

[Assistant] SELECT p.product_id AS original_id, p.updated_at AS original_updated_at, r.product_id AS recent_id, r.updated_at AS recent_updated_at, p.product_type FROM insurance.insurance_products p JOIN (SELECT product_type, MAX(updated_at) AS max_updated FROM insurance.insurance_products WHERE updated_at IS NOT NULL GROUP BY product_type) m ON p.product_type = m.product_type AND p.updated_at IS NOT NULL JOIN insurance.insurance_products r ON r.product_type = p.product_type AND r.updated_at = m.max_updated;

[User] Also, only include product types that have more than 2 products.

[Assistant] SELECT p.product_id AS original_id, p.updated_at AS original_updated_at, r.product_id AS recent_id, r.updated_at AS recent_updated_at, p.product_type FROM insurance.insurance_products p JOIN (SELECT product_type, MAX(updated_at) AS max_updated FROM insurance.insurance_products WHERE updated_at IS NOT NULL GROUP BY product_type) m ON p.product_type = m.product_type AND p.updated_at IS NOT NULL JOIN insurance.insurance_products r ON r.product_type = p.product_type AND r.updated_at = m.max_updated WHERE p.product_type IN (SELECT product_type FROM insurance.insurance_products GROUP BY product_type HAVING COUNT(*) > 2);

[User] Finally, sort the results by recent_updated_at descending.

[Assistant] SELECT p.product_id AS original_id, p.updated_at AS original_updated_at, r.product_id AS recent_id, r.updated_at AS recent_updated_at, p.product_type FROM insurance.insurance_products p JOIN (SELECT product_type, MAX(updated_at) AS max_updated FROM insurance.insurance_products WHERE updated_at IS NOT NULL GROUP BY product_type) m ON p.product_type = m.product_type AND p.updated_at IS NOT NULL JOIN insurance.insurance_products r ON r.product_type = p.product_type AND r.updated_at = m.max_updated WHERE p.product_type IN (SELECT product_type FROM insurance.insurance_products GROUP BY product_type HAVING COUNT(*) > 2) ORDER BY recent_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.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] What is the total sum of all amounts for all UTXOs in the system, regardless of whether they are spent or unspent?

[Assistant] SELECT SUM(amount) FROM trading_platform.utxos

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 PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
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, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, 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 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.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] Find the names of service locations where services categorized as 'Licensing' have had appointments scheduled.

[Assistant] SELECT DISTINCT T1.location_name FROM service_locations AS T1 JOIN appointments AS T2 ON T1.location_id = T2.location_id JOIN services AS T3 ON T2.service_id = T3.service_id WHERE T3.category = 'Licensing';

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 character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.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.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    employee_id character varying(64), -- FK to employees table (optional, if assigned)
    location_id character varying(64), -- FK to service_locations table (if physical)
    service_id character varying(64), -- FK to services table (optional, if related to specific service)
    scheduled_start_time timestamp NOT NULL,
    scheduled_end_time timestamp,
    purpose text NOT NULL, -- reason for the appointment
    status character varying(30) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-Show
    booking_method character varying(50), -- e.g., Online, Phone, In-Person
    created_at timestamp NOT NULL, -- when the appointment was booked
    notes text,
    PRIMARY KEY (appointment_id)
)


[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] Show all users whose full name starts with 'A' and who have updated their profile in June 2024. Please include their usernames and updated_at timestamps.

[Assistant] SELECT username, updated_at FROM social_media.users WHERE full_name ILIKE 'A%' AND EXTRACT(YEAR FROM updated_at) = 2024 AND EXTRACT(MONTH FROM updated_at) = 6;

[User] I also want to know which of them have a verified profile. Can you add the verification status to the results?

[Assistant] SELECT username, updated_at, is_verified FROM social_media.users WHERE full_name ILIKE 'A%' AND EXTRACT(YEAR FROM updated_at) = 2024 AND EXTRACT(MONTH FROM updated_at) = 6;

[User] Now, please only show the users who are verified.

[Assistant] SELECT username, updated_at FROM social_media.users WHERE full_name ILIKE 'A%' AND EXTRACT(YEAR FROM updated_at) = 2024 AND EXTRACT(MONTH FROM updated_at) = 6 AND is_verified = 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 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 )


[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] List all agencies that do not have a website URL specified. Return their agency_id, agency_name, and main_phone_number.

[Assistant] SELECT agency_id, agency_name, main_phone_number FROM government_services.agencies WHERE website_url IS NULL OR website_url = '';

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.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )


[User] List all medical records, showing the record ID, record date, and the full name of the doctor who created the record. Include the patient ID as well.

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)


[User] Could you list the player_id of users who have unlocked both achievement '11111111-1111-1111-1111-111111111111' and '22222222-2222-2222-2222-222222222222'?

[Assistant]
SELECT pa1.player_id
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
WHERE pa1.achievement_id = '11111111-1111-1111-1111-111111111111'
  AND pa2.achievement_id = '22222222-2222-2222-2222-222222222222'
GROUP BY pa1.player_id;

[User] Now also include the date when each of these achievements was unlocked, labeled as unlocked_ach1 and unlocked_ach2.

[Assistant]
SELECT pa1.player_id,
       pa1.unlocked_at AS unlocked_ach1,
       pa2.unlocked_at AS unlocked_ach2
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
WHERE pa1.achievement_id = '11111111-1111-1111-1111-111111111111'
  AND pa2.achievement_id = '22222222-2222-2222-2222-222222222222'
GROUP BY pa1.player_id, pa1.unlocked_at, pa2.unlocked_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 gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )


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

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

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

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

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


[User] What are the safety ratings or crash statistics for the Boeing 787 Dreamliner?

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

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


[User] What are the fuel consumption rates per hour for the Boeing 747-8 model?

[Assistant] I'm sorry, but I can't provide information on the fuel consumption rates for the Boeing 747-8 model as this data is not included in the aircraft_models table. The table contains details such as model name, manufacturer, passenger capacity, and other specifications, but fuel consumption data is not available. If you have another question or need assistance with something else related to the table, I'm happy to help.

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


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

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

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


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)


[User] Find all pairs of users where the registration times are within 30 minutes of each other, and show both user IDs, usernames, and the time difference in minutes.

[Assistant] SELECT u1.user_id AS user1_id, u1.username AS user1_name, u2.user_id AS user2_id, u2.username AS user2_name, ROUND(ABS(EXTRACT(EPOCH FROM u1.created_at - u2.created_at))/60,2) AS diff_minutes FROM web3.users u1 JOIN web3.users u2 ON u1.user_id < u2.user_id WHERE ABS(EXTRACT(EPOCH FROM u1.created_at - u2.created_at))/60 <= 30;

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.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )


[User] Show me all doctors who have prescribed medications with a dosage greater than 200mg, along with their specialties and the count of such prescriptions per doctor.

[Assistant] SELECT d.doctor_id, d.first_name, d.last_name, d.specialty, COUNT(p.prescription_id) AS prescription_count FROM healthcare.doctors d JOIN healthcare.prescriptions p ON d.doctor_id = p.doctor_id WHERE CAST(SUBSTRING(p.dosage FROM '[0-9]+') AS INTEGER) > 200 GROUP BY d.doctor_id, d.first_name, d.last_name, d.specialty ORDER BY prescription_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.text, first_name.text, last_name.text, specialty.text, license_number.text, phone_number.text, email.text, hospital_affiliation_id.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
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.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )


[User] List pairs of citizens who share the same email domain.

[Assistant]
SELECT c1.first_name AS first1,
       c1.last_name AS last1,
       c2.first_name AS first2,
       c2.last_name AS last2,
       SPLIT_PART(c1.contact_email, '@', 2) AS domain
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON SPLIT_PART(c1.contact_email, '@', 2) = SPLIT_PART(c2.contact_email, '@', 2)
 AND c1.citizen_id < c2.citizen_id
WHERE c1.contact_email IS NOT NULL
  AND c2.contact_email IS NOT NULL;

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


[User] Show me each product_type along with the count of products for that type, but only include types where the average base_premium exceeds 500. Order the results by the product count in descending order.

[Assistant]
SELECT product_type,
       COUNT(*) AS product_count
FROM insurance.insurance_products
GROUP BY product_type
HAVING AVG(base_premium) > 500
ORDER BY product_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.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] Show me the total billable hours and total billed amount for each lawyer who worked on 'Civil Litigation' cases in 2023, sorted by billed amount descending.

[Assistant]
SELECT te.lawyer_id,
       SUM(te.hours_spent) AS total_billable_hours,
       SUM(te.hours_spent * te.billing_rate) AS total_billed_amount
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = true
  AND te.is_billed = true
  AND c.case_type = 'Civil Litigation'
  AND te.date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY te.lawyer_id
ORDER BY total_billed_amount DESC;

[User] Actually, I'd like to include only those lawyers who have at least 10 billable entries in that period.

[Assistant]
SELECT te.lawyer_id,
       SUM(te.hours_spent) AS total_billable_hours,
       SUM(te.hours_spent * te.billing_rate) AS total_billed_amount
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = true
  AND te.is_billed = true
  AND c.case_type = 'Civil Litigation'
  AND te.date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY te.lawyer_id
HAVING COUNT(*) >= 10
ORDER BY total_billed_amount DESC;

[User] Also break down the report by case, listing each lawyer and case_number along with their billable hours and billed amount per case, sorted by billed amount descending.

[Assistant]
SELECT te.lawyer_id,
       c.case_number,
       SUM(te.hours_spent) AS case_billable_hours,
       SUM(te.hours_spent * te.billing_rate) AS case_billed_amount
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = true
  AND te.is_billed = true
  AND c.case_type = 'Civil Litigation'
  AND te.date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY te.lawyer_id, c.case_number
ORDER BY case_billed_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 legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )


[User] 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] Find all unique diagnosis codes that are associated with more than one doctor, and show how many doctors are linked to each code.

[Assistant] SELECT diagnosis_code, COUNT(DISTINCT doctor_id) AS doctor_count FROM healthcare.diagnoses GROUP BY diagnosis_code HAVING COUNT(DISTINCT doctor_id) > 1;

[User] Also, show only codes that are used after January 1st, 2023.

[Assistant] SELECT diagnosis_code, COUNT(DISTINCT doctor_id) AS doctor_count FROM healthcare.diagnoses WHERE diagnosis_date > '2023-01-01' GROUP BY diagnosis_code HAVING COUNT(DISTINCT doctor_id) > 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )


[User] List all patients who have a current prescription that was prescribed by a doctor with a specialty of 'Endocrinology'. Show patient full name, prescription ID, medication name, and prescription date.

[Assistant]
SELECT p.patient_id, p.first_name || ' ' || p.last_name AS full_name, pr.prescription_id, m.medication_name, pr.prescription_date
FROM healthcare.prescriptions pr
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
JOIN healthcare.patients p ON pr.patient_id = p.patient_id
JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id
WHERE d.specialty = 'Endocrinology' AND pr.end_date IS NULL OR pr.end_date > CURRENT_DATE;

[User] Include prescriptions that ended within the past 7 days as well.

[Assistant]
SELECT p.patient_id, p.first_name || ' ' || p.last_name AS full_name, pr.prescription_id, m.medication_name, pr.prescription_date
FROM healthcare.prescriptions pr
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
JOIN healthcare.patients p ON pr.patient_id = p.patient_id
JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id
WHERE d.specialty = 'Endocrinology' AND (pr.end_date IS NULL OR pr.end_date > CURRENT_DATE OR pr.end_date >= CURRENT_DATE - INTERVAL '7 days');

[User] I got an error: relation "healthcare.patients" does not exist. Can you fix it using existing tables only?

[Assistant]
SELECT pr.patient_id, pr.prescription_id, m.medication_name, pr.prescription_date
FROM healthcare.prescriptions pr
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id
WHERE d.specialty = 'Endocrinology' AND (pr.end_date IS NULL OR pr.end_date > CURRENT_DATE OR pr.end_date >= CURRENT_DATE - INTERVAL '7 days');

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


[User] Retrieve each agent's ID, full name, and the count of 'Pending' policies they have sold with a premium_amount greater than 2000. Order the results by the policy count descending.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       COUNT(p.policy_id) AS pending_policy_count
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE p.status = 'Pending'
  AND p.premium_amount > 2000
GROUP BY a.agent_id, agent_name
ORDER BY pending_policy_count DESC;

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


[User] 能否帮我统计特定车站(station_id 为 'station_xyz')的所有工作人员数量？

[Assistant]
MATCH (s:Station {station_id: 'station_xyz'})<-[:BASED_AT]-(staff:Staff)
RETURN COUNT(staff) AS total_staff

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// Node Label: :Station
// Properties:
//   station_id: String (Constraint: UNIQUE)
//   station_name: String
//   city: String (Index recommended)
//   state_province: String
//   country_code: String
//   address: String
//   timezone: String
//   number_of_platforms: Integer
//   created_at: DateTime
//   last_updated_at: DateTime
// Example Cypher CREATE:
// CREATE (:Station {station_id: 'station_xyz', station_name: 'Grand Central Terminal', city: 'New York', ...})
// Node Label: :Platform
// Properties:
//   platform_id: String (Constraint: UNIQUE)
//   platform_number: String
//   track_number: String
//   status: String
//   length_meters: Float
//   accessible: Boolean
// Relationship: (:Platform)-[:LOCATED_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (s:Station {station_id: 'station_xyz'})
// CREATE (p:Platform {platform_id: 'plat_123', ...})-[:LOCATED_AT]->(s)
// Node Label: :Train
// Properties:
//   train_id: String (Constraint: UNIQUE)
//   train_number: String (Constraint: UNIQUE)
//   model: String
//   manufacturer: String
//   year_manufactured: Integer
//   capacity: Integer
//   status: String
//   last_maintenance_date: Date
//   next_maintenance_date: Date
// Example Cypher CREATE:
// CREATE (:Train {train_id: 'train_789', train_number: 'Acela 2151', ...})
// Node Label: :TrainCar
// Properties:
//   car_id: String (Constraint: UNIQUE)
//   car_number: String
//   car_type: String
//   class: String
//   capacity: Integer
//   features: String (Or List<String> if driver supports)
// Relationship: (:TrainCar)-[:PART_OF_TRAIN]->(:Train)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'})
// CREATE (c:TrainCar {car_id: 'car_abc', ...})-[:PART_OF_TRAIN]->(t)
// Node Label: :Route
// Properties:
//   route_id: String (Constraint: UNIQUE)
//   route_name: String
//   description: String
//   is_active: Boolean
// Relationships:
//   (:Route)-[:STARTS_AT]->(:Station)
//   (:Route)-[:ENDS_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (origin:Station {station_id: 'station_bos'}), (dest:Station {station_id: 'station_was'})
// CREATE (r:Route {route_id: 'route_ne_corr', ...})-[:STARTS_AT]->(origin), (r)-[:ENDS_AT]->(dest)
// Relationship: (:Route)-[rel:HAS_STOP]->(:Station)
// Relationship Properties on :HAS_STOP:
//   sequence_order: Integer
//   distance_from_previous_km: Float
//   typical_stop_duration_minutes: Integer
// Example Cypher CREATE:
// MATCH (r:Route {route_id: 'route_ne_corr'}), (s:Station {station_id: 'station_pvd'})
// CREATE (r)-[:HAS_STOP {sequence_order: 2, distance_from_previous_km: 70.5, ...}]->(s)
// Node Label: :ScheduledTrip (or just :Trip)
// Properties:
//   schedule_id: String (Constraint: UNIQUE)
//   departure_datetime: DateTime
//   arrival_datetime: DateTime
//   status: String
//   notes: String
// Relationships:
//   (:ScheduledTrip)-[:USES_TRAIN]->(:Train)
//   (:ScheduledTrip)-[:FOLLOWS_ROUTE]->(:Route)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'}), (r:Route {route_id: 'route_ne_corr'})
// CREATE (sched:ScheduledTrip {schedule_id: 'sched_1122', ...})-[:USES_TRAIN]->(t), (sched)-[:FOLLOWS_ROUTE]->(r)
// Relationship: (:ScheduledTrip)-[rel:SCHEDULED_STOP]->(:Station)
// Relationship Properties on :SCHEDULED_STOP:
//   sequence_order: Integer
//   platform_id: String (references Platform node if modeled, or just store ID)
//   scheduled_arrival_time: DateTime
//   scheduled_departure_time: DateTime
//   actual_arrival_time: DateTime
//   actual_departure_time: DateTime
//   status: String
// Example Cypher CREATE:
// MATCH (sched:ScheduledTrip {schedule_id: 'sched_1122'}), (s:Station {station_id: 'station_pvd'})
// CREATE (sched)-[:SCHEDULED_STOP {sequence_order: 2, platform_id: 'plat_pvd_1', ...}]->(s)
// Node Label: :Passenger
// Properties:
//   passenger_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   email: String (Constraint: UNIQUE, if not null)
//   phone_number: String (Constraint: UNIQUE, if not null)
//   date_of_birth: Date
//   loyalty_program_id: String
//   created_at: DateTime
// Example Cypher CREATE:
// CREATE (:Passenger {passenger_id: 'pass_pqr', first_name: 'Alice', ...})
// Node Label: :Booking
// Properties:
//   booking_id: String (Constraint: UNIQUE)
//   booking_datetime: DateTime
//   status: String
//   total_price: Float
//   currency_code: String
//   special_requests: String
// Relationships:
//   (:Passenger)-[:MADE_BOOKING]->(:Booking)
//   (:Booking)-[:FOR_TRIP]->(:ScheduledTrip)
// Example Cypher CREATE:
// MATCH (p:Passenger {passenger_id: 'pass_pqr'}), (sched:ScheduledTrip {schedule_id: 'sched_1122'})
// CREATE (p)-[:MADE_BOOKING]->(b:Booking {booking_id: 'book_zyx', ...})-[:FOR_TRIP]->(sched)
// Node Label: :Ticket
// Properties:
//   ticket_id: String (Constraint: UNIQUE)
//   seat_number: String
//   ticket_type: String
//   price: Float
//   is_checked_in: Boolean
//   qr_code_data: String
// Relationships:
//   (:Ticket)-[:PART_OF_BOOKING]->(:Booking)
//   (:Ticket)-[:ASSIGNED_TO_CAR]->(:TrainCar)
// Example Cypher CREATE:
// MATCH (b:Booking {booking_id: 'book_zyx'}), (c:TrainCar {car_id: 'car_abc'})
// CREATE (t:Ticket {ticket_id: 'tkt_1a2b', ...})-[:PART_OF_BOOKING]->(b), (t)-[:ASSIGNED_TO_CAR]->(c)
// Node Label: :Staff
// Properties:
//   staff_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   role: String
//   employee_number: String (Constraint: UNIQUE)
//   hire_date: Date
//   contact_email: String (Constraint: UNIQUE, if not null)
//   contact_phone: String
//   is_active: Boolean
// Relationship (Optional):
//   (:Staff)-[:BASED_AT]->(:Station)
// Example Cypher CREATE:
// CREATE (:Staff {staff_id: 'staff_mno', first_name: 'Bob', ...})
// OPTIONAL MATCH (s:Station {station_id: 'station_xyz'}) // If primary_station_id exists
// WITH s, staff_mno // Need to get the created staff node reference
// WHERE s IS NOT NULL
// CREATE (staff_mno)-[:BASED_AT]->(s)


[User] Count the number of law firms founded in each decade. Show the decade (e.g., 1990s, 2000s) and the count.

[Assistant] SELECT CONCAT(FLOOR(EXTRACT(YEAR FROM founded_date) / 10) * 10, 's') AS decade, COUNT(*) AS firm_count FROM law_firms WHERE founded_date IS NOT NULL GROUP BY decade ORDER BY decade;

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


[User] For each event recorded, list its ID, name, and the status and value of the transaction in which it occurred.

[Assistant] SELECT E.event_id, E.event_name, E.transaction_id, T.status, T.value FROM web3.events AS E JOIN web3.transactions AS T ON E.transaction_id = T.transaction_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.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)
)
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )