[User] For each diagnosis, show the diagnosis code, description, and the full name of the doctor who made the diagnosis.

[Assistant]
SELECT dgn.diagnosis_code, dgn.description, doc.first_name AS doctor_first_name, doc.last_name AS doctor_last_name
FROM healthcare.diagnoses dgn
JOIN healthcare.doctors doc ON dgn.doctor_id = doc.doctor_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 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.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.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 guests from California (state_province = 'California') who are loyalty members, along with their email and phone number.

[Assistant] SELECT guest_id, first_name, last_name, email, phone_number FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL;

[User] Now, filter these results to only include guests who have communication consent and were created in the last year.

[Assistant] SELECT guest_id, first_name, last_name, email, phone_number FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL AND communication_consent = true AND created_at >= CURRENT_DATE - INTERVAL '1 year';

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

[Assistant] SELECT guest_id, first_name, last_name, email, phone_number, city FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL AND communication_consent = true AND created_at >= CURRENT_DATE - INTERVAL '1 year';

[User] Actually, I only need guests from Los Angeles and San Francisco, and order by last name in alphabetical order.

[Assistant] SELECT guest_id, first_name, last_name, email, phone_number, city FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL AND communication_consent = true AND created_at >= CURRENT_DATE - INTERVAL '1 year' AND city IN ('Los Angeles', 'San Francisco') ORDER BY last_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )


[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] Count the total number of invoices issued in each calendar year and month. Show the year, month, and the count, ordered chronologically.

[Assistant] SELECT EXTRACT(YEAR FROM issue_date) AS issue_year, EXTRACT(MONTH FROM issue_date) AS issue_month, COUNT(*) AS invoice_count FROM legal_services.invoices GROUP BY issue_year, issue_month ORDER BY issue_year, issue_month;

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


[User] 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] List each citizen's first and last name along with the number of applications they have submitted, only include those with at least 3 applications.

[Assistant]
SELECT c.first_name, c.last_name, COUNT(a.application_id) AS application_count
FROM government_services.citizens c
JOIN government_services.applications a ON c.citizen_id = a.citizen_id
GROUP BY c.first_name, c.last_name
HAVING COUNT(a.application_id) >= 3;

[User] Now also show the average standard fee of the services those applications are associated with.

[Assistant]
SELECT c.first_name, c.last_name, COUNT(a.application_id) AS application_count, AVG(s.standard_fee) AS avg_service_fee
FROM government_services.citizens c
JOIN government_services.applications a ON c.citizen_id = a.citizen_id
JOIN government_services.services s ON a.service_id = s.service_id
GROUP BY c.first_name, c.last_name
HAVING COUNT(a.application_id) >= 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )


[User] 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] Can you show, for each employee, the full name and job title of their direct manager, as well as the employee's department and branch_id?

[Assistant]
SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.department AS employee_department, e.branch_id AS employee_branch_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.job_title AS manager_job_title
FROM financial_services.employees e
LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id;

[User] Actually, show only employees who have a manager assigned, and include only those where the manager works at a different branch than the employee.

[Assistant]
SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.department AS employee_department, e.branch_id AS employee_branch_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.job_title AS manager_job_title, m.branch_id AS manager_branch_id
FROM financial_services.employees e
INNER JOIN financial_services.employees m ON e.manager_id = m.employee_id
WHERE e.branch_id IS DISTINCT FROM m.branch_id;

[User] Now, only include employees who were hired after 2021-01-01.

[Assistant]
SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.department AS employee_department, e.branch_id AS employee_branch_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.job_title AS manager_job_title, m.branch_id AS manager_branch_id
FROM financial_services.employees e
INNER JOIN financial_services.employees m ON e.manager_id = m.employee_id
WHERE e.branch_id IS DISTINCT FROM m.branch_id
  AND e.hire_date > '2021-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.transactions (
    transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    PRIMARY KEY (transaction_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id)
)
CREATE TABLE financial_services.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
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)
)
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] Show me all employees (employee_id, first_name, last_name) who work in the 'Investment' department and have processed trades (trade_id, security_id) in the last month, along with the trade details.

