[User] Show smart money addresses with an ROI greater than 3 and a realized ratio greater than 0.7. Display the address, chain, ROI, realized ratio, and most profitable token.

[Assistant] SELECT address, chain, roi, realized_ratio, most_profit_token FROM smart_money_profit WHERE roi > 3 AND realized_ratio > 0.7;

[User] For these tokens (`most_profit_token` from the previous result), what is the total USD value held by CEXes across all chains? Show the token symbol and the total CEX USD value.

[Assistant] WITH HighlyPerformingTokens AS (SELECT DISTINCT most_profit_token FROM smart_money_profit WHERE roi > 3 AND realized_ratio > 0.7 AND most_profit_token IS NOT NULL) SELECT c.token_symbol, SUM(c.usd_value) AS total_cex_usd_value FROM cex_token_balance c JOIN HighlyPerformingTokens h ON c.token_symbol = h.most_profit_token WHERE c.usd_value IS NOT NULL GROUP BY c.token_symbol ORDER BY total_cex_usd_value DESC;

[User] Filter the previous results to only include tokens where the `average_smart_money_roi` is greater than 10 (1000%) and the `average_smart_money_realized_ratio` is greater than 0.8.

[Assistant] WITH CexHeldTokens AS (SELECT DISTINCT token_symbol FROM cex_token_balance WHERE token_symbol IS NOT NULL AND token_symbol != ''), TokenPerformance AS (SELECT s.most_profit_token AS token_symbol, AVG(s.roi) AS average_smart_money_roi, AVG(s.realized_ratio) AS average_smart_money_realized_ratio FROM smart_money_profit s JOIN CexHeldTokens c ON s.most_profit_token = c.token_symbol WHERE s.roi IS NOT NULL AND s.realized_ratio IS NOT NULL GROUP BY s.most_profit_token) SELECT token_symbol, average_smart_money_roi, average_smart_money_realized_ratio FROM TokenPerformance WHERE average_smart_money_roi > 10 AND average_smart_money_realized_ratio > 0.8 ORDER BY average_smart_money_roi DESC;

[User] For these filtered tokens, add the total USD value held by CEXes (`usd_value` from `cex_token_balance`) to the results. Show token symbol, total CEX USD value, average ROI, and average realized ratio.

[Assistant] WITH CexHeldTokens AS (SELECT DISTINCT token_symbol FROM cex_token_balance WHERE token_symbol IS NOT NULL AND token_symbol != ''), TokenPerformance AS (SELECT s.most_profit_token AS token_symbol, AVG(s.roi) AS average_smart_money_roi, AVG(s.realized_ratio) AS average_smart_money_realized_ratio FROM smart_money_profit s JOIN CexHeldTokens c ON s.most_profit_token = c.token_symbol WHERE s.roi IS NOT NULL AND s.realized_ratio IS NOT NULL GROUP BY s.most_profit_token), FilteredPerformance AS (SELECT token_symbol, average_smart_money_roi, average_smart_money_realized_ratio FROM TokenPerformance WHERE average_smart_money_roi > 10 AND average_smart_money_realized_ratio > 0.8) SELECT fp.token_symbol, SUM(c.usd_value) AS total_cex_usd_value, fp.average_smart_money_roi, fp.average_smart_money_realized_ratio FROM FilteredPerformance fp JOIN cex_token_balance c ON fp.token_symbol = c.token_symbol WHERE c.usd_value IS NOT NULL GROUP BY fp.token_symbol, fp.average_smart_money_roi, fp.average_smart_money_realized_ratio ORDER BY fp.average_smart_money_roi 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 cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

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] Show all beneficiaries who were added in 2024 for any policy. List their beneficiary_id, first and last name, relationship, and the policy_id.

[Assistant]
SELECT beneficiary_id, first_name, last_name, relationship, policy_id
FROM insurance.policy_beneficiaries
WHERE EXTRACT(YEAR FROM added_at) = 2024;

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, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, ssn_hash character varying(128), 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, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, status character varying(20) NOT NULL DEFAULT 'Active', 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.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )


[User] List all claim documents that are police reports and were uploaded in the last 30 days, along with their file sizes.

[Assistant] SELECT cd.document_id, cd.claim_id, cd.file_size_bytes FROM insurance.claim_documents cd WHERE cd.document_type = 'Police Report' AND cd.uploaded_at >= CURRENT_DATE - INTERVAL '30 days';

[User] Now include only documents that are larger than 1MB and sort them by file size in descending order.

[Assistant] SELECT cd.document_id, cd.claim_id, cd.file_size_bytes FROM insurance.claim_documents cd WHERE cd.document_type = 'Police Report' AND cd.uploaded_at >= CURRENT_DATE - INTERVAL '30 days' AND cd.file_size_bytes > 1000000 ORDER BY cd.file_size_bytes DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies ( policy_id 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.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )


[User] List all patients who have both a primary insurance plan and at least one completed appointment, including their insurance provider names.

[Assistant] SELECT p.first_name, p.last_name, i.insurance_provider FROM healthcare.patients p JOIN healthcare.insurance_plans i ON p.primary_insurance_id = i.plan_id JOIN healthcare.appointments a ON p.patient_id = a.patient_id WHERE a.status = 'Completed' GROUP BY p.patient_id, i.insurance_provider;

