[User] Show me all time entries, including the case name they are associated with.

[Assistant] SELECT T1.*, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id

[User] Only show me time entries for lawyer with ID 'lawyer_789'.

[Assistant] SELECT T1.*, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T1.lawyer_id = 'lawyer_789'

[User] Actually, I only want entries for the date '2024-07-30', and just show the entry description, hours spent, and case name.

[Assistant] SELECT T1.description, T1.hours_spent, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T1.lawyer_id = 'lawyer_789' AND T1.date_worked = '2024-07-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 legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)


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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] List all ERC20 tokens from the sui_coins_metadata table where the decimals are 18, including their names and symbols.

[Assistant] SELECT name, symbol FROM sui_coins_metadata WHERE decimals = 18;

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

[Assistant] SELECT scm.name, scm.symbol, tpl.price FROM sui_coins_metadata scm JOIN token_prices_latest tpl ON scm.coin_type = tpl.address WHERE scm.decimals = 18;

[User] I think there's an error in your join condition - it should be on coin_type not address. Also, can you filter to only show tokens with price greater than $1?

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


[User] For each guest, list reservation_id, guest_id, check_in_date, and the next reservation_id and its check_in_date.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     );

[User] Only include guests who have at least two reservations.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     )
WHERE r1.guest_id IN (
  SELECT guest_id
  FROM reservations
  GROUP BY guest_id
  HAVING COUNT(*) >= 2
);

[User] Also, only show next reservations that occur within 30 days of the current reservation.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     )
   AND r2.check_in_date <= r1.check_in_date + INTERVAL '30 days'
WHERE r1.guest_id IN (
  SELECT guest_id
  FROM reservations
  GROUP BY guest_id
  HAVING COUNT(*) >= 2
);

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


[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] List all room types with their type name, base rate, and the name of the property they belong to.

[Assistant]
SELECT rt.room_type_id, rt.type_name, rt.base_rate, p.property_name
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_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 hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)


[User] List all vehicles and their last maintenance service date along with the odometer reading, including only those that have not had a fuel refill in the past 30 days.

[Assistant]
SELECT m.vehicle_id,
       m.last_service_date,
       m.last_odometer
FROM (
  SELECT l.vehicle_id,
         MAX(l.service_date) AS last_service_date,
         (SELECT odometer_reading
          FROM transportation.maintenance_logs
          WHERE vehicle_id = l.vehicle_id
          ORDER BY service_date DESC
          LIMIT 1) AS last_odometer
  FROM transportation.maintenance_logs l
  GROUP BY l.vehicle_id
) AS m
LEFT JOIN (
  SELECT fl.vehicle_id,
         MAX(fl.log_timestamp) AS last_fuel_date
  FROM transportation.fuel_logs fl
  GROUP BY fl.vehicle_id
) AS f ON m.vehicle_id = f.vehicle_id
WHERE COALESCE(f.last_fuel_date, '1900-01-01'::timestamp) < NOW() - INTERVAL '30 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 transportation.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
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.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.fuel_logs ( fuel_log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, trip_id character varying(64), log_timestamp timestamp with time zone NOT NULL, fuel_type character varying(32) NOT NULL, quantity numeric(10, 3) NOT NULL, unit character varying(16) NOT NULL, cost_per_unit numeric(8, 4), total_cost numeric(10, 2) NOT NULL, odometer_reading integer, location_id character varying(64), PRIMARY KEY (fuel_log_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )


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

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

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


[User] Show me all insurance plans that cover more than 10 patients as their primary insurance, along with the provider name and contact information.

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.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.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.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions (
    prescription_id character varying(64) NOT NULL, -- unique identifier for the prescription
    record_id character varying(64) NOT NULL, -- FK linking to the medical record where it was prescribed
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to prescribing doctor
    medication_id character varying(64) NOT NULL, -- FK to medications table
    dosage character varying(100) NOT NULL, -- e.g., '100mg', '1 tablet'
    frequency character varying(100) NOT NULL, -- e.g., 'Once daily', 'Twice a day with meals'
    route character varying(50), -- e.g., 'Oral', 'Topical', 'Intravenous'
    start_date date NOT NULL, -- date prescription begins
    end_date date, -- date prescription ends (if applicable)
    quantity_dispensed numeric(10,2), -- amount dispensed (e.g., number of tablets)
    refills_allowed integer NOT NULL DEFAULT 0, -- number of allowed refills
    prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (prescription_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] Calculate the monthly total quantity of fuel consumed and the average cost_per_unit for each fuel_type in 2023.

[Assistant]
SELECT date_trunc('month', log_timestamp) AS month,
       fuel_type,
       SUM(quantity)      AS total_quantity,
       AVG(cost_per_unit) AS avg_cost_per_unit
FROM transportation.fuel_logs
WHERE log_timestamp >= '2023-01-01'
  AND log_timestamp <  '2024-01-01'
GROUP BY 1, fuel_type
ORDER BY 1, fuel_type;

[User] Now limit the results to fuel types where the total_quantity exceeds 1000 units in that month.

[Assistant]
SELECT month,
       fuel_type,
       total_quantity,
       avg_cost_per_unit
FROM (
  SELECT date_trunc('month', log_timestamp) AS month,
         fuel_type,
         SUM(quantity)      AS total_quantity,
         AVG(cost_per_unit) AS avg_cost_per_unit
  FROM transportation.fuel_logs
  WHERE log_timestamp >= '2023-01-01'
    AND log_timestamp <  '2024-01-01'
  GROUP BY 1, fuel_type
) sub
WHERE total_quantity > 1000
ORDER BY month, fuel_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 transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )


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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )


[User] Show projects that raised funds in 2023 along with their token symbols and current prices from token_basic_info.

[Assistant]
SELECT pfr.project_name,
       pfr.rounds_name,
       pfr.investment_value,
       tbi.token_symbol,
       tbi.price
FROM project_fundraising_record pfr
JOIN token_basic_info tbi
  ON pfr.project_name = tbi.token_name
WHERE pfr.investment_date LIKE '2023%';

[User] Include the 24h DEX trading volume for each token by joining with token_dexpool_info.

[Assistant]
SELECT pfr.project_name,
       pfr.rounds_name,
       pfr.investment_value,
       tbi.token_symbol,
       tbi.price,
       tdp.volume_24h
FROM project_fundraising_record pfr
JOIN token_basic_info tbi
  ON pfr.project_name = tbi.token_name
JOIN token_dexpool_info tdp
  ON tbi.token_symbol = tdp.token_symbol
     AND tbi.chain = tdp.chain
WHERE pfr.investment_date LIKE '2023%';

[User] Limit to projects with investment_value greater than 1000000.

[Assistant]
SELECT pfr.project_name,
       pfr.rounds_name,
       pfr.investment_value,
       tbi.token_symbol,
       tbi.price,
       tdp.volume_24h
FROM project_fundraising_record pfr
JOIN token_basic_info tbi
  ON pfr.project_name = tbi.token_name
JOIN token_dexpool_info tdp
  ON tbi.token_symbol = tdp.token_symbol
     AND tbi.chain = tdp.chain
WHERE pfr.investment_date LIKE '2023%'
  AND pfr.investment_value > 1000000;

[User] Order the results by investment_value descending and show top 10.

[Assistant]
SELECT pfr.project_name,
       pfr.rounds_name,
       pfr.investment_value,
       tbi.token_symbol,
       tbi.price,
       tdp.volume_24h
FROM project_fundraising_record pfr
JOIN token_basic_info tbi
  ON pfr.project_name = tbi.token_name
JOIN token_dexpool_info tdp
  ON tbi.token_symbol = tdp.token_symbol
     AND tbi.chain = tdp.chain
WHERE pfr.investment_date LIKE '2023%'
  AND pfr.investment_value > 1000000