[Assistant] SELECT e.employee_id, e.first_name, e.last_name, t.trade_id, t.security_id FROM financial_services.employees e JOIN financial_services.trades t ON e.employee_id = t.account_id WHERE e.department = 'Investment' AND t.trade_timestamp >= CURRENT_DATE - INTERVAL '1 month'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, account_number character varying(128) NOT NULL UNIQUE, account_type character varying(50) NOT NULL, balance numeric(19, 4) NOT NULL DEFAULT 0.00, currency character varying(3) NOT NULL, opened_date date NOT NULL, status character varying(32) NOT NULL, interest_rate numeric(5, 4), last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (account_id), FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id) )
CREATE TABLE financial_services.transactions ( transaction_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, related_account_id character varying(64), transaction_type character varying(50) NOT NULL, amount numeric(19, 4) NOT NULL, currency character varying(3) NOT NULL, transaction_date timestamp NOT NULL, effective_date date NOT NULL, description text, status character varying(32) NOT NULL, reference_number character varying(128), PRIMARY KEY (transaction_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id) )
CREATE TABLE financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), 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.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(100) NOT NULL, department character varying(100), branch_id character varying(64), email character varying(128) NOT NULL UNIQUE, phone_extension character varying(20), hire_date date NOT NULL, termination_date date, manager_id character varying(64), status character varying(32) NOT NULL, PRIMARY KEY (employee_id), FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id) )
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 property, show the most expensive room type by base_rate, including the property name, room type name, and the highest base_rate.

[Assistant]
SELECT p.property_name,
       rt.type_name,
       MAX(rt.base_rate) AS max_base_rate
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p
  ON rt.property_id = p.property_id
GROUP BY p.property_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] Show me all lawyers' full names, their bar number, and if they are partners, the full name of another partner from their firm.

[Assistant]
SELECT l1.first_name || ' ' || l1.last_name AS lawyer_full_name, l1.bar_number,
       CASE WHEN l1.is_partner = TRUE THEN (
           SELECT l2.first_name || ' ' || l2.last_name
           FROM legal_services.lawyers l2
           WHERE l2.firm_id = l1.firm_id AND l2.is_partner = TRUE AND l2.lawyer_id <> l1.lawyer_id
           LIMIT 1
       ) ELSE NULL END AS another_partner_full_name
FROM legal_services.lawyers l1;

[User] Only include lawyers who have an email address specified.

[Assistant]
SELECT l1.first_name || ' ' || l1.last_name AS lawyer_full_name, l1.bar_number,
       CASE WHEN l1.is_partner = TRUE THEN (
           SELECT l2.first_name || ' ' || l2.last_name
           FROM legal_services.lawyers l2
           WHERE l2.firm_id = l1.firm_id AND l2.is_partner = TRUE AND l2.lawyer_id <> l1.lawyer_id
           LIMIT 1
       ) ELSE NULL END AS another_partner_full_name
FROM legal_services.lawyers l1
WHERE l1.email IS NOT NULL AND l1.email <> '';

[User] Actually, restrict it to lawyers hired in or after 2023.

[Assistant]
SELECT l1.first_name || ' ' || l1.last_name AS lawyer_full_name, l1.bar_number,
       CASE WHEN l1.is_partner = TRUE THEN (
           SELECT l2.first_name || ' ' || l2.last_name
           FROM legal_services.lawyers l2
           WHERE l2.firm_id = l1.firm_id AND l2.is_partner = TRUE AND l2.lawyer_id <> l1.lawyer_id
           LIMIT 1
       ) ELSE NULL END AS another_partner_full_name
FROM legal_services.lawyers l1
WHERE l1.email IS NOT NULL AND l1.email <> '' AND l1.hire_date >= '2023-01-01';

[User] Sort the results by the lawyer's last name in descending order.

[Assistant]
SELECT l1.first_name || ' ' || l1.last_name AS lawyer_full_name, l1.bar_number,
       CASE WHEN l1.is_partner = TRUE THEN (
           SELECT l2.first_name || ' ' || l2.last_name
           FROM legal_services.lawyers l2
           WHERE l2.firm_id = l1.firm_id AND l2.is_partner = TRUE AND l2.lawyer_id <> l1.lawyer_id
           LIMIT 1
       ) ELSE NULL END AS another_partner_full_name
FROM legal_services.lawyers l1
WHERE l1.email IS NOT NULL AND l1.email <> '' AND l1.hire_date >= '2023-01-01'
ORDER BY l1.last_name 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.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )


[User] List the plan_id, plan_name, and plan_type for all insurance plans where the insurance_provider is 'Humana'.

[Assistant]
SELECT
  plan_id,
  plan_name,
  plan_type
FROM healthcare.insurance_plans
WHERE
  insurance_provider = 'Humana';

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 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.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 PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- 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)
)


