[User] Show me all trips along with the vehicle make and the route distance in km.

[Assistant]
SELECT t.trip_id, v.make, r.distance_km
FROM transportation.trips t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
JOIN transportation.routes r ON t.route_id = r.route_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.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)
)
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 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 text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )


[User] List the name and location ID for all locations where the postal code is missing.

[Assistant] SELECT name, location_id FROM transportation.locations WHERE postal_code IS NULL;

[User] Also include the city and order the results by city ascending.

[Assistant] SELECT name, location_id, city FROM transportation.locations WHERE postal_code IS NULL ORDER BY city 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 transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )


[User] Find pairs of patients where patient A's emergency contact phone matches patient B's phone number, and patient B's emergency contact phone matches patient A's phone number. Include both patient IDs, their full names, patient A's phone, and patient B's phone.

[Assistant] SELECT p1.patient_id AS patient_a_id, p1.first_name AS patient_a_first_name, p1.last_name AS patient_a_last_name, p2.patient_id AS patient_b_id, p2.first_name AS patient_b_first_name, p2.last_name AS patient_b_last_name, p1.phone_number AS patient_a_phone, p2.phone_number AS patient_b_phone FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.emergency_contact_phone = p2.phone_number AND p2.emergency_contact_phone = p1.phone_number AND p1.patient_id != p2.patient_id;

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


[User] Can you show me each doctor and the number of prescriptions they wrote for each patient they treated? Include the doctor's full name, the patient's full name, and the total count of prescriptions.

[Assistant] SELECT d.first_name, d.last_name, p.first_name, p.last_name, COUNT(pr.prescription_id) AS prescription_count FROM healthcare.prescriptions pr JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id JOIN healthcare.patients p ON pr.patient_id = p.patient_id GROUP BY d.doctor_id, d.first_name, d.last_name, p.patient_id, p.first_name, p.last_name;

[User] Actually, only show combinations where the doctor has written more than 2 prescriptions for that patient.

[Assistant] SELECT d.first_name, d.last_name, p.first_name, p.last_name, COUNT(pr.prescription_id) AS prescription_count FROM healthcare.prescriptions pr JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id JOIN healthcare.patients p ON pr.patient_id = p.patient_id GROUP BY d.doctor_id, d.first_name, d.last_name, p.patient_id, p.first_name, p.last_name HAVING COUNT(pr.prescription_id) > 2;

[User] Also, include the date of the most recent prescription for each combination, and sort the results by the prescription count in descending order.

[Assistant] SELECT d.first_name, d.last_name, p.first_name, p.last_name, COUNT(pr.prescription_id) AS prescription_count, MAX(pr.prescription_date) AS most_recent_prescription_date FROM healthcare.prescriptions pr JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id JOIN healthcare.patients p ON pr.patient_id = p.patient_id GROUP BY d.doctor_id, d.first_name, d.last_name, p.patient_id, p.first_name, p.last_name HAVING COUNT(pr.prescription_id) > 2 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.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )


[User] Find all wallets that were created by users with IDs starting with 'admin_' and show their addresses along with creation timestamps.

[Assistant] SELECT address, created_at FROM web3.wallets WHERE user_id LIKE 'admin_%';

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


[User] How many users in total have a profile picture URL specified?

[Assistant] SELECT COUNT(*) FROM social_media.users WHERE profile_picture_url IS NOT NULL

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
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.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )


[User] List the names and types of all in-game items that have a rarity of 'Epic'.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic';

[User] Further restrict the list to only include items of item_type 'Weapon'.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon';

[User] Order these results by their cost_amount in descending order.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon' ORDER BY cost_amount DESC;

[User] Please also include the cost_currency and cost_amount in the output.

[Assistant] SELECT item_name, item_type, cost_currency, cost_amount FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon' ORDER BY cost_amount DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid, player_id uuid, item_id uuid, quantity integer, acquired_at timestamp with time zone, instance_data jsonb )


[User] Find all events with name 'Transfer' that were emitted by contracts deployed by address '0x1234', showing the event data and deployment timestamp of the contract.

[Assistant] SELECT e.event_id, e.data, c.deployed_at FROM web3.events e JOIN web3.contracts c ON e.contract_id = c.contract_id WHERE e.event_name = 'Transfer' AND c.deployer_address = '0x1234';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.contracts (
    contract_id character varying(64) NOT NULL,  -- unique identifier for the contract
    address character varying(128) NOT NULL, -- address of the deployed contract
    abi text NOT NULL, -- application binary interface of the contract
    bytecode text NOT NULL, -- bytecode of the contract
    deployer_address character varying(128) NOT NULL, -- address of the deployer
    deployed_at timestamp NOT NULL, -- time when the contract was deployed
    network_id character varying(64) NOT NULL, -- identifier of the network where the contract is deployed
    status character varying(32) NOT NULL, -- status of the contract (e.g., active, deprecated)
    PRIMARY KEY (contract_id)
)
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)


[User] List the IDs of citizens who have received notifications related to more than one distinct type of entity.