ORDER BY pfr.investment_value DESC
LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id text, project_id text, project_name text, rounds_name text, investment_value numeric, investment_date text, introduction text, valuation numeric )
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 token_dexpool_info ( pair_address text, token_name text, token_symbol text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_6h numeric, price_change_percentage_24h numeric, makers_24h numeric, volume_24h numeric, liquidity numeric, market_cap numeric, trend_rank numeric )
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)


[User] Show the total number of policies in each status.

[Assistant] SELECT status, COUNT(*) FROM insurance.policies GROUP BY status

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.policies (
    policy_id 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.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 )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )


[User] Count the total number of chronic diagnoses for each code_type.

[Assistant]
SELECT
  code_type,
  COUNT(*) AS chronic_diagnosis_count
FROM healthcare.diagnoses
WHERE is_chronic = TRUE
GROUP BY code_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 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 )


[User] List all pairs of wallets that were created within 10 minutes of each other, showing both wallet IDs, the user_id, and both creation timestamps.

[Assistant]
SELECT
  w1.wallet_id AS wallet1_id,
  w2.wallet_id AS wallet2_id,
  w1.user_id,
  w1.created_at AS created_at1,
  w2.created_at AS created_at2
FROM web3.wallets w1
JOIN web3.wallets w2
  ON w1.user_id = w2.user_id
  AND w1.wallet_id < w2.wallet_id
  AND ABS(EXTRACT(EPOCH FROM (w1.created_at - w2.created_at))) <= 600;

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 text, user_id text, address text, private_key text, created_at timestamp )


[User] Show me the top 5 smart money addresses by profit on the Ethereum chain, along with their most profitable token and ROI, but only include addresses with a realized profit ratio above 70%.

[Assistant] SELECT address, most_profit_token, roi FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 70 ORDER BY profit DESC LIMIT 5;

[User] Can you also include their rank and filter to only show addresses with ROI greater than 50%?

[Assistant] SELECT address, most_profit_token, roi, rank FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 70 AND roi > 50 ORDER BY profit DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )


[User] Find the contract address and name for all NFT collections listed on the 'Ethereum' blockchain.

[Assistant] SELECT contract_address, name FROM nft_collections WHERE blockchain = 'Ethereum'

[User] For these collections, can you show the count of unique wallet addresses holding NFTs in each collection by joining with nft_holders?

[Assistant] SELECT T1.contract_address, T1.name, COUNT(DISTINCT T2.wallet_address) AS unique_holder_count FROM nft_collections AS T1 JOIN nft_holders AS T2 ON T1.contract_address = T2.contract_address WHERE T1.blockchain = 'Ethereum' GROUP BY T1.contract_address, T1.name

[User] Please filter the results to only include collections that have more than 100 unique holders.

[Assistant] SELECT T1.contract_address, T1.name, COUNT(DISTINCT T2.wallet_address) AS unique_holder_count FROM nft_collections AS T1 JOIN nft_holders AS T2 ON T1.contract_address = T2.contract_address WHERE T1.blockchain = 'Ethereum' GROUP BY T1.contract_address, T1.name HAVING COUNT(DISTINCT T2.wallet_address) > 100

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )


[User] Show me all rooms that were last cleaned more than 3 days ago, along with their room numbers and cleaning status.

[Assistant] SELECT room_number, current_condition FROM hospitality_technology.rooms WHERE last_cleaned_at < CURRENT_DATE - INTERVAL '3 days';

[User] Now, join this with another query to show only rooms that are currently 'Available' and have a 'Jacuzzi' in their features.

[Assistant] SELECT r.room_number, r.current_condition FROM hospitality_technology.rooms r WHERE r.last_cleaned_at < CURRENT_DATE - INTERVAL '3 days' AND r.status = 'available' AND r.features LIKE '%Jacuzzi%';

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