[User] Find law firms where the managing partner is also listed as a lawyer within that firm. Show the firm name and the managing partner's first and last name.

[Assistant] SELECT T1.firm_name, T2.first_name, T2.last_name FROM law_firms AS T1 JOIN lawyers AS T2 ON T1.firm_id = T2.firm_id AND T1.managing_partner_id = T2.lawyer_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
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 )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )


[User] For each patient, find the next appointment after each one. Return patient_id, appointment_id, next_appointment_id, and the waiting time in minutes between them.

[Assistant]
SELECT A.patient_id,
       A.appointment_id AS current_id,
       B.appointment_id AS next_id,
       EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 AS wait_minutes
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.patient_id = B.patient_id
 AND B.appointment_time = (
       SELECT MIN(appointment_time)
       FROM healthcare.appointments
       WHERE patient_id = A.patient_id
         AND appointment_time > A.appointment_time
   );

[User] Now include only the pairs where the waiting time is less than 30 minutes.

[Assistant]
SELECT A.patient_id,
       A.appointment_id AS current_id,
       B.appointment_id AS next_id,
       EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 AS wait_minutes
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.patient_id = B.patient_id
 AND B.appointment_time = (
       SELECT MIN(appointment_time)
       FROM healthcare.appointments
       WHERE patient_id = A.patient_id
         AND appointment_time > A.appointment_time
   )
WHERE EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 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 healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )


[User] Find the product type that has the lowest average base premium among all product types that have at least 5 active products. Display the product type and its average base premium.

[Assistant] SELECT product_type, AVG(base_premium) AS average_premium FROM insurance.insurance_products WHERE is_active = TRUE GROUP BY product_type HAVING COUNT(product_id) >= 5 ORDER BY AVG(base_premium) ASC LIMIT 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 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] Get each staff member who delivered service orders in the last month and the count of orders they delivered.

[Assistant]
SELECT s.staff_id,
       s.first_name,
       s.last_name,
       COUNT(so.order_id) AS delivered_orders
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.staff s ON so.staff_id_delivered = s.staff_id
WHERE so.delivery_timestamp >= date_trunc('month', current_date) - INTERVAL '1 month'
  AND so.delivery_timestamp < date_trunc('month', current_date)
GROUP BY s.staff_id, s.first_name, s.last_name;

[User] Actually, only include staff who delivered more than 5 orders and order the result by delivered_orders descending.

[Assistant]
SELECT s.staff_id,
       s.first_name,
       s.last_name,
       COUNT(so.order_id) AS delivered_orders
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.staff s ON so.staff_id_delivered = s.staff_id
WHERE so.delivery_timestamp >= date_trunc('month', current_date) - INTERVAL '1 month'
  AND so.delivery_timestamp < date_trunc('month', current_date)
GROUP BY s.staff_id, s.first_name, s.last_name
HAVING COUNT(so.order_id) > 5
ORDER BY delivered_orders DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )


[User] Count the number of staff members for each position.

[Assistant]
SELECT
  position,
  COUNT(staff_id) AS staff_count
FROM hospitality_technology.staff
GROUP BY
  position;

[User] Only show positions that have more than 10 staff members and order the results by the count descending.

[Assistant]
SELECT
  position,
  COUNT(staff_id) AS staff_count
FROM hospitality_technology.staff
GROUP BY
  position
HAVING
  COUNT(staff_id) > 10
ORDER BY
  staff_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )


[User] What is the current location of train number Acela 2151?

[Assistant] I'm sorry, but I don't have access to real-time location data for trains. The database only contains static information such as train ID, model, capacity, and maintenance schedules. For current location updates, please check with the train operator or a tracking service.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.trains (
    train_id character varying(64) NOT NULL, -- Unique identifier for the train set
    train_number character varying(32) NOT NULL, -- Operational number of the train (e.g., 'Acela 2151')
    model character varying(128), -- Model of the train (e.g., 'Siemens Velaro')
    manufacturer character varying(128), -- Manufacturer of the train
    year_manufactured integer, -- Year the train was built
    capacity integer NOT NULL, -- Total passenger capacity
    status character varying(32) NOT NULL DEFAULT 'Active', -- e.g., Active, Maintenance, Retired
    last_maintenance_date date, -- Date of last scheduled maintenance
    next_maintenance_date date, -- Date of next scheduled maintenance
    PRIMARY KEY (train_id),
    UNIQUE (train_number)
)


[User] Show me the earliest unlock date for each achievement along with the player_id who unlocked it.