[User] Actually, I only need patients whose appointments were completed in the last 3 months.

[Assistant] SELECT p.first_name, p.last_name, i.insurance_provider FROM healthcare.patients p JOIN healthcare.insurance_plans i ON p.primary_insurance_id = i.plan_id JOIN healthcare.appointments a ON p.patient_id = a.patient_id WHERE a.status = 'Completed' AND a.appointment_time >= NOW() - INTERVAL '3 months' GROUP BY p.patient_id, i.insurance_provider;

[User] Can you also include the count of completed appointments for each patient?

[Assistant] SELECT p.first_name, p.last_name, i.insurance_provider, COUNT(a.appointment_id) AS completed_appointments FROM healthcare.patients p JOIN healthcare.insurance_plans i ON p.primary_insurance_id = i.plan_id JOIN healthcare.appointments a ON p.patient_id = a.patient_id WHERE a.status = 'Completed' AND a.appointment_time >= NOW() - INTERVAL '3 months' GROUP BY p.patient_id, i.insurance_provider;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)


[User] Find all documents that are associated with an application but have a verification status of 'Pending'. Show the document ID, document type, and application ID.

[Assistant] SELECT document_id, document_type, application_id FROM government_services.documents WHERE application_id IS NOT NULL AND verification_status = 'Pending';

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


[User] What is the average age of verified citizens as of today?

[Assistant]
SELECT AVG(EXTRACT(YEAR FROM AGE(NOW(), date_of_birth))) AS average_age_verified
FROM government_services.citizens
WHERE is_verified = TRUE;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] List the application reference numbers, the corresponding message subjects, and the sent dates for notifications related to each application.

[Assistant]
SELECT a.reference_number, n.message_subject, n.sent_at
FROM government_services.applications a
JOIN government_services.notifications n ON a.application_id = n.application_id;

[User] Only include applications that have a status of 'Approved'.

[Assistant]
SELECT a.reference_number, n.message_subject, n.sent_at
FROM government_services.applications a
JOIN government_services.notifications n ON a.application_id = n.application_id
WHERE a.status = 'Approved';

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.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] List the first name and last name of the driver and the license plate of the vehicle used for each trip.

[Assistant] SELECT T1.first_name , T1.last_name , T3.license_plate FROM transportation.drivers AS T1 JOIN transportation.trips AS T2 ON T1.driver_id = T2.driver_id JOIN transportation.vehicles AS T3 ON T2.vehicle_id = T3.vehicle_id

[User] Now, restrict this list to only include trips where the vehicle's fuel type is 'Electric'.

[Assistant] SELECT T1.first_name , T1.last_name , T3.license_plate FROM transportation.drivers AS T1 JOIN transportation.trips AS T2 ON T1.driver_id = T2.driver_id JOIN transportation.vehicles AS T3 ON T2.vehicle_id = T3.vehicle_id WHERE T3.fuel_type = 'Electric'

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 )
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
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 )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )


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

[Assistant] SELECT t1.firm_name AS firm1_name, t2.firm_name AS firm2_name, t1.founded_date FROM legal_services.law_firms AS t1 JOIN legal_services.law_firms AS t2 ON MONTH(t1.founded_date) = MONTH(t2.founded_date) AND DAY(t1.founded_date) = DAY(t2.founded_date) AND t1.firm_id < t2.firm_id WHERE MONTH(t1.founded_date) <> 1 OR DAY(t1.founded_date) <> 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )


[User] List all unique hashtag IDs present in the system.

[Assistant] SELECT DISTINCT hashtag_id FROM social_media.post_hashtags;

[User] And how many users have chosen the 'dark' theme?

[Assistant] SELECT COUNT(*) FROM social_media.user_settings WHERE theme = 'dark';

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.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )


[User] Find pairs of distinct token transfers that occurred in the same transaction and were initiated by the same sender address. List the transaction ID, the common sender address, and both transfer IDs.

[Assistant]
SELECT
  t1.transaction_id,
  t1.from_address,
  t1.transfer_id AS transfer_id_1,
  t2.transfer_id AS transfer_id_2
FROM web3.token_transfers AS t1
JOIN web3.token_transfers AS t2
  ON t1.transaction_id = t2.transaction_id
  AND t1.from_address = t2.from_address
WHERE
  t1.transfer_id < t2.transfer_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)


[User] Show the make, model, and license plate for each vehicle along with the name of the depot it is assigned to.

[Assistant] SELECT v.make, v.model, v.license_plate, d.depot_name FROM transportation.vehicles AS v JOIN transportation.depots AS d ON v.depot_id = d.depot_id;

[User] Restrict the list to only include vehicles whose assigned depot is located in the state of 'Texas'.

[Assistant] SELECT v.make, v.model, v.license_plate, d.depot_name FROM transportation.vehicles AS v JOIN transportation.depots AS d ON v.depot_id = d.depot_id WHERE d.state_province = 'TX';

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


[User] For each insurance product, show its product_id, product_type, and the next product_id created after it in the same product_type, labeled as next_product_id.

[Assistant]
SELECT p1.product_id,
       p1.product_type,
       p2.product_id AS next_product_id
FROM insurance.insurance_products p1
JOIN insurance.insurance_products p2
  ON p1.product_type = p2.product_type
  AND p2.created_at = (
    SELECT MIN(p3.created_at)
    FROM insurance.insurance_products p3
    WHERE p3.product_type = p1.product_type
      AND p3.created_at > p1.created_at
  );

[User] Actually, only include rows where both products are active.

[Assistant]
SELECT p1.product_id,
       p1.product_type,
       p2.product_id AS next_product_id
FROM insurance.insurance_products p1
JOIN insurance.insurance_products p2
  ON p1.product_type = p2.product_type
  AND p2.created_at = (
    SELECT MIN(p3.created_at)
    FROM insurance.insurance_products p3
    WHERE p3.product_type = p1.product_type
      AND p3.created_at > p1.created_at
  )
WHERE p1.is_active = true
  AND p2.is_active = true;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )


[User] Show me all patients who have scheduled appointments with doctors specializing in Cardiology, along with their appointment times and the doctors' full names.

[Assistant] SELECT p.first_name, p.last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name FROM healthcare.patients p JOIN healthcare.appointments a ON p.patient_id = a.patient_id JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id WHERE d.specialty = 'Cardiology' ORDER BY a.appointment_time;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )


[User] Which SUI coins are owned by the address '0xSuperOwner'? Please list the object_id, coin_type, and balance.

[Assistant]
SELECT object_id, coin_type, balance
FROM sui_coins
WHERE owner = '0xSuperOwner';

[User] Add the name and symbol of each coin by joining with the sui_coins_metadata table (assume the metadata table has columns: coin_type, name, symbol).

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

[User] Only include coins with a balance greater than 1,000,000.

[Assistant]
SELECT sc.object_id, sc.coin_type, sc.balance, scm.name, scm.symbol
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.owner = '0xSuperOwner' AND CAST(sc.balance AS DECIMAL) > 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.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 number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
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 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 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_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone (
    address varchar NOT NULL, -- address fields for the functionType  in contract
    table_id varchar NOT NULL, -- table_id fields for the functionType  in contract
    key_bytes varchar NOT NULL, -- key_bytes fields for the functionType  in contract
    key0 varchar NOT NULL, -- key0 fields for the functionType  in contract
    key1 varchar NOT NULL, -- key1 fields for the functionType  in contract
    static_data varchar NOT NULL, -- static_data fields for the functionType  in contract
    encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType  in contract
    dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType  in contract
    is_deleted boolean NOT NULL, -- is_deleted fields for the functionType  in contract
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    log_index bigint NOT NULL  -- Index of the log within the transaction
)
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_avalanche (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(42) NOT NULL, -- Address sending the inscription
    to_address varchar(42) NOT NULL  -- Address receiving the inscription
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 )

[User] List the top 5 tokens by price_change_percentage_7d, showing token_symbol, narrative, and price_change_percentage_7d.

[Assistant]
SELECT token_symbol, narrative, price_change_percentage_7d
FROM token_basic_info
ORDER BY price_change_percentage_7d DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] List all patients who have insurance plans with group numbers, showing their patient IDs and the count of such plans per patient.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id;

[User] Actually, I only need patients who have more than 2 such plans.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;

[User] Can you also include the earliest effective date among these plans for each patient?

[Assistant] SELECT patient_id, COUNT(*) AS plan_count, MIN(effective_date) AS earliest_effective_date FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )

[User] Which agents, along with their managers' full names, are licensed in 'TX' and are currently active?

[Assistant]
SELECT a.agent_id, a.first_name AS agent_first_name, a.last_name AS agent_last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.license_state = 'TX' AND a.status = 'Active';


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

[User] Retrieve all pairs of loans for the same account where both loans are active and have different loan types. Show account_id, loan_id as loan_a, loan_type as type_a, loan_id as loan_b, and loan_type as type_b.

[Assistant]
SELECT a.account_id,
       a.loan_id AS loan_a,
       a.loan_type AS type_a,
       b.loan_id AS loan_b,
       b.loan_type AS type_b
FROM financial_services.loans a
JOIN financial_services.loans b
  ON a.account_id = b.account_id
 AND a.loan_id < b.loan_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
  AND a.loan_type <> b.loan_type;

[User] Actually, only include pairs where loan_a has a higher principal_amount than loan_b.

[Assistant]
SELECT a.account_id,
       a.loan_id AS loan_a,
       a.loan_type AS type_a,
       b.loan_id AS loan_b,
       b.loan_type AS type_b
FROM financial_services.loans a
JOIN financial_services.loans b
  ON a.account_id = b.account_id
 AND a.loan_id < b.loan_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
  AND a.loan_type <> b.loan_type
  AND a.principal_amount > b.principal_amount;

[User] Now restrict to accounts where the total number of active loans is at least 3.

[Assistant]
SELECT a.account_id,
       a.loan_id AS loan_a,
       a.loan_type AS type_a,
       b.loan_id AS loan_b,
       b.loan_type AS type_b
FROM financial_services.loans a
JOIN financial_services.loans b
  ON a.account_id = b.account_id
 AND a.loan_id < b.loan_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
  AND a.loan_type <> b.loan_type
  AND a.principal_amount > b.principal_amount
  AND a.account_id IN (
    SELECT account_id
    FROM financial_services.loans
    WHERE status = 'Active'
    GROUP BY account_id
    HAVING COUNT(*) >= 3
  );

[User] Finally, also include the number of active loans for each account as loan_count.

[Assistant]
WITH active_counts AS (
  SELECT account_id,
         COUNT(*) AS loan_count
  FROM financial_services.loans
  WHERE status = 'Active'
  GROUP BY account_id
)
SELECT a.account_id,
       ac.loan_count,
       a.loan_id AS loan_a,
       a.loan_type AS type_a,
       b.loan_id AS loan_b,
       b.loan_type AS type_b
FROM financial_services.loans a
JOIN financial_services.loans b
  ON a.account_id = b.account_id
 AND a.loan_id < b.loan_id
JOIN active_counts ac
  ON a.account_id = ac.account_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
  AND a.loan_type <> b.loan_type
  AND a.principal_amount > b.principal_amount
  AND ac.loan_count >= 3;


[User] List the product ID and product name of all insurance products created in 2024.

[Assistant]
SELECT product_id, product_name
FROM insurance.insurance_products
WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01';

[User] Can you also include their product type and base premium in the results?

[Assistant]
SELECT product_id, product_name, product_type, base_premium
FROM insurance.insurance_products
WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01';

[User] I only want to see those products with a base premium below 1000.

[Assistant]
SELECT product_id, product_name, product_type, base_premium
FROM insurance.insurance_products
WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01'
  AND base_premium < 1000;

[User] Also, sort the result by product name in ascending order.

[Assistant]
SELECT product_id, product_name, product_type, base_premium
FROM insurance.insurance_products
WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01'
  AND base_premium < 1000
ORDER BY product_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )


[User] Show me the top 5 users with the highest number of wallet addresses.

[Assistant] SELECT user_id, COUNT(*) AS wallet_count FROM blockchain.wallets WHERE user_id IS NOT NULL GROUP BY user_id ORDER BY wallet_count DESC LIMIT 5;

[User] Can you also include the earliest created wallet address for each of these top 5 users?

[Assistant] SELECT w1.user_id, w1.address_id, w1.private_key FROM blockchain.wallets w1 INNER JOIN (SELECT user_id, MIN(wallet_id) AS oldest_wallet_id FROM blockchain.wallets WHERE user_id IS NOT NULL GROUP BY user_id ORDER BY COUNT(*) DESC LIMIT 5) w2 ON w1.user_id = w2.user_id AND w1.wallet_id = w2.oldest_wallet_id;

[User] This query seems incorrect as it's not showing the actual earliest wallet address. Can you modify it to show the wallet_id with the minimum creation timestamp?

[Assistant] SELECT w1.user_id, w1.address_id, w1.private_key FROM blockchain.wallets w1 INNER JOIN (SELECT user_id FROM blockchain.wallets WHERE user_id IS NOT NULL GROUP BY user_id ORDER BY COUNT(*) DESC LIMIT 5) w2 ON w1.user_id = w2.user_id WHERE w1.wallet_id = (SELECT MIN(wallet_id) FROM blockchain.wallets w3 WHERE w3.user_id = w1.user_id);

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


[User] Show me for each asset_id, the number of associated metadata entries and the total number of notifications ever sent to users.

[Assistant]
SELECT m.asset_id, COUNT(m.metadata_id) AS metadata_count, (SELECT COUNT(*) FROM trading_platform.notifications) AS total_notifications
FROM trading_platform.metadata m
GROUP BY m.asset_id;

[User] I only want assets that have more than three metadata entries.

[Assistant]
SELECT m.asset_id, COUNT(m.metadata_id) AS metadata_count, (SELECT COUNT(*) FROM trading_platform.notifications) AS total_notifications
FROM trading_platform.metadata m
GROUP BY m.asset_id
HAVING COUNT(m.metadata_id) > 3;

[User] Also, only include cases where the total notifications is above 50.

[Assistant]
SELECT m.asset_id, COUNT(m.metadata_id) AS metadata_count, tn.total_notifications
FROM trading_platform.metadata m
CROSS JOIN (SELECT COUNT(*) AS total_notifications FROM trading_platform.notifications) tn
GROUP BY m.asset_id, tn.total_notifications
HAVING COUNT(m.metadata_id) > 3 AND tn.total_notifications > 50;

[User] Can you add a column showing the most recent notification sent_at timestamp for the whole system to this result?

[Assistant]
SELECT m.asset_id, COUNT(m.metadata_id) AS metadata_count, tn.total_notifications, tn.latest_sent_at
FROM trading_platform.metadata m
CROSS JOIN (
  SELECT COUNT(*) AS total_notifications, MAX(sent_at) AS latest_sent_at
  FROM trading_platform.notifications
) tn
GROUP BY m.asset_id, tn.total_notifications, tn.latest_sent_at
HAVING COUNT(m.metadata_id) > 3 AND tn.total_notifications > 50;

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


[User] Find all peers that haven't been seen in the last 30 days, along with their IP addresses and ports.

[Assistant] SELECT peer_id, ip_address, port FROM trading_platform.peers WHERE last_seen < CURRENT_DATE - INTERVAL '30 days';

[User] Now show me the count of such inactive peers grouped by their port numbers.

[Assistant] SELECT port, COUNT(*) AS inactive_peer_count FROM trading_platform.peers WHERE last_seen < CURRENT_DATE - INTERVAL '30 days' GROUP BY port;

[User] Actually, I want to see only ports with more than 5 inactive peers.

[Assistant] SELECT port, COUNT(*) AS inactive_peer_count FROM trading_platform.peers WHERE last_seen < CURRENT_DATE - INTERVAL '30 days' GROUP BY port HAVING COUNT(*) > 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id character varying(64) NOT NULL, transaction_id character varying(64) NOT NULL, output_index integer NOT NULL, address character varying(128) NOT NULL, amount numeric(38,14) NOT NULL, spent boolean NOT NULL, PRIMARY KEY (utxo_id) )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, status character varying(32) NOT NULL, reviewed_at timestamp NOT NULL, PRIMARY KEY (kyc_audit_id) )


[User] Show a list of all trips along with the first and last names of all passengers who have booked on those trips. Each result should have the trip_id, passenger first name and last name.

[Assistant]
SELECT t.trip_id, p.first_name, p.last_name
FROM transportation.trips t
JOIN transportation.bookings b ON t.trip_id = b.trip_id
JOIN transportation.passengers p ON b.passenger_id = p.passenger_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 transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)


[User] List all pairs of drivers whose license_expiry_date falls in the same month and year. Display the first and last names of both drivers as driver1_first, driver1_last, driver2_first, driver2_last, and the shared year and month as expiry_year and expiry_month.

[Assistant]
SELECT d1.first_name AS driver1_first, d1.last_name AS driver1_last,
       d2.first_name AS driver2_first, d2.last_name AS driver2_last,
       EXTRACT(YEAR FROM d1.license_expiry_date) AS expiry_year,
       EXTRACT(MONTH FROM d1.license_expiry_date) AS expiry_month
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date)
 AND EXTRACT(MONTH FROM d1.license_expiry_date) = EXTRACT(MONTH FROM d2.license_expiry_date)
 AND d1.driver_id < d2.driver_id;

[User] Now limit to only those expiry dates in the year 2024.

[Assistant]
SELECT d1.first_name AS driver1_first, d1.last_name AS driver1_last,
       d2.first_name AS driver2_first, d2.last_name AS driver2_last,
       EXTRACT(YEAR FROM d1.license_expiry_date) AS expiry_year,
       EXTRACT(MONTH FROM d1.license_expiry_date) AS expiry_month
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date)
 AND EXTRACT(MONTH FROM d1.license_expiry_date) = EXTRACT(MONTH FROM d2.license_expiry_date)
 AND d1.driver_id < d2.driver_id
WHERE EXTRACT(YEAR FROM d1.license_expiry_date) = 2024;

[User] Also include only pairs where both drivers have status 'Active'.

[Assistant]
SELECT d1.first_name AS driver1_first, d1.last_name AS driver1_last,
       d2.first_name AS driver2_first, d2.last_name AS driver2_last,
       EXTRACT(YEAR FROM d1.license_expiry_date) AS expiry_year,
       EXTRACT(MONTH FROM d1.license_expiry_date) AS expiry_month
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date)
 AND EXTRACT(MONTH FROM d1.license_expiry_date) = EXTRACT(MONTH FROM d2.license_expiry_date)
 AND d1.driver_id < d2.driver_id
WHERE EXTRACT(YEAR FROM d1.license_expiry_date) = 2024
  AND d1.status = 'Active'
  AND d2.status = 'Active';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )


[User] List each wallet with its corresponding user_id and the total number of notifications that user has received.

[Assistant]
SELECT w.wallet_id, w.user_id, COUNT(n.notification_id) as total_notifications
FROM trading_platform.wallets w
LEFT JOIN trading_platform.notifications n ON w.user_id = n.user_id
GROUP BY w.wallet_id, w.user_id;

[User] Can you also display only wallets for users who have received at least 5 notifications?

[Assistant]
SELECT w.wallet_id, w.user_id, COUNT(n.notification_id) as total_notifications
FROM trading_platform.wallets w
LEFT JOIN trading_platform.notifications n ON w.user_id = n.user_id
GROUP BY w.wallet_id, w.user_id
HAVING COUNT(n.notification_id) >= 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id.text, asset_id.text, key.text, value.text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] For each game, show the game title, the total duration of all sessions in seconds, and the average score.

[Assistant] SELECT g.title, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title;

[User] Could you also show the total number of sessions for each game?

[Assistant] SELECT g.title, COUNT(gs.session_id) AS total_sessions, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title;

[User] Filter the results to only include games with more than 100 sessions.

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


[User] List all applications that have at least one document with a verification status of 'Verified'. Show the application reference number and the name of the service associated with the application.

[Assistant]
SELECT
  T1.reference_number,
  T2.service_name
FROM government_services.applications AS T1
INNER JOIN government_services.services AS T2
  ON T1.service_id = T2.service_id
WHERE EXISTS (
  SELECT
    1
  FROM government_services.documents AS T3
  WHERE
    T3.application_id = T1.application_id AND T3.verification_status = 'Verified'
);

[User] Now, only include applications that were submitted in the year 2024.

[Assistant]
SELECT
  T1.reference_number,
  T2.service_name
FROM government_services.applications AS T1
INNER JOIN government_services.services AS T2
  ON T1.service_id = T2.service_id
WHERE EXISTS (
  SELECT
    1
  FROM government_services.documents AS T3
  WHERE
    T3.application_id = T1.application_id AND T3.verification_status = 'Verified'
)
AND EXTRACT(YEAR FROM T1.submitted_at) = 2024;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies (
    agency_id character varying(64) NOT NULL, -- unique identifier for the agency
    agency_name character varying(255) NOT NULL, -- full name of the government agency
    jurisdiction_level character varying(50) NOT NULL, -- e.g., Federal, State, County, City
    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), -- FK to self for hierarchical structure
    PRIMARY KEY (agency_id)
)
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    employee_id character varying(64), -- FK to employees table (optional, if assigned)
    location_id character varying(64), -- FK to service_locations table (if physical)
    service_id character varying(64), -- FK to services table (optional, if related to specific service)
    scheduled_start_time timestamp NOT NULL,
    scheduled_end_time timestamp,
    purpose text NOT NULL, -- reason for the appointment
    status character varying(30) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-Show
    booking_method character varying(50), -- e.g., Online, Phone, In-Person
    created_at timestamp NOT NULL, -- when the appointment was booked
    notes text,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE government_services.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    application_id character varying(64), -- FK to applications table (optional)
    message_subject character varying(255),
    message_body text NOT NULL,
    channel character varying(30) NOT NULL, -- e.g., Email, SMS, Portal Message, Mail
    sent_at timestamp NOT NULL,
    status character varying(30) NOT NULL, -- e.g., Queued, Sent, Delivered, Failed, Read
    related_entity_type character varying(50), -- e.g., Application, Appointment, Document Request
    related_entity_id character varying(64), -- ID of the related entity
    PRIMARY KEY (notification_id)
)


[User] Show me all claims with police reports that were filed in the last 3 months, along with the policy details and customer information.

[Assistant] SELECT c.claim_id, c.policy_id, c.customer_id, c.incident_date, c.reported_date, c.description, c.estimated_loss, c.status, c.settlement_amount, c.settlement_date, c.police_report_number, p.product_id, p.product_name, p.product_type, b.first_name, b.last_name, b.relationship FROM insurance.claims c JOIN insurance.insurance_products p ON c.policy_id = p.product_id JOIN insurance.policy_beneficiaries b ON c.customer_id = b.customer_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months';

[User] Now filter to only show claims where the estimated loss is above $10,000.

[Assistant] SELECT c.claim_id, c.policy_id, c.customer_id, c.incident_date, c.reported_date, c.description, c.estimated_loss, c.status, c.settlement_amount, c.settlement_date, c.police_report_number, p.product_id, p.product_name, p.product_type, b.first_name, b.last_name, b.relationship FROM insurance.claims c JOIN insurance.insurance_products p ON c.policy_id = p.product_id JOIN insurance.policy_beneficiaries b ON c.customer_id = b.customer_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND c.estimated_loss > 10000;

[User] I also want to see the count of such claims per product type.

[Assistant] SELECT p.product_type, COUNT(c.claim_id) AS claim_count FROM insurance.claims c JOIN insurance.insurance_products p ON c.policy_id = p.product_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND c.estimated_loss > 10000 GROUP BY p.product_type;

[User] Finally, show me the average estimated loss for these claims by product type.

[Assistant] SELECT p.product_type, AVG(c.estimated_loss) AS avg_estimated_loss FROM insurance.claims c JOIN insurance.insurance_products p ON c.policy_id = p.product_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND c.estimated_loss > 10000 GROUP BY p.product_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 insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )


[User] Show me all rooms that are currently available (status = 'available') and have a non-smoking policy, along with their room type details including base rate and max occupancy.

[Assistant] SELECT r.room_id, r.room_number, r.floor, rt.type_name, rt.base_rate, rt.max_occupancy, rt.bed_type, rt.area_sqft FROM hospitality_technology.rooms r JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.status = 'available' AND r.is_smoking = false;

[User] Now, filter these results to only include rooms with a max occupancy of at least 4 people and order them by base rate in ascending order.

[Assistant] SELECT r.room_id, r.room_number, r.floor, rt.type_name, rt.base_rate, rt.max_occupancy, rt.bed_type, rt.area_sqft FROM hospitality_technology.rooms r JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.status = 'available' AND r.is_smoking = false AND rt.max_occupancy >= 4 ORDER BY rt.base_rate ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.room_types ( room_type_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, type_name character varying(100) NOT NULL, description text, base_rate numeric(10, 2) NOT NULL, max_occupancy integer NOT NULL, bed_type character varying(50), area_sqft numeric(8,2), amenities text, PRIMARY KEY (room_type_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] Count the number of prescriptions each doctor has written for medications manufactured by 'Pfizer' in the last 6 months.

[Assistant]
SELECT p.doctor_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions p
JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE m.manufacturer = 'Pfizer'
  AND p.prescription_date >= CURRENT_DATE - INTERVAL '6 months'
GROUP BY p.doctor_id;

[User] Actually, please include the doctor's full name instead of the ID, and order the results by prescription_count descending.

[Assistant]
SELECT p.doctor_id,
       d.first_name || ' ' || d.last_name AS doctor_name,
       COUNT(*) AS prescription_count
FROM healthcare.prescriptions p
JOIN healthcare.medications m ON p.medication_id = m.medication_id
JOIN healthcare.doctors d ON p.doctor_id = d.doctor_id
WHERE m.manufacturer = 'Pfizer'
  AND p.prescription_date >= CURRENT_DATE - INTERVAL '6 months'
GROUP BY p.doctor_id, doctor_name
ORDER BY prescription_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] For each passenger, compute the count of bookings and average fare for bookings made in February 2024.

[Assistant]
SELECT p.passenger_id, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2024-02-01' AND b.booking_time < '2024-03-01'
GROUP BY p.passenger_id;

[User] I need to see the passengers' first and last names instead of IDs and only include those with an average fare greater than 75.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2024-02-01' AND b.booking_time < '2024-03-01'
GROUP BY p.first_name, p.last_name
HAVING AVG(b.fare) > 75;

[User] Also, order the results by booking_count descending and limit the output to the top 5 passengers.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2024-02-01' AND b.booking_time < '2024-03-01'
GROUP BY p.first_name, p.last_name
HAVING AVG(b.fare) > 75
ORDER BY booking_count DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )


[User] Could you list all games, show their title and genre, and also include the total number of achievements for each game?

[Assistant] SELECT g.title, g.genre, COUNT(a.achievement_id) AS total_achievements FROM gaming_technology.games g LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id GROUP BY g.game_id, g.title, g.genre;

[User] Okay, now can you also include the developer's name for each game?

[Assistant] SELECT d.name AS developer_name, g.title, g.genre, COUNT(a.achievement_id) AS total_achievements FROM gaming_technology.games g JOIN gaming_technology.developers d ON g.developer_id = d.developer_id LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id GROUP BY d.developer_id, d.name, g.game_id, g.title, g.genre;

[User] Can you filter the results to only show games from the 'Action' genre or games developed in 'Japan'?

[Assistant] SELECT d.name AS developer_name, g.title, g.genre, COUNT(a.achievement_id) AS total_achievements FROM gaming_technology.games g JOIN gaming_technology.developers d ON g.developer_id = d.developer_id LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id WHERE g.genre = 'Action' OR d.country = 'Japan' GROUP BY d.developer_id, d.name, g.game_id, g.title, g.genre;

[User] Finally, order the results by the total number of achievements in descending order, and only show games with at least one achievement.

[Assistant] SELECT d.name AS developer_name, g.title, g.genre, COUNT(a.achievement_id) AS total_achievements FROM gaming_technology.games g JOIN gaming_technology.developers d ON g.developer_id = d.developer_id JOIN gaming_technology.achievements a ON g.game_id = a.game_id GROUP BY d.developer_id, d.name, g.game_id, g.title, g.genre HAVING COUNT(a.achievement_id) > 0 ORDER BY total_achievements DESC;


[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] For each customer, what is their total premium amount and total deductible across all their policies?

[Assistant] SELECT customer_id, SUM(premium_amount) AS total_premium, SUM(deductible) AS total_deductible FROM insurance.policies GROUP BY customer_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )


[User] Give me the total number of reservations and the sum of total_amount by month for the year 2023.

[Assistant]
SELECT DATE_TRUNC('month', check_in_date) AS month,
       COUNT(*)                         AS reservation_count,
       SUM(total_amount)               AS total_revenue
FROM hospitality_technology.reservations
WHERE EXTRACT(YEAR FROM check_in_date) = 2023
GROUP BY DATE_TRUNC('month', check_in_date)
ORDER BY month;

[User] Actually, I only want reservations with status 'CheckedOut' or 'Completed'.

[Assistant]
SELECT DATE_TRUNC('month', check_in_date) AS month,
       COUNT(*)                         AS reservation_count,
       SUM(total_amount)               AS total_revenue
FROM hospitality_technology.reservations
WHERE EXTRACT(YEAR FROM check_in_date) = 2023
  AND status IN ('CheckedOut', 'Completed')
GROUP BY DATE_TRUNC('month', check_in_date)
ORDER BY 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.reservations ( reservation_id text PRIMARY KEY, 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 int, num_children int, 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] Find projects from the project_fundraising_record table that have completed both a 'Seed' fundraising round and a 'Series A' fundraising round.

[Assistant] SELECT pf_seed.project_name FROM project_fundraising_record pf_seed JOIN project_fundraising_record pf_seriesa ON pf_seed.project_id = pf_seriesa.project_id WHERE pf_seed.rounds_name = 'Seed' AND pf_seriesa.rounds_name = 'Series A';

[User] For these projects that had both a 'Seed' and 'Series A' round, show the investment value for both rounds side by side.

[Assistant] SELECT pf_seed.project_name, pf_seed.investment_value AS seed_investment, pf_seriesa.investment_value AS seriesa_investment FROM project_fundraising_record pf_seed JOIN project_fundraising_record pf_seriesa ON pf_seed.project_id = pf_seriesa.project_id WHERE pf_seed.rounds_name = 'Seed' AND pf_seriesa.rounds_name = 'Series A';

[User] Filter the results to only include projects where the investment value in the 'Series A' round was greater than the investment value in the 'Seed' round.

[Assistant] SELECT pf_seed.project_name, pf_seed.investment_value AS seed_investment, pf_seriesa.investment_value AS seriesa_investment FROM project_fundraising_record pf_seed JOIN project_fundraising_record pf_seriesa ON pf_seed.project_id = pf_seriesa.project_id WHERE pf_seed.rounds_name = 'Seed' AND pf_seriesa.rounds_name = 'Series A' AND pf_seriesa.investment_value > pf_seed.investment_value;

[User] Order the results by the 'Series A' investment value in descending order and show the top 5 projects.

[Assistant] SELECT pf_seed.project_name, pf_seed.investment_value AS seed_investment, pf_seriesa.investment_value AS seriesa_investment FROM project_fundraising_record pf_seed JOIN project_fundraising_record pf_seriesa ON pf_seed.project_id = pf_seriesa.project_id WHERE pf_seed.rounds_name = 'Seed' AND pf_seriesa.rounds_name = 'Series A' AND pf_seriesa.investment_value > pf_seed.investment_value ORDER BY seriesa_investment 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 project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
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] For each blockchain (chain), find the token with the highest ROI in the smart_money_token_performance table, and include that token's narrative from smart_money_token_inflow, its net_flow, and avg_cost.

[Assistant] WITH ranked_tokens AS ( SELECT p.chain, p.token_symbol, p.token_address, p.roi, p.avg_cost, i.narrative, i.net_flow, ROW_NUMBER() OVER (PARTITION BY p.chain ORDER BY p.roi DESC) AS rn FROM smart_money_token_performance p LEFT JOIN smart_money_token_inflow i ON p.token_address = i.token_address AND p.chain = i.chain ) SELECT chain, token_symbol, roi, narrative, net_flow, avg_cost FROM ranked_tokens WHERE rn = 1;

[User] Please exclude any tokens where net_flow is negative or NULL from these results.

[Assistant] WITH ranked_tokens AS ( SELECT p.chain, p.token_symbol, p.token_address, p.roi, p.avg_cost, i.narrative, i.net_flow, ROW_NUMBER() OVER (PARTITION BY p.chain ORDER BY p.roi DESC) AS rn FROM smart_money_token_performance p JOIN smart_money_token_inflow i ON p.token_address = i.token_address AND p.chain = i.chain WHERE i.net_flow > 0 ) SELECT chain, token_symbol, roi, narrative, net_flow, avg_cost FROM ranked_tokens WHERE rn = 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 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 )
  "CREATE TABLE smart_money_token_inflow (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token",
    "usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token",
    "avg_price numeric(38,6), -- the average cost price of user spent on this token",
    "type int, -- the direction of the trade on this token. 1 means buying, 2 means selling",
    "address_amount integer, -- the amount of the user bought this token",
    "narrative character varying(100), -- the category or narrative of the token",
    "chain character varying(100), -- the chain that the token resides",
    ",PRIMARY KEY (token_address, chain)",


[User] For each booking, show the booking ID, the passenger ID, the trip ID, and indicate if a special request was made.

[Assistant]
SELECT booking_id, passenger_id, trip_id,
       CASE WHEN special_requests IS NOT NULL AND special_requests <> '' THEN 'Yes' ELSE 'No' END AS has_special_request
FROM transportation.bookings;

[User] Can you only include bookings with special requests?

[Assistant]
SELECT booking_id, passenger_id, trip_id, special_requests
FROM transportation.bookings
WHERE special_requests IS NOT NULL AND special_requests <> '';

[User] Add the booking time and sort the results by most recent booking.

[Assistant]
SELECT booking_id, passenger_id, trip_id, special_requests, booking_time
FROM transportation.bookings
WHERE special_requests IS NOT NULL AND special_requests <> ''
ORDER BY booking_time DESC;

[User] Please only show the top 5 most recent bookings with special requests.

[Assistant]
SELECT booking_id, passenger_id, trip_id, special_requests, booking_time
FROM transportation.bookings
WHERE special_requests IS NOT NULL AND special_requests <> ''
ORDER BY booking_time 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 transportation.bookings (
    booking_id character varying(64) NOT NULL,  -- unique identifier for the booking
    passenger_id character varying(64) NOT NULL, -- identifier of the passenger making the booking
    trip_id character varying(64) NOT NULL, -- identifier of the trip being booked
    seat_number character varying(16), -- assigned seat number (if applicable)
    booking_time timestamp with time zone NOT NULL, -- time when the booking was made
    status character varying(32) NOT NULL, -- e.g., Confirmed, Cancelled, Pending Payment
    fare numeric(10, 2) NOT NULL, -- price paid for the booking
    payment_transaction_id character varying(128), -- reference to the payment transaction
    special_requests text, -- any special requests from the passenger
    PRIMARY KEY (booking_id)
)