[Assistant] SELECT r.room_number, r.current_condition, r.floor FROM hospitality_technology.rooms r WHERE r.last_cleaned_at < CURRENT_DATE - INTERVAL '3 days' AND r.status = 'available' AND r.features LIKE '%Jacuzzi%';

[User] Actually, I need to see the results ordered by floor in descending order, then by room_number.

[Assistant] SELECT r.room_number, r.current_condition, r.floor FROM hospitality_technology.rooms r WHERE r.last_cleaned_at < CURRENT_DATE - INTERVAL '3 days' AND r.status = 'available' AND r.features LIKE '%Jacuzzi%' ORDER BY r.floor DESC, r.room_number;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )


[User] What is the detailed repair history of the equipment used by the staff with staff_id 'STAFF123' during maintenance tasks?

[Assistant] I'm sorry, but I can't provide information on the detailed repair history of equipment used by staff members. The data in the maintenance_records table only includes information about maintenance tasks, such as record_id, asset_id, maintenance type, and staff_id, but does not cover equipment repair histories.

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


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

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

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

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

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

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

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


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

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

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

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

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

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

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

[Assistant] SELECT creator_address, COUNT(*) AS large_code_contract_count FROM blockchain.smart_contracts WHERE LENGTH(code) > 1000 GROUP BY creator_address HAVING COUNT(*) > 3 ORDER BY large_code_contract_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 blockchain.smart_contracts ( contract_id.text, creator_address.text, code.text, timestamp.timestamp )


[User] For each group chat, list its ID, name, creation time, and the creation time of the next group chat created after it, ordered by creation time.

[Assistant] SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ORDER BY created_at;

[User] Only show pairs where the next group chat was created within 48 hours of the current one, and also include the time difference in hours.

[Assistant] WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 ORDER BY created_at;

[User] Further refine: Only include group chats whose names contain 'Discuss'.

[Assistant] WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 AND group_name LIKE '%Discuss%' 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 social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )


[User] Find all pairs of transactions where both transactions have the same nonce and from_address, but different transaction_id. Show both transaction IDs, the shared from_address, shared nonce, and their block numbers.

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

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


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

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

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


[User] 我想查看所有检查记录中检查员的ID和检查结果，同时统计每个检查员的检查次数。

[Assistant]
db.inspections.aggregate([
  {
    $group: {
      _id: '$inspector_employee_id',
      total_inspections: { $count: {} },
      results: { $push: '$result' }
    }
  },
  {
    $project: {
      inspector_employee_id: '$_id',
      total_inspections: 1,
      results: 1,
      _id: 0
    }
  }
]);

[User] 如果我想只统计检查结果为'Fail'的次数，应该怎么改？

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      result: 'Fail'
    }
  },
  {
    $group: {
      _id: '$inspector_employee_id',
      failed_inspections: { $count: {} }
    }
  },
  {
    $project: {
      inspector_employee_id: '$_id',
      failed_inspections: 1,
      _id: 0
    }
  }
]);

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Collection 'inspections'. Document structure: { _id: <ObjectId (or inspection_id)>, inspection_id: String, build_id: String (reference), component_id: String (reference, optional), step_id: String (reference, optional), inspection_type: String, inspector_employee_id: String (reference), inspection_timestamp: ISODate, result: String, remarks: String }. Required: inspection_id, build_id, inspection_type, inspector_employee_id, inspection_timestamp, result. Indexes on build_id, component_id, step_id, inspector_employee_id, result.


[User] I need the average capacity of vehicles for each fuel_type.

[Assistant]
SELECT fuel_type,
       AVG(capacity) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type;

[User] Only include fuel types where the vehicle count is at least 10.

[Assistant]
SELECT fuel_type,
       AVG(capacity) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 10;

[User] Also show the number of vehicles for each of these fuel types.

[Assistant]
SELECT fuel_type,
       COUNT(*) AS vehicle_count,
       AVG(capacity) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 10;

[User] Please round avg_capacity to one decimal place.