[Assistant] SELECT achievement_id, player_id, MIN(unlocked_at) AS earliest_unlock FROM gaming_technology.player_achievements GROUP BY achievement_id, player_id;

[User] Actually, for each achievement, I only want to see the player who was the very first to unlock it and the corresponding date.

[Assistant] SELECT pa.achievement_id, pa.player_id, pa.unlocked_at AS earliest_unlock FROM gaming_technology.player_achievements pa INNER JOIN ( SELECT achievement_id, MIN(unlocked_at) AS min_unlocked_at FROM gaming_technology.player_achievements GROUP BY achievement_id ) first_unlock ON pa.achievement_id = first_unlock.achievement_id AND pa.unlocked_at = first_unlock.min_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, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )


[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] List the first name, last name, and job title of each employee, along with the job title of their manager.

[Assistant] SELECT e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.job_title AS employee_job_title, m.job_title AS manager_job_title FROM government_services.employees AS e LEFT JOIN government_services.employees AS m ON e.manager_employee_id = m.employee_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.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)
)


[User] Could you list the name, type, and rarity for all in-game items that belong to games released on or after January 1st, 2022?

[Assistant] SELECT ii.item_name, ii.item_type, ii.rarity FROM gaming_technology.in_game_items AS ii JOIN gaming_technology.games AS g ON ii.game_id = g.game_id WHERE g.release_date >= '2022-01-01';

[User] Now, only include items that have a 'Epic' or 'Legendary' rarity.

[Assistant] SELECT ii.item_name, ii.item_type, ii.rarity FROM gaming_technology.in_game_items AS ii JOIN gaming_technology.games AS g ON ii.game_id = g.game_id WHERE g.release_date >= '2022-01-01' AND ii.rarity IN ('Epic', 'Legendary');

[User] Please also include the title of the game for each item and order the list by rarity ascending, then by item name ascending.

[Assistant] SELECT ii.item_name, ii.item_type, ii.rarity, g.title AS game_title FROM gaming_technology.in_game_items AS ii JOIN gaming_technology.games AS g ON ii.game_id = g.game_id WHERE g.release_date >= '2022-01-01' AND ii.rarity IN ('Epic', 'Legendary') ORDER BY ii.rarity ASC, ii.item_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player
    username character varying(100) NOT NULL UNIQUE, -- player's chosen display name
    email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery
    password_hash text NOT NULL, -- securely hashed password
    registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created
    last_login timestamp with time zone, -- timestamp of the last successful login
    country_code character(2), -- player's country (ISO 3166-1 alpha-2)
    status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended)
    profile_data jsonb, -- flexible field for avatar url, bio, preferences etc.
    PRIMARY KEY (player_id)
)
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)


[User] Show me the average, maximum, and minimum points for all achievements.

[Assistant] SELECT AVG(points) AS average_points, MAX(points) AS maximum_points, MIN(points) AS minimum_points FROM gaming_technology.achievements;

[User] Can you break this down by whether the achievement is hidden or not?

[Assistant] SELECT hidden, AVG(points) AS average_points, MAX(points) AS maximum_points, MIN(points) AS minimum_points FROM gaming_technology.achievements GROUP BY hidden;

[User] Exclude achievements with zero points from this calculation.

[Assistant] SELECT hidden, AVG(points) AS average_points, MAX(points) AS maximum_points, MIN(points) AS minimum_points FROM gaming_technology.achievements WHERE points > 0 GROUP BY hidden;

[User] Also, include the count of achievements in each group.

[Assistant] SELECT hidden, COUNT(achievement_id) AS achievement_count, AVG(points) AS average_points, MAX(points) AS maximum_points, MIN(points) AS minimum_points FROM gaming_technology.achievements WHERE points > 0 GROUP BY hidden;

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.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)


[User] List all managers (employees who have other employees reporting to them) along with the count of their direct reports, showing only those with more than 5 reports.

[Assistant] SELECT e.employee_id, e.first_name, e.last_name, COUNT(r.employee_id) as direct_reports_count FROM financial_services.employees e JOIN financial_services.employees r ON e.employee_id = r.manager_id WHERE e.status = 'Active' GROUP BY e.employee_id, e.first_name, e.last_name HAVING COUNT(r.employee_id) > 5 ORDER BY direct_reports_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )


[User] Find all contracts where the deployer address is the same as the contract address, indicating self-deployed contracts, and show their network IDs and deployment timestamps.

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

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


[User] 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] Could you show me a list of posts, including their content, and the total number of comments and likes each post has received?

[Assistant]
SELECT
  p.post_id,
  p.content,
  COUNT(DISTINCT c.comment_id) AS comment_count,
  COUNT(DISTINCT l.like_id) AS like_count
FROM social_media.posts AS p
LEFT JOIN social_media.comments AS c
  ON p.post_id = c.post_id
LEFT JOIN social_media.likes AS l
  ON p.post_id = l.post_id
GROUP BY
  p.post_id,
  p.content;

[User] Please filter these results to include only public posts.

[Assistant]
SELECT
  p.post_id,
  p.content,
  COUNT(DISTINCT c.comment_id) AS comment_count,
  COUNT(DISTINCT l.like_id) AS like_count
FROM social_media.posts AS p
LEFT JOIN social_media.comments AS c
  ON p.post_id = c.post_id
LEFT JOIN social_media.likes AS l
  ON p.post_id = l.post_id
WHERE
  p.visibility = 'public'
GROUP BY
  p.post_id,
  p.content;

[User] Also, only include posts created by verified users.

[Assistant]
SELECT
  p.post_id,
  p.content,
  COUNT(DISTINCT c.comment_id) AS comment_count,
  COUNT(DISTINCT l.like_id) AS like_count
FROM social_media.posts AS p
JOIN social_media.users AS u
  ON p.user_id = u.user_id
LEFT JOIN social_media.comments AS c
  ON p.post_id = c.post_id
LEFT JOIN social_media.likes AS l
  ON p.post_id = l.post_id
WHERE
  p.visibility = 'public' AND u.is_verified = TRUE
GROUP BY
  p.post_id,
  p.content;

[User] Now, only show posts created in the last 90 days.

[Assistant]
SELECT
  p.post_id,
  p.content,
  COUNT(DISTINCT c.comment_id) AS comment_count,
  COUNT(DISTINCT l.like_id) AS like_count
FROM social_media.posts AS p
JOIN social_media.users AS u
  ON p.user_id = u.user_id
LEFT JOIN social_media.comments AS c
  ON p.post_id = c.post_id
LEFT JOIN social_media.likes AS l
  ON p.post_id = l.post_id
WHERE
  p.visibility = 'public' AND u.is_verified = TRUE AND p.created_at >= CURRENT_DATE - INTERVAL '90 days'
GROUP BY
  p.post_id,
  p.content;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id character varying(64) NOT NULL, follower_user_id character varying(64) NOT NULL, following_user_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (follow_id), CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )


[User] Show me all home loans (loan_id, principal_amount, interest_rate) where the current principal balance is more than 75% of the original principal amount, along with the account_id and employee details (first_name, last_name) of the employee who processed the loan application.

[Assistant] SELECT l.loan_id, l.principal_amount, l.interest_rate, l.account_id, e.first_name, e.last_name FROM financial_services.loans l JOIN financial_services.employees e ON l.account_id = e.employee_id WHERE l.loan_type = 'Home' AND l.current_principal_balance > (l.principal_amount * 0.75)

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.transactions ( transaction_id.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees ( employee_id.text, first_name.text, last_name.text, job_title.text, department.text, branch_id.text, email.text, phone_extension.text, hire_date.date, termination_date.date, manager_id.text, status.text )
CREATE TABLE financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )


[User] What is the history of incidents or accidents that occurred on platform 5 at station GHI?

[Assistant] I'm sorry, but I can't provide information about the history of incidents or accidents on platform 5 at station GHI. My data is limited to the structural and operational details of the platforms, such as platform ID, station ID, and status. For incident history, you may need to consult a different database or contact the relevant authorities.

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


[User] What is the count of securities for each security_type in the 'Technology' sector?

[Assistant] SELECT security_type, COUNT(*) as security_count FROM financial_services.securities WHERE sector = 'Technology' GROUP BY security_type;

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


[User] Show the IDs and registration dates of all verified citizens who could be eligible for at least one active service. Display the citizen ID and registration date.

[Assistant]
SELECT DISTINCT c.citizen_id, c.registration_date
FROM government_services.citizens c
JOIN government_services.services s ON s.is_active = true
WHERE c.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 government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )


[User] How many participants are there in each conversation? Return conversation_id and participant_count.

[Assistant]
SELECT conversation_id,
       COUNT(*) AS participant_count
FROM social_media.conversation_participants
GROUP BY conversation_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )


[User] Please show me all locations that do not have a state or province recorded. Include the location name, city, and country.

[Assistant]
SELECT name, city, country
FROM transportation.locations
WHERE state_province IS NULL OR state_province = '';

[User] For these locations, also include their location_id and type.

[Assistant]
SELECT location_id, name, type, city, country
FROM transportation.locations
WHERE state_province IS NULL OR state_province = '';

[User] Could you additionally list any routes for which these locations are either the origin or the destination? Show the location name, route number, and specify if the location is origin or destination.

[Assistant]
SELECT l.name, r.route_number,
  CASE
    WHEN r.origin_location_id = l.location_id THEN 'origin'
    WHEN r.destination_location_id = l.location_id THEN 'destination'
  END AS role
FROM transportation.locations l
JOIN transportation.routes r
  ON r.origin_location_id = l.location_id OR r.destination_location_id = l.location_id
WHERE l.state_province IS NULL OR l.state_province = '';

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.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )


[User] Show a list of all wallet addresses along with the user_id who owns them, sorted by the wallet creation time.

[Assistant] SELECT user_id, address FROM web3.wallets ORDER BY created_at;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)


[User] List the first and last names of employees and the full name of the citizens for whom they have scheduled appointments.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T3.first_name ,  T3.last_name FROM government_services.employees AS T1 JOIN government_services.appointments AS T2 ON T1.employee_id  =  T2.employee_id JOIN government_services.citizens AS T3 ON T2.citizen_id  =  T3.citizen_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 PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text 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 PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, 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.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


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

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

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


[User] I need a list of claim_ids that have at least one document of type 'Photo' and at least one of type 'Invoice'.

[Assistant]
SELECT DISTINCT cd.claim_id
FROM insurance.claim_documents cd
WHERE cd.document_type IN ('Photo', 'Invoice');

[User] It returns claim_ids that have either a Photo or an Invoice but not necessarily both. I need only those with both types.

[Assistant]
SELECT cd.claim_id
FROM insurance.claim_documents cd
WHERE cd.document_type IN ('Photo', 'Invoice')
GROUP BY cd.claim_id
HAVING COUNT(DISTINCT cd.document_type) = 2;

[User] Actually, I only want those documents uploaded in 2024.

[Assistant]
SELECT cd.claim_id
FROM insurance.claim_documents cd
WHERE cd.document_type IN ('Photo', 'Invoice')
  AND cd.uploaded_at >= '2024-01-01'
GROUP BY cd.claim_id
HAVING COUNT(DISTINCT cd.document_type) = 2;

[User] Also, I'd like to see the policy_number and incident_date for these claims.

[Assistant]
SELECT c.claim_id, p.policy_number, c.incident_date
FROM (
  SELECT cd.claim_id
  FROM insurance.claim_documents cd
  WHERE cd.document_type IN ('Photo', 'Invoice')
    AND cd.uploaded_at >= '2024-01-01'
  GROUP BY cd.claim_id
  HAVING COUNT(DISTINCT cd.document_type) = 2
) AS filtered
JOIN insurance.claims c ON filtered.claim_id = c.claim_id
JOIN insurance.policies p ON c.policy_id = p.policy_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 insurance.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
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.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.agents (
    agent_id character varying(64) NOT NULL, -- unique identifier for the agent
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    agency_name character varying(150),
    license_number character varying(100) NOT NULL UNIQUE, -- state insurance license number
    license_state character varying(50) NOT NULL,
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(30),
    hire_date date,
    termination_date date,
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Terminated, On Leave
    commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, -- percentage commission
    manager_id character varying(64), -- identifier for the agent's manager (FK to agents or employees)
    PRIMARY KEY (agent_id)
)
CREATE TABLE insurance.claim_documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document
    claim_id character varying(64) NOT NULL, -- identifier of the claim this document relates to (FK to claims)
    document_type character varying(50) NOT NULL, -- e.g., Police Report, Photo, Invoice, Medical Bill
    file_name character varying(255) NOT NULL, -- original name of the uploaded file
    file_path character varying(512) NOT NULL, -- storage path (e.g., S3 URL, network path)
    file_size_bytes integer, -- size of the file in bytes
    mime_type character varying(100), -- MIME type of the file (e.g., 'image/jpeg', 'application/pdf')
    uploaded_by character varying(64), -- identifier of the user/system who uploaded (FK to users/customers)
    uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- time of upload
    description text, -- optional description of the document
    PRIMARY KEY (document_id)
)
CREATE TABLE insurance.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)