[Assistant] SELECT citizen_id FROM government_services.notifications WHERE related_entity_type IS NOT NULL AND related_entity_type != '' GROUP BY citizen_id HAVING COUNT(DISTINCT related_entity_type) > 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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] Which developers founded after 2010 have published games using the 'Unreal Engine'? List the developer's name, country, game title, and the release year.

[Assistant]
SELECT d.name AS developer_name, d.country, g.title AS game_title, EXTRACT(YEAR FROM g.release_date) AS release_year
FROM gaming_technology.developers d
JOIN gaming_technology.games g
  ON d.developer_id = g.developer_id
WHERE d.founded_year > 2010 AND g.engine = 'Unreal Engine';

[User] Show only games released in or after 2022.

[Assistant]
SELECT d.name AS developer_name, d.country, g.title AS game_title, EXTRACT(YEAR FROM g.release_date) AS release_year
FROM gaming_technology.developers d
JOIN gaming_technology.games g
  ON d.developer_id = g.developer_id
WHERE d.founded_year > 2010 AND g.engine = 'Unreal Engine' AND g.release_date >= '2022-01-01';

[User] Include the developer's website and the full release date for each game.

[Assistant]
SELECT d.name AS developer_name, d.country, d.website AS developer_website, g.title AS game_title, g.release_date
FROM gaming_technology.developers d
JOIN gaming_technology.games g
  ON d.developer_id = g.developer_id
WHERE d.founded_year > 2010 AND g.engine = 'Unreal Engine' AND g.release_date >= '2022-01-01';

[User] Now, limit the results to developers located in 'Canada'.

[Assistant]
SELECT d.name AS developer_name, d.country, d.website AS developer_website, g.title AS game_title, g.release_date
FROM gaming_technology.developers d
JOIN gaming_technology.games g
  ON d.developer_id = g.developer_id
WHERE d.founded_year > 2010 AND g.engine = 'Unreal Engine' AND g.release_date >= '2022-01-01' AND d.country = 'Canada';

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, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )


[User] Show me the user ID, username, and email for all users.

[Assistant] SELECT user_id, username, email FROM blockchain.users;

[User] Now, only show the users whose username starts with 'alpha'.

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

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.users ( user_id.text, username.text, email.text, password_hash.text )


[User] I want to find all claim IDs that have both an 'Accident Report' and a 'Police Report' document.

[Assistant]
SELECT DISTINCT a.claim_id
FROM insurance.claim_documents a
JOIN insurance.claim_documents b
  ON a.claim_id = b.claim_id
WHERE a.document_type = 'Accident Report'
  AND b.document_type = 'Police Report';

[User] Now, only include those pairs if both documents were uploaded after '2024-06-01'.

[Assistant]
SELECT DISTINCT a.claim_id
FROM insurance.claim_documents a
JOIN insurance.claim_documents b
  ON a.claim_id = b.claim_id
WHERE a.document_type = 'Accident Report'
  AND b.document_type = 'Police Report'
  AND a.uploaded_at > '2024-06-01'
  AND b.uploaded_at > '2024-06-01';

[User] Additionally, ensure that both files are larger than 500 KB.

[Assistant]
SELECT DISTINCT a.claim_id
FROM insurance.claim_documents a
JOIN insurance.claim_documents b
  ON a.claim_id = b.claim_id
WHERE a.document_type = 'Accident Report'
  AND b.document_type = 'Police Report'
  AND a.uploaded_at > '2024-06-01'
  AND b.uploaded_at > '2024-06-01'
  AND a.file_size_bytes > 512000
  AND b.file_size_bytes > 512000;

[User] Finally, show me the file_name and uploaded_by for both document types in the results.

[Assistant]
SELECT
    a.claim_id,
    a.file_name       AS accident_file_name,
    a.uploaded_by     AS accident_uploaded_by,
    b.file_name       AS police_file_name,
    b.uploaded_by     AS police_uploaded_by
FROM insurance.claim_documents a
JOIN insurance.claim_documents b
  ON a.claim_id = b.claim_id
WHERE a.document_type = 'Accident Report'
  AND b.document_type = 'Police Report'
  AND a.uploaded_at > '2024-06-01'
  AND b.uploaded_at > '2024-06-01'
  AND a.file_size_bytes > 512000
  AND b.file_size_bytes > 512000;

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.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )


[User] Which developers have created games that include at least one item of rarity 'Legendary'? Show the developer_id and the item_name.

[Assistant]
SELECT d.developer_id, igi.item_name
FROM gaming_technology.developers d
JOIN gaming_technology.in_game_items igi ON d.developer_id = igi.game_id /* This assumes developer_id = game_id; adjust join logic as needed */
WHERE igi.rarity = 'Legendary';

[User] I think the join is wrong, it should match developers to games and then in_game_items to games. Please revise the SQL.

[Assistant]
-- Assuming the existence of a 'games' table with columns (game_id, developer_id)
SELECT d.developer_id, igi.item_name
FROM gaming_technology.developers d
JOIN gaming_technology.games g ON d.developer_id = g.developer_id
JOIN gaming_technology.in_game_items igi ON g.game_id = igi.game_id
WHERE igi.rarity = 'Legendary';

[User] You can only use the given tables. Is it possible to get a list of developers who have legendary items in their games with the available schema?

[Assistant] -- Based on the given schema alone (without a games table), it's not possible to relate developers to in_game_items directly since there is no relationship between developer_id and game_id in the available tables.

[User] Okay, then just list all 'Legendary' rarity in-game items, including their item_id, item_name, and cost_amount.

[Assistant]
SELECT item_id, item_name, cost_amount
FROM gaming_technology.in_game_items
WHERE rarity = 'Legendary';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )


[User] Show me all patients who have been prescribed medications with dosage greater than 100mg, along with their full names and the medication details.

[Assistant] SELECT p.first_name, p.last_name, m.medication_name, m.generic_name, pr.dosage, pr.frequency, pr.start_date, pr.end_date FROM healthcare.patients p JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id JOIN healthcare.medications m ON pr.medication_id = m.medication_id WHERE pr.dosage LIKE '%100mg%' OR pr.dosage LIKE '%>100mg%';

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 PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions (
    prescription_id character varying(64) NOT NULL, -- unique identifier for the prescription
    record_id character varying(64) NOT NULL, -- FK linking to the medical record where it was prescribed
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to prescribing doctor
    medication_id character varying(64) NOT NULL, -- FK to medications table
    dosage character varying(100) NOT NULL, -- e.g., '100mg', '1 tablet'
    frequency character varying(100) NOT NULL, -- e.g., 'Once daily', 'Twice a day with meals'
    route character varying(50), -- e.g., 'Oral', 'Topical', 'Intravenous'
    start_date date NOT NULL, -- date prescription begins
    end_date date, -- date prescription ends (if applicable)
    quantity_dispensed numeric(10,2), -- amount dispensed (e.g., number of tablets)
    refills_allowed integer NOT NULL DEFAULT 0, -- number of allowed refills
    prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (prescription_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, 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, -- 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] Show policy numbers and product names for all policies that started in 2023.

[Assistant] SELECT p.policy_number, ip.product_name FROM insurance.policies AS p JOIN insurance.insurance_products AS ip ON p.product_id = ip.product_id WHERE date_part('year', p.start_date) = 2023

[User] Add the policy status and the product type to the list.

[Assistant] SELECT p.policy_number, ip.product_name, p.status, ip.product_type FROM insurance.policies AS p JOIN insurance.insurance_products AS ip ON p.product_id = ip.product_id WHERE date_part('year', p.start_date) = 2023

[User] Filter these policies to only include those where the product is currently active and the policy status is 'active'.

[Assistant] SELECT p.policy_number, ip.product_name, p.status, ip.product_type FROM insurance.policies AS p JOIN insurance.insurance_products AS ip ON p.product_id = ip.product_id WHERE date_part('year', p.start_date) = 2023 AND p.status = 'active' AND ip.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.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )


[User] List all replacement policies where a customer received a new policy starting the day after their previous policy was cancelled. Return customer_id, original_policy_id, original_cancellation_date, new_policy_id, new_start_date.

[Assistant]
SELECT orig.customer_id,
       orig.policy_id      AS original_policy_id,
       orig.cancellation_date AS original_cancellation_date,
       nw.policy_id        AS new_policy_id,
       nw.start_date       AS new_start_date
FROM insurance.policies orig
JOIN insurance.policies nw
  ON orig.customer_id = nw.customer_id
 AND orig.cancellation_date IS NOT NULL
 AND nw.start_date = orig.cancellation_date + INTERVAL '1 day';

[User] Now include the premium_amount difference as premium_diff and only show cases where the new policy's premium is higher.

[Assistant]
SELECT orig.customer_id,
       orig.policy_id      AS original_policy_id,
       orig.cancellation_date AS original_cancellation_date,
       nw.policy_id        AS new_policy_id,
       nw.start_date       AS new_start_date,
       (nw.premium_amount - orig.premium_amount) AS premium_diff
FROM insurance.policies orig
JOIN insurance.policies nw
  ON orig.customer_id = nw.customer_id
 AND orig.cancellation_date IS NOT NULL
 AND nw.start_date = orig.cancellation_date + INTERVAL '1 day'
WHERE nw.premium_amount > orig.premium_amount;

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


[User] Show me all appointments along with any diagnoses recorded for the same patient on the same day. Include appointment_id, patient_id, appointment_time, and diagnosis_description.

[Assistant] SELECT T1.appointment_id, T1.patient_id, T1.appointment_time, T2.description FROM healthcare.appointments AS T1 JOIN healthcare.diagnoses AS T2 ON T1.patient_id = T2.patient_id AND DATE(T1.appointment_time) = T2.diagnosis_date;

[User] Refine this to only include diagnoses that are marked as 'chronic'.

[Assistant] SELECT T1.appointment_id, T1.patient_id, T1.appointment_time, T2.description FROM healthcare.appointments AS T1 JOIN healthcare.diagnoses AS T2 ON T1.patient_id = T2.patient_id AND DATE(T1.appointment_time) = T2.diagnosis_date WHERE T2.is_chronic = true;

[User] Additionally, filter to only include appointments where the status is 'Completed'.

[Assistant] SELECT T1.appointment_id, T1.patient_id, T1.appointment_time, T2.description FROM healthcare.appointments AS T1 JOIN healthcare.diagnoses AS T2 ON T1.patient_id = T2.patient_id AND DATE(T1.appointment_time) = T2.diagnosis_date WHERE T2.is_chronic = true AND T1.status = 'Completed';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )


[User] Show me all in-progress trips with their vehicle IDs and the difference between scheduled and actual departure time in minutes.

[Assistant] SELECT trip_id, vehicle_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS departure_delay_minutes FROM transportation.trips WHERE status = 'in-progress';

[User] Can you include the driver ID and filter to only show trips that have been delayed by more than 15 minutes?

[Assistant] SELECT trip_id, vehicle_id, driver_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS departure_delay_minutes FROM transportation.trips WHERE status = 'in-progress' AND EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 > 15;

[User] Now order these results by the delay time in descending order and include the passenger count.

[Assistant] SELECT trip_id, vehicle_id, driver_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS departure_delay_minutes, passenger_count FROM transportation.trips WHERE status = 'in-progress' AND EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 > 15 ORDER BY departure_delay_minutes DESC;

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


[User] Show me the total fuel cost for each trip along with the trip's route number and the type of the route.

[Assistant]
SELECT t.trip_id, r.route_number, r.type, SUM(f.total_cost) AS total_fuel_cost
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
GROUP BY t.trip_id, r.route_number, r.type;

[User] Modify the query to only include trips on routes of type 'Express', and show results ordered by total fuel cost descending.

[Assistant]
SELECT t.trip_id, r.route_number, r.type, SUM(f.total_cost) AS total_fuel_cost
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
WHERE r.type = 'Express'
GROUP BY t.trip_id, r.route_number, r.type
ORDER BY total_fuel_cost DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.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.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )


[User] List all policies where the premium_amount exceeds the base_premium of its insurance product. Display the policy_number, premium_amount, product_name, and base_premium. Sort the results by premium_amount descending.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
ORDER BY p.premium_amount DESC;

[User] Actually, I only want policies that are active and whose insurance products are also active.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'active'
  AND ip.is_active = TRUE
ORDER BY p.premium_amount DESC;

[User] Also, limit the output to policies with a coverage_limit greater than 1000000.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'active'
  AND ip.is_active = TRUE
  AND p.coverage_limit > 1000000
ORDER BY p.premium_amount DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text 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 )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] Show me all patients who have been prescribed medications with dosage greater than 100mg, along with their full names and the medication details, including the prescribing doctor's last name.

[Assistant] SELECT p.first_name, p.last_name, m.medication_name, m.generic_name, pr.dosage, d.last_name AS doctor_last_name FROM healthcare.patients p JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id JOIN healthcare.medications m ON pr.medication_id = m.medication_id JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id WHERE pr.dosage LIKE '%100mg%' OR CAST(SUBSTRING(pr.dosage FROM '([0-9]+)') AS INTEGER) > 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 healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions (
    prescription_id character varying(64) NOT NULL, -- unique identifier for the prescription
    record_id character varying(64) NOT NULL, -- FK linking to the medical record where it was prescribed
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to prescribing doctor
    medication_id character varying(64) NOT NULL, -- FK to medications table
    dosage character varying(100) NOT NULL, -- e.g., '100mg', '1 tablet'
    frequency character varying(100) NOT NULL, -- e.g., 'Once daily', 'Twice a day with meals'
    route character varying(50), -- e.g., 'Oral', 'Topical', 'Intravenous'
    start_date date NOT NULL, -- date prescription begins
    end_date date, -- date prescription ends (if applicable)
    quantity_dispensed numeric(10,2), -- amount dispensed (e.g., number of tablets)
    refills_allowed integer NOT NULL DEFAULT 0, -- number of allowed refills
    prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (prescription_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)


[User] List pairs of documents uploaded by the same lawyer, showing uploader ID and both document names.

[Assistant] SELECT d1.uploaded_by_lawyer_id, d1.document_name AS doc1, d2.document_name AS doc2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.uploaded_by_lawyer_id = d2.uploaded_by_lawyer_id AND d1.document_id < d2.document_id;

[User] Only include pairs where the upload timestamps are within 7 days of each other.

[Assistant] SELECT d1.uploaded_by_lawyer_id, d1.document_name AS doc1, d2.document_name AS doc2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.uploaded_by_lawyer_id = d2.uploaded_by_lawyer_id AND d1.document_id < d2.document_id AND ABS(EXTRACT(EPOCH FROM (d1.upload_timestamp - d2.upload_timestamp)))/86400 <= 7;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)


[User] Show all comments that are replies, including the comment_id, parent_comment_id, and post_id.

[Assistant] SELECT comment_id, parent_comment_id, post_id FROM social_media.comments WHERE parent_comment_id IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )


[User] What is the average ROI for smart money addresses on the Ethereum chain with a realized profit ratio above 50%?

[Assistant]
SELECT AVG(roi) as average_roi
FROM smart_money_token_performance
WHERE chain = 'Ethereum'
AND realized_ratio > 0.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.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.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 )
CREATE TABLE smart_money_token_inflow ( token_address.text, token_symbol.text, token_amount.numeric, usd_value.numeric, avg_price.numeric, type.numeric, address_amount.numeric, narrative.text, chain.text )


[User] Show me all invoices where the total_amount is more than 2000, including the invoice number, the associated case name, and the full name of the client.

[Assistant]
SELECT i.invoice_number, c.case_name, cl.first_name || ' ' || cl.last_name AS client_full_name
FROM legal_services.invoices i
JOIN legal_services.cases c ON i.case_id = c.case_id
JOIN legal_services.clients cl ON i.client_id = cl.client_id
WHERE i.total_amount > 2000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.invoices ( invoice_id character varying(64) NOT NULL, invoice_number character varying(100) UNIQUE NOT NULL, client_id character varying(64) NOT NULL, case_id character varying(64), issue_date date NOT NULL, due_date date NOT NULL, total_amount numeric(12, 2) NOT NULL, amount_paid numeric(12, 2) DEFAULT 0.00, status character varying(50) NOT NULL, payment_date timestamp, notes text, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (invoice_id) )


[User] List the count of events for each contract deployed by address '0x123abc...'

[Assistant] SELECT c.address, COUNT(e.event_id) FROM web3.contracts c JOIN web3.events e ON c.contract_id = e.contract_id WHERE c.deployer_address = '0x123abc...' GROUP BY c.address;

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 web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
CREATE TABLE web3.token_transfers ( transfer_id character varying(64) NOT NULL, token_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128) NOT NULL, value numeric(38,14) NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (transfer_id) )
CREATE TABLE web3.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE web3.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )


[User] Find all pairs of bookings on the same trip, showing both booking IDs, passenger IDs, and booking times.

[Assistant]
SELECT b1.booking_id AS booking_id1,
       b1.passenger_id AS passenger1,
       b1.booking_time AS time1,
       b2.booking_id AS booking_id2,
       b2.passenger_id AS passenger2,
       b2.booking_time AS time2
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.trip_id = b2.trip_id
 AND b1.booking_id < b2.booking_id;

[User] Now limit to only those pairs where both fares exceed 100.

[Assistant]
SELECT b1.booking_id AS booking_id1,
       b1.passenger_id AS passenger1,
       b1.booking_time AS time1,
       b2.booking_id AS booking_id2,
       b2.passenger_id AS passenger2,
       b2.booking_time AS time2
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.trip_id = b2.trip_id
 AND b1.booking_id < b2.booking_id
WHERE b1.fare > 100
  AND b2.fare > 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 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 users who have made comments that are replies to other comments. Show their user IDs, the comment ID, and the parent comment ID.

[Assistant]
SELECT user_id, comment_id, parent_comment_id
FROM social_media.comments
WHERE parent_comment_id IS NOT NULL;

[User] Now, only include users whose profiles are not private.

[Assistant]
SELECT c.user_id, c.comment_id, c.parent_comment_id
FROM social_media.comments c
JOIN social_media.user_settings us ON c.user_id = us.user_id
WHERE c.parent_comment_id IS NOT NULL
  AND us.private_profile = false;

[User] Can you also show when their profile settings were last updated and order the results by updated_at descending?

[Assistant]
SELECT c.user_id, c.comment_id, c.parent_comment_id, us.updated_at
FROM social_media.comments c
JOIN social_media.user_settings us ON c.user_id = us.user_id
WHERE c.parent_comment_id IS NOT NULL
  AND us.private_profile = false
ORDER BY us.updated_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)


[User] What is the average balance for each account_type among accounts with status 'Open'?

[Assistant] SELECT account_type, AVG(balance) AS avg_balance FROM financial_services.accounts WHERE status = 'Open' GROUP BY account_type;

[User] Exclude account types with fewer than 3 accounts.

[Assistant] SELECT account_type, AVG(balance) AS avg_balance FROM financial_services.accounts WHERE status = 'Open' GROUP BY account_type HAVING COUNT(*) >= 3;

[User] Sort the results by average balance descending.

[Assistant] SELECT account_type, AVG(balance) AS avg_balance FROM financial_services.accounts WHERE status = 'Open' GROUP BY account_type HAVING COUNT(*) >= 3 ORDER BY avg_balance DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )


[User] Show each user_id for users with 'pending' KYC status along with the count of unread notifications they have.

[Assistant]
SELECT k.user_id, COUNT(n.notification_id) AS unread_count
FROM trading_platform.kyc_audit k
JOIN trading_platform.notifications n ON k.user_id = n.user_id AND n.read_at IS NULL
WHERE k.status = 'pending'
GROUP BY k.user_id;

[User] The query doesn't include users with zero unread notifications. Please include users with zero unread notifications too.

[Assistant]
SELECT k.user_id, COALESCE(COUNT(n.notification_id),0) AS unread_count
FROM trading_platform.kyc_audit k
LEFT JOIN trading_platform.notifications n ON k.user_id = n.user_id AND n.read_at IS NULL
WHERE k.status = 'pending'
GROUP BY k.user_id;

[User] Also include the date of the most recent notification sent for each user, whether read or unread.

[Assistant]
SELECT k.user_id,
       COALESCE(COUNT(n.notification_id),0) AS unread_count,
       MAX(n.sent_at) AS last_notification_at
FROM trading_platform.kyc_audit k
LEFT JOIN trading_platform.notifications n ON k.user_id = n.user_id
WHERE k.status = 'pending'
GROUP BY k.user_id;

[User] Now only show users who have more than 1 unread notification, and order by unread_count descending.

[Assistant]
SELECT user_id, unread_count, last_notification_at
FROM (
  SELECT k.user_id,
         COALESCE(COUNT(n.notification_id),0) AS unread_count,
         MAX(n.sent_at) AS last_notification_at
  FROM trading_platform.kyc_audit k
  LEFT JOIN trading_platform.notifications n ON k.user_id = n.user_id AND n.read_at IS NULL
  WHERE k.status = 'pending'
  GROUP BY k.user_id
) t
WHERE unread_count > 1
ORDER BY unread_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 trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id 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) )
CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )
CREATE TABLE trading_platform.notifications ( notification_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, message text NOT NULL, sent_at timestamp NOT NULL, read_at timestamp, PRIMARY KEY (notification_id) )


[User] How many distinct posts does each hashtag appear in?

[Assistant] SELECT hashtag_id, COUNT(DISTINCT post_id) AS post_count FROM social_media.post_hashtags GROUP BY hashtag_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )


[User] Show me the top 5 users by the total trade volume (quantity * price) as buyers, along with their email addresses and the number of distinct assets they traded.

[Assistant] SELECT u.user_id, u.email, COUNT(DISTINCT t.asset_id) AS distinct_assets_traded, SUM(t.quantity * t.price) AS total_trade_volume FROM trading_platform.users u JOIN trading_platform.trades t ON u.user_id = t.buyer_id GROUP BY u.user_id, u.email ORDER BY total_trade_volume DESC LIMIT 5;

[User] Now filter these results to only include trades that happened in the last 30 days.

[Assistant] SELECT u.user_id, u.email, COUNT(DISTINCT t.asset_id) AS distinct_assets_traded, SUM(t.quantity * t.price) AS total_trade_volume FROM trading_platform.users u JOIN trading_platform.trades t ON u.user_id = t.buyer_id WHERE t.traded_at >= NOW() - INTERVAL '30 days' GROUP BY u.user_id, u.email ORDER BY total_trade_volume DESC LIMIT 5;

[User] Actually, I want to see the average trade size (quantity) for each of these users as well.

[Assistant] SELECT u.user_id, u.email, COUNT(DISTINCT t.asset_id) AS distinct_assets_traded, SUM(t.quantity * t.price) AS total_trade_volume, AVG(t.quantity) AS avg_trade_size FROM trading_platform.users u JOIN trading_platform.trades t ON u.user_id = t.buyer_id WHERE t.traded_at >= NOW() - INTERVAL '30 days' GROUP BY u.user_id, u.email ORDER BY total_trade_volume DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
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.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] List each player along with the number of achievements they have unlocked in game 'SuperQuest'.

[Assistant]
SELECT p.player_id,
       p.username,
       COUNT(pa.achievement_id) AS achievement_count
FROM gaming_technology.player_achievements pa
JOIN gaming_technology.players p ON pa.player_id = p.player_id
JOIN gaming_technology.achievements a ON pa.achievement_id = a.achievement_id
JOIN gaming_technology.games g ON a.game_id = g.game_id
WHERE g.title = 'SuperQuest'
GROUP BY p.player_id, p.username;

[User] Actually, I only want players who unlocked at least 5 achievements and also show their registration_date.

[Assistant]
SELECT p.player_id,
       p.username,
       p.registration_date,
       COUNT(pa.achievement_id) AS achievement_count
FROM gaming_technology.player_achievements pa
JOIN gaming_technology.players p ON pa.player_id = p.player_id
JOIN gaming_technology.achievements a ON pa.achievement_id = a.achievement_id
JOIN gaming_technology.games g ON a.game_id = g.game_id
WHERE g.title = 'SuperQuest'
GROUP BY p.player_id, p.username, p.registration_date
HAVING COUNT(pa.achievement_id) >= 5;

[User] Also include the timestamp of their earliest unlocked achievement for that game.

[Assistant]
SELECT p.player_id,
       p.username,
       p.registration_date,
       COUNT(pa.achievement_id) AS achievement_count,
       MIN(pa.unlocked_at) AS first_unlocked_at
FROM gaming_technology.player_achievements pa
JOIN gaming_technology.players p ON pa.player_id = p.player_id
JOIN gaming_technology.achievements a ON pa.achievement_id = a.achievement_id
JOIN gaming_technology.games g ON a.game_id = g.game_id
WHERE g.title = 'SuperQuest'
GROUP BY p.player_id, p.username, p.registration_date
HAVING COUNT(pa.achievement_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 gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, 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.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.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )


[User] Show me all reservations with more than 2 adults that are confirmed (status = 'Confirmed'), including their check-in dates and total amounts.

[Assistant] SELECT r.reservation_id, r.property_id, r.guest_id, r.check_in_date, r.total_amount FROM hospitality_technology.reservations r WHERE r.num_adults > 2 AND r.status = 'Confirmed';

[User] Now join this with the room_types table to include the room type name and base rate for each reservation.

[Assistant] SELECT r.reservation_id, r.property_id, r.guest_id, r.check_in_date, r.total_amount, rt.type_name, rt.base_rate FROM hospitality_technology.reservations r JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.status = 'Confirmed';

[User] The query should also show the difference between the total amount and the base rate for each reservation.

[Assistant] SELECT r.reservation_id, r.property_id, r.guest_id, r.check_in_date, r.total_amount, rt.type_name, rt.base_rate, (r.total_amount - rt.base_rate) AS rate_difference FROM hospitality_technology.reservations r JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.status = 'Confirmed';

[User] Actually, I only need reservations where the total amount is at least 50% higher than the base rate, and order them by check-in date.

[Assistant] SELECT r.reservation_id, r.property_id, r.guest_id, r.check_in_date, r.total_amount, rt.type_name, rt.base_rate, (r.total_amount - rt.base_rate) AS rate_difference FROM hospitality_technology.reservations r JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.status = 'Confirmed' AND r.total_amount >= (rt.base_rate * 1.5) ORDER BY r.check_in_date;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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,  -- unique identifier for the booking
    property_id character varying(64) NOT NULL, -- FK to properties table
    guest_id character varying(64) NOT NULL, -- FK to guests table (primary guest)
    room_id character varying(64), -- FK to rooms table (assigned room, might be null initially)
    room_type_id character varying(64) NOT NULL, -- FK to room_types table (booked room type)
    check_in_date date NOT NULL, -- scheduled check-in date
    check_out_date date NOT NULL, -- scheduled check-out date
    actual_check_in_ts timestamp with time zone, -- actual check-in time
    actual_check_out_ts timestamp with time zone, -- actual check-out time
    num_adults integer NOT NULL, -- number of adults
    num_children integer DEFAULT 0, -- number of children
    status character varying(50) NOT NULL, -- e.g., Pending, Confirmed, CheckedIn, CheckedOut, Cancelled, NoShow
    booking_source character varying(100), -- e.g., Website, OTA (Expedia, Booking.com), Phone, WalkIn
    rate_plan_id character varying(64), -- FK to rate_plans table (optional)
    total_amount numeric(12, 2), -- estimated or final total cost
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    special_requests text, -- specific guest requests for this booking
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (reservation_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    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)
)
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )


[User] List all guests who have never left a review, including their full name and email.

[Assistant]
SELECT g.guest_id, g.first_name, g.last_name, g.email
FROM hospitality_technology.guests g
LEFT JOIN hospitality_technology.reviews r ON g.guest_id = r.guest_id
WHERE r.review_id IS NULL;

[User] Can you also include their phone number?

[Assistant]
SELECT g.guest_id, g.first_name, g.last_name, g.email, g.phone_number
FROM hospitality_technology.guests g
LEFT JOIN hospitality_technology.reviews r ON g.guest_id = r.guest_id
WHERE r.review_id IS NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.payments ( payment_id text PRIMARY KEY, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


[User] Show me the first and last names of citizens, the appointment id, and the department of the employee who scheduled their appointment.

[Assistant]
SELECT c.first_name, c.last_name, a.appointment_id, e.department
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.employees e ON a.employee_id = e.employee_id;

[User] Can you also include the scheduled start time and filter to show only appointments with the status 'Scheduled'?

[Assistant]
SELECT c.first_name, c.last_name, a.appointment_id, e.department, a.scheduled_start_time
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.employees e ON a.employee_id = e.employee_id
WHERE a.status = 'Scheduled';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )


[User] Which chain has the highest average ROI among all tokens in smart_money_token_performance? Show the chain and the average ROI.

[Assistant]
SELECT chain, AVG(roi) AS avg_roi
FROM smart_money_token_performance
GROUP BY chain
ORDER BY avg_roi DESC
LIMIT 1;

[User] Could you also include the total number of tokens analyzed for that chain?

[Assistant]
SELECT chain, AVG(roi) AS avg_roi, COUNT(DISTINCT token_symbol) AS token_count
FROM smart_money_token_performance
GROUP BY chain
ORDER BY avg_roi DESC
LIMIT 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
CREATE TABLE smart_money_token_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 text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )


[User] Which hashtags appear on the most posts? Return hashtag_id, tag_name, and the number of posts each hashtag is used in, sorted descending, limited to the top 3.

[Assistant]
SELECT
  h.hashtag_id,
  h.tag_name,
  COUNT(ph.post_id) AS post_count
FROM social_media.hashtags h
JOIN social_media.post_hashtags ph
  ON h.hashtag_id = ph.hashtag_id
GROUP BY h.hashtag_id, h.tag_name
ORDER BY post_count DESC
LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id.text, username.text, email.text, password_hash.text, full_name.text, profile_picture_url.text, bio.text, location.text, created_at.timestamp, updated_at.timestamp, is_verified.boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.messages ( message_id.text, conversation_id.text, sender_user_id.text, content.text, media_url.text, media_type.text, sent_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )


[User] List all active products, showing their product ID, name, and type, ordered by their creation date.

[Assistant] SELECT product_id, product_name, product_type FROM insurance.insurance_products WHERE is_active = TRUE ORDER BY created_at;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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] I need to get the most recent message each verified user has sent in any group chat, showing username, group_name, message_id, and sent_at.

[Assistant]
WITH user_recent AS (
  SELECT m.sender_user_id, m.message_id, m.conversation_id, m.sent_at,
         ROW_NUMBER() OVER (PARTITION BY m.sender_user_id ORDER BY m.sent_at DESC) AS rn
  FROM social_media.messages m
  JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
  WHERE c.is_group_chat = true
)
SELECT u.username, c.group_name, ur.message_id, ur.sent_at
FROM user_recent ur
JOIN social_media.users u ON ur.sender_user_id = u.user_id
JOIN social_media.conversations c ON ur.conversation_id = c.conversation_id
WHERE ur.rn = 1
  AND u.is_verified = true;

[User] Actually, I only want messages sent in the past 30 days.

[Assistant]
WITH user_recent AS (
  SELECT m.sender_user_id, m.message_id, m.conversation_id, m.sent_at,
         ROW_NUMBER() OVER (PARTITION BY m.sender_user_id ORDER BY m.sent_at DESC) AS rn
  FROM social_media.messages m
  JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
  WHERE c.is_group_chat = true
    AND m.sent_at >= NOW() - INTERVAL '30 days'
)
SELECT u.username, c.group_name, ur.message_id, ur.sent_at
FROM user_recent ur
JOIN social_media.users u ON ur.sender_user_id = u.user_id
JOIN social_media.conversations c ON ur.conversation_id = c.conversation_id
WHERE ur.rn = 1
  AND u.is_verified = true;

[User] Also, exclude any users who have disabled push notifications.

[Assistant]
WITH user_recent AS (
  SELECT m.sender_user_id, m.message_id, m.conversation_id, m.sent_at,
         ROW_NUMBER() OVER (PARTITION BY m.sender_user_id ORDER BY m.sent_at DESC) AS rn
  FROM social_media.messages m
  JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
  WHERE c.is_group_chat = true
    AND m.sent_at >= NOW() - INTERVAL '30 days'
)
SELECT u.username, c.group_name, ur.message_id, ur.sent_at
FROM user_recent ur
JOIN social_media.users u ON ur.sender_user_id = u.user_id
JOIN social_media.conversations c ON ur.conversation_id = c.conversation_id
JOIN social_media.user_settings s ON s.user_id = u.user_id
WHERE ur.rn = 1
  AND u.is_verified = true
  AND s.push_notifications_enabled = true;

[User] And order the results by sent_at descending.

[Assistant]
WITH user_recent AS (
  SELECT m.sender_user_id, m.message_id, m.conversation_id, m.sent_at,
         ROW_NUMBER() OVER (PARTITION BY m.sender_user_id ORDER BY m.sent_at DESC) AS rn
  FROM social_media.messages m
  JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
  WHERE c.is_group_chat = true
    AND m.sent_at >= NOW() - INTERVAL '30 days'
)
SELECT u.username, c.group_name, ur.message_id, ur.sent_at
FROM user_recent ur
JOIN social_media.users u ON ur.sender_user_id = u.user_id
JOIN social_media.conversations c ON ur.conversation_id = c.conversation_id
JOIN social_media.user_settings s ON s.user_id = u.user_id
WHERE ur.rn = 1
  AND u.is_verified = true
  AND s.push_notifications_enabled = true
ORDER BY ur.sent_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
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.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )


[User] I need a list of trip_id, status, and the corresponding vehicle's license_plate and fuel_type for trips that haven't yet begun.

[Assistant]
SELECT t.trip_id, t.status, v.license_plate, v.fuel_type
FROM transportation.trips t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
WHERE t.status = 'Scheduled';

[User] I got an error because scheduled trips include records where actual_departure is not null. Please filter for trips with status 'Scheduled' and scheduled_departure in the next 7 days.

[Assistant]
SELECT t.trip_id, t.status, v.license_plate, v.fuel_type
FROM transportation.trips t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
WHERE t.status = 'Scheduled'
  AND t.actual_departure IS NULL
  AND t.scheduled_departure >= now()
  AND t.scheduled_departure < now() + interval '7 days';

[User] Additionally, exclude vehicles with status not equal to 'Active' and show results ordered by scheduled_departure ascending.

[Assistant]
SELECT t.trip_id, t.status, v.license_plate, v.fuel_type, t.scheduled_departure
FROM transportation.trips t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
WHERE t.status = 'Scheduled'
  AND t.actual_departure IS NULL
  AND t.scheduled_departure >= now()
  AND t.scheduled_departure < now() + interval '7 days'
  AND v.status = 'Active'
ORDER BY t.scheduled_departure 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 transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
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.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.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 PRIMARY KEY, 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 )