[Assistant]
SELECT fuel_type,
       COUNT(*) AS vehicle_count,
       ROUND(AVG(capacity)::numeric, 1) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )


[User] List all 'exists'-status coins from sui_coins_metadata with more than 8 decimals, showing coin_type, symbol, name, and decimals.

[Assistant] SELECT coin_type, symbol, name, decimals FROM sui_coins_metadata WHERE status = 'exists' AND decimals > 8;

[User] Add the total balance for each coin_type by joining with sui_coins.

[Assistant] SELECT scm.coin_type, scm.symbol, scm.name, scm.decimals, SUM(sc.balance) AS total_balance FROM sui_coins_metadata scm JOIN sui_coins sc ON scm.coin_type = sc.coin_type WHERE scm.status = 'exists' AND scm.decimals > 8 GROUP BY scm.coin_type, scm.symbol, scm.name, scm.decimals;

[User] Can you also include only coins where the total_balance is greater than 1,000,000 and show the description?

[Assistant] SELECT scm.coin_type, scm.symbol, scm.name, scm.decimals, scm.description, SUM(sc.balance) AS total_balance FROM sui_coins_metadata scm JOIN sui_coins sc ON scm.coin_type = sc.coin_type WHERE scm.status = 'exists' AND scm.decimals > 8 GROUP BY scm.coin_type, scm.symbol, scm.name, scm.decimals, scm.description HAVING SUM(sc.balance) > 1000000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk integer )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


[User] List all users whose password hash contains the substring 'abc'.

[Assistant] SELECT user_id, username, password_hash FROM blockchain.users WHERE password_hash LIKE '%abc%';

[User] Also include their email address.

[Assistant] SELECT user_id, username, password_hash, email FROM blockchain.users WHERE password_hash LIKE '%abc%';

[User] Filter to only show users whose username does *not* contain 'test'.

[Assistant] SELECT user_id, username, password_hash, email FROM blockchain.users WHERE password_hash LIKE '%abc%' AND username NOT LIKE '%test%';

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


[User] How many pairs of distinct locations are there that share the same state or province but are in different cities?

[Assistant] SELECT COUNT(*) FROM transportation.locations AS l1 JOIN transportation.locations AS l2 ON l1.state_province = l2.state_province AND l1.location_id < l2.location_id WHERE l1.city != l2.city;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )


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

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

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

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

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


[User] List the post_id and the count of distinct hashtags associated with each post that has at least 3 hashtags.

[Assistant] SELECT ph.post_id, COUNT(DISTINCT ph.hashtag_id) AS hashtag_count FROM social_media.post_hashtags ph GROUP BY ph.post_id HAVING COUNT(DISTINCT ph.hashtag_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 social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)


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

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

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


[User] List all ERC20 tokens where the price is between $1 and $10, including their names, symbols, and contract addresses.

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.contract_address WHERE tm.is_erc20 = 1 AND tpl.price BETWEEN 1 AND 10;

[User] I think there's an error in your query - the token_prices_latest table isn't in the schema. Can you modify it to use the token_balances table instead?

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address FROM token_metas tm JOIN token_balances tb ON tm.contract_address = tb.wallet_address WHERE tm.is_erc20 = 1 AND CAST(tb.amount AS decimal) BETWEEN 1 AND 10;

[User] That doesn't seem right either. Let's just get the basic ERC20 token information without price filtering for now.

[Assistant] SELECT name, symbol, contract_address FROM token_metas WHERE is_erc20 = 1 LIMIT 100;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


[User] How many documents are there for each document_type? Show document_type and count ordered by the count in descending order.

[Assistant]
SELECT document_type,
       COUNT(*) AS count
FROM legal_services.documents
GROUP BY document_type
ORDER BY 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 legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )


[User] Calculate the total quantity traded for each asset, showing the asset name and symbol.

[Assistant] SELECT T1.name, T1.symbol, SUM(T2.quantity) FROM trading_platform.assets AS T1 JOIN trading_platform.trades AS T2 ON T1.asset_id = T2.asset_id GROUP BY 1, 2;

[User] Only show assets where the total quantity traded is more than 5000.

[Assistant] SELECT T1.name, T1.symbol, SUM(T2.quantity) FROM trading_platform.assets AS T1 JOIN trading_platform.trades AS T2 ON T1.asset_id = T2.asset_id GROUP BY 1, 2 HAVING SUM(T2.quantity) > 5000;

[User] Actually, instead of total quantity, show the average trade price for each asset.

[Assistant] SELECT T1.name, T1.symbol, AVG(T2.price) FROM trading_platform.assets AS T1 JOIN trading_platform.trades AS T2 ON T1.asset_id = T2.asset_id GROUP BY 1, 2;

[User] Sort those assets by the average price in descending order.

[Assistant] SELECT T1.name, T1.symbol, AVG(T2.price) FROM trading_platform.assets AS T1 JOIN trading_platform.trades AS T2 ON T1.asset_id = T2.asset_id GROUP BY 1, 2 ORDER BY AVG(T2.price) DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] How many agencies exist for each jurisdiction level?

[Assistant] SELECT jurisdiction_level, COUNT(*) AS agency_count FROM government_services.agencies GROUP BY jurisdiction_level;

[User] Only show the jurisdiction levels with more than 5 agencies.

[Assistant] SELECT jurisdiction_level, COUNT(*) AS agency_count FROM government_services.agencies GROUP BY jurisdiction_level HAVING COUNT(*) > 5;

[User] Sort the results by the number of agencies in descending order.

[Assistant] SELECT jurisdiction_level, COUNT(*) AS agency_count FROM government_services.agencies GROUP BY jurisdiction_level HAVING COUNT(*) > 5 ORDER BY agency_count DESC;

[User] Also, only include agencies established before January 1, 2020, in the count.

[Assistant] SELECT jurisdiction_level, COUNT(*) AS agency_count FROM government_services.agencies WHERE established_date < '2020-01-01' GROUP BY jurisdiction_level HAVING COUNT(*) > 5 ORDER BY agency_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 government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )


[User] How many customers are there for each status?

[Assistant] SELECT status, COUNT(*) FROM financial_services.customers GROUP BY status

[User] Only show statuses where the count is greater than 50.

[Assistant] SELECT status, COUNT(*) FROM financial_services.customers GROUP BY status HAVING COUNT(*) > 50

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

[Assistant] SELECT status, COUNT(*) FROM financial_services.customers GROUP BY status HAVING COUNT(*) > 50 ORDER BY 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.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )


[User] Show me all claims along with the related customer's full name and the policy number for incidents that occurred in 2024.

[Assistant]
SELECT c.claim_id, c.incident_date, c.description, cu.first_name || ' ' || cu.last_name AS customer_full_name, p.policy_number
FROM insurance.claims c
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
JOIN insurance.policies p ON c.policy_id = p.policy_id
WHERE EXTRACT(YEAR FROM c.incident_date) = 2024;

[User] Include the settlement amount and status of each claim in the results.

[Assistant]
SELECT c.claim_id, c.incident_date, c.description, cu.first_name || ' ' || cu.last_name AS customer_full_name, p.policy_number, c.settlement_amount, c.status
FROM insurance.claims c
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
JOIN insurance.policies p ON c.policy_id = p.policy_id
WHERE EXTRACT(YEAR FROM c.incident_date) = 2024;

[User] Actually, please filter only those claims with a settlement_amount that is not null.

[Assistant]
SELECT c.claim_id, c.incident_date, c.description, cu.first_name || ' ' || cu.last_name AS customer_full_name, p.policy_number, c.settlement_amount, c.status
FROM insurance.claims c
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
JOIN insurance.policies p ON c.policy_id = p.policy_id
WHERE EXTRACT(YEAR FROM c.incident_date) = 2024
  AND c.settlement_amount IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id.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 )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )