System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address.text, city.text, state.text, zip_code.text, country.text, email.text, phone_number.text, created_at.timestamp, status.text, risk_profile.text )
CREATE TABLE financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )
CREATE TABLE financial_services.transactions ( transaction_id.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text )
CREATE TABLE financial_services.trades ( trade_id.text, account_id.text, security_id.text, order_id.text, trade_type.text, quantity.numeric, price_per_unit.numeric, total_amount.numeric, commission.numeric, trade_timestamp.timestamp, settlement_date.date, status.text, execution_venue.text )
CREATE TABLE financial_services.employees ( employee_id.text, first_name.text, last_name.text, job_title.text, department.text, branch_id.text, email.text, phone_extension.text, hire_date.date, termination_date.date, manager_id.text, status.text )

[User] List all employees who were hired in the last two years along with their department and status.

[Assistant] SELECT employee_id, first_name, last_name, department, status FROM financial_services.employees WHERE hire_date >= (CURRENT_DATE - INTERVAL '2 years');

[User] Now also include their manager's full name in the output.

[Assistant] SELECT e.employee_id, e.first_name, e.last_name, e.department, e.status, m.first_name || ' ' || m.last_name AS manager_full_name FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.hire_date >= (CURRENT_DATE - INTERVAL '2 years');

[User] Only include employees whose status is 'Active' and whose manager is also currently 'Active'.

[Assistant] SELECT e.employee_id, e.first_name, e.last_name, e.department, e.status, m.first_name || ' ' || m.last_name AS manager_full_name FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.hire_date >= (CURRENT_DATE - INTERVAL '2 years') AND e.status = 'Active' AND m.status = 'Active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )

[User] List all developer names and their websites.

[Assistant] SELECT name, website FROM gaming_technology.developers;

[User] Can you only include developers whose website contains '.net'?

[Assistant] SELECT name, website FROM gaming_technology.developers WHERE website LIKE '%.net%';

[User] Also include their country in the output.

[Assistant] SELECT name, website, country FROM gaming_technology.developers WHERE website LIKE '%.net%';


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 hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.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 character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )

[User] List the top 5 most used services across all properties. Show service_name and total quantity ordered, ordered by quantity descending.

[Assistant]
SELECT s.service_name,
       SUM(o.quantity) AS total_quantity
FROM hospitality_technology.services s
JOIN hospitality_technology.service_orders o ON s.service_id = o.service_id
GROUP BY s.service_name
ORDER BY total_quantity DESC
LIMIT 5;

[User] Now filter those to only include services in the 'Food & Beverage' category and sort by total_quantity descending.

[Assistant]
SELECT s.service_name,
       SUM(o.quantity) AS total_quantity
FROM hospitality_technology.services s
JOIN hospitality_technology.service_orders o ON s.service_id = o.service_id
WHERE s.category = 'Food & Beverage'
GROUP BY s.service_name
ORDER BY total_quantity DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.prescriptions (
    prescription_id character varying(64) NOT NULL, -- unique identifier for the prescription
    record_id character varying(64) NOT NULL, -- FK linking to the medical record where it was prescribed
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to prescribing doctor
    medication_id character varying(64) NOT NULL, -- FK to medications table
    dosage character varying(100) NOT NULL, -- e.g., '100mg', '1 tablet'
    frequency character varying(100) NOT NULL, -- e.g., 'Once daily', 'Twice a day with meals'
    route character varying(50), -- e.g., 'Oral', 'Topical', 'Intravenous'
    start_date date NOT NULL, -- date prescription begins
    end_date date, -- date prescription ends (if applicable)
    quantity_dispensed numeric(10,2), -- amount dispensed (e.g., number of tablets)
    refills_allowed integer NOT NULL DEFAULT 0, -- number of allowed refills
    prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (prescription_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] List all patients along with their primary insurance plan name and the first and last name of their prescribing doctor for any prescription they have received.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, ip.plan_name AS primary_insurance_plan, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
LEFT JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id AND pi.is_primary = true
LEFT JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
LEFT JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
LEFT JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id;

[User] Only include patients whose insurance plan type is 'EPO' and prescriptions issued after January 1st, 2023.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, ip.plan_name AS primary_insurance_plan, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
LEFT JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id AND pi.is_primary = true
LEFT JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
LEFT JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id AND pr.prescription_date >= '2023-01-01'
LEFT JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id
WHERE ip.plan_type = 'EPO';

[User] Add the prescription's medication_id and dosage to the results, and sort by prescription_date descending.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, ip.plan_name AS primary_insurance_plan, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name, pr.medication_id, pr.dosage, pr.prescription_date
FROM healthcare.patients p
LEFT JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id AND pi.is_primary = true
LEFT JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
LEFT JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id AND pr.prescription_date >= '2023-01-01'
LEFT JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id
WHERE ip.plan_type = 'EPO'
ORDER BY pr.prescription_date DESC;


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 gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )

[User] List each player's most recent achievement unlock, showing the player_id, achievement_id, and unlocked_at timestamp.

[Assistant] SELECT pa.player_id, pa.achievement_id, pa.unlocked_at FROM gaming_technology.player_achievements pa INNER JOIN (SELECT player_id, MAX(unlocked_at) AS max_unlocked FROM gaming_technology.player_achievements GROUP BY player_id) sub ON pa.player_id = sub.player_id AND pa.unlocked_at = sub.max_unlocked;

[User] I got duplicate rows for some players who unlocked multiple achievements at the exact same time. Can you make sure to include all such achievements for the player, but if that's the case, list one row per achievement?

[Assistant] SELECT pa.player_id, pa.achievement_id, pa.unlocked_at FROM gaming_technology.player_achievements pa INNER JOIN (SELECT player_id, MAX(unlocked_at) AS max_unlocked FROM gaming_technology.player_achievements GROUP BY player_id) sub ON pa.player_id = sub.player_id AND pa.unlocked_at = sub.max_unlocked;

[User] Instead, for each player, just show the total number of achievements unlocked on their most recent unlock timestamp.

[Assistant] SELECT pa.player_id, pa.unlocked_at AS most_recent_unlocked_at, COUNT(*) AS achievements_on_latest_time FROM gaming_technology.player_achievements pa INNER JOIN (SELECT player_id, MAX(unlocked_at) AS max_unlocked FROM gaming_technology.player_achievements GROUP BY player_id) sub ON pa.player_id = sub.player_id AND pa.unlocked_at = sub.max_unlocked GROUP BY pa.player_id, pa.unlocked_at;

[User] Now filter to only show players where achievements_on_latest_time is greater than 1.

[Assistant] SELECT pa.player_id, pa.unlocked_at AS most_recent_unlocked_at, COUNT(*) AS achievements_on_latest_time FROM gaming_technology.player_achievements pa INNER JOIN (SELECT player_id, MAX(unlocked_at) AS max_unlocked FROM gaming_technology.player_achievements GROUP BY player_id) sub ON pa.player_id = sub.player_id AND pa.unlocked_at = sub.max_unlocked GROUP BY pa.player_id, pa.unlocked_at HAVING COUNT(*) > 1;


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 hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.guests (
    guest_id character varying(64) NOT NULL,  -- unique identifier for the guest profile
    first_name character varying(100) NOT NULL, -- guest's first name
    last_name character varying(100) NOT NULL, -- guest's last name
    email character varying(255) UNIQUE, -- guest's email address (unique identifier?)
    phone_number character varying(30), -- guest's phone number
    date_of_birth date, -- guest's date of birth
    address_line1 character varying(255), -- guest's home address
    city character varying(100),
    state_province character varying(100),
    postal_code character varying(20),
    country_code character varying(3),
    preferences text, -- notes on guest preferences (e.g., allergies, room location)
    loyalty_member_id character varying(64) UNIQUE, -- FK to loyalty_members table
    communication_consent boolean DEFAULT true, -- consent for marketing communications
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (guest_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.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.reviews (
    review_id character varying(64) NOT NULL,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    PRIMARY KEY (review_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id)
)

[User] Show me each property and the average rating_service from reviews posted in the last year.

[Assistant]
SELECT p.property_name,
       AVG(rw.rating_service) AS avg_rating_service
FROM hospitality_technology.properties p
JOIN hospitality_technology.reviews rw ON p.property_id = rw.property_id
WHERE rw.review_date >= current_date - INTERVAL '1 year'
GROUP BY p.property_name;

[User] Exclude properties with fewer than 10 reviews in that period and order by avg_rating_service descending.

[Assistant]
SELECT p.property_name,
       AVG(rw.rating_service) AS avg_rating_service,
       COUNT(rw.review_id) AS review_count
FROM hospitality_technology.properties p
JOIN hospitality_technology.reviews rw ON p.property_id = rw.property_id
WHERE rw.review_date >= current_date - INTERVAL '1 year'
GROUP BY p.property_name
HAVING COUNT(rw.review_id) >= 10
ORDER BY avg_rating_service DESC;


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 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] Give me all trips where the trip status is 'Completed' with their trip ID, vehicle ID, and number of passengers.

[Assistant] SELECT trip_id, vehicle_id, passenger_count FROM transportation.trips WHERE status = 'Completed';

[User] Now, also include the scheduled and actual arrival times.

[Assistant] SELECT trip_id, vehicle_id, passenger_count, scheduled_arrival, actual_arrival FROM transportation.trips WHERE status = 'Completed';

[User] I want to filter out trips that had zero passengers.

[Assistant] SELECT trip_id, vehicle_id, passenger_count, scheduled_arrival, actual_arrival FROM transportation.trips WHERE status = 'Completed' AND passenger_count > 0;

[User] Actually, can you also include the driver ID in the output?

[Assistant] SELECT trip_id, vehicle_id, driver_id, passenger_count, scheduled_arrival, actual_arrival FROM transportation.trips WHERE status = 'Completed' AND passenger_count > 0;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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 character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
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, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, 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 character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, 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] I want to see each user's username and the number of posts they've made that include a media attachment of type 'image'.

[Assistant]
SELECT u.username, COUNT(*) AS image_post_count
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.media_url IS NOT NULL
  AND p.media_type = 'image'
GROUP BY u.username;

[User] Only include users with more than 2 image posts.

[Assistant]
SELECT u.username, COUNT(*) AS image_post_count
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.media_url IS NOT NULL
  AND p.media_type = 'image'
GROUP BY u.username
HAVING COUNT(*) > 2;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.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] List all products, showing their ID, name, type, and whether they are active.

[Assistant] SELECT product_id, product_name, product_type, is_active FROM insurance.insurance_products;

[User] Now, only show me products of type 'Auto' or 'Home'.

[Assistant] SELECT product_id, product_name, product_type, is_active FROM insurance.insurance_products WHERE product_type IN ('Auto', 'Home');

[User] Also, only include those products that have a base premium greater than 750.

[Assistant] SELECT product_id, product_name, product_type, is_active FROM insurance.insurance_products WHERE product_type IN ('Auto', 'Home') AND base_premium > 750;

[User] Great, but just show the product name and base premium for those results, ordered by base premium descending.

[Assistant] SELECT product_name, base_premium FROM insurance.insurance_products WHERE product_type IN ('Auto', 'Home') AND base_premium > 750 ORDER BY base_premium DESC;


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 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.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id uuid PRIMARY KEY, game_id uuid, server_name text, region text, ip_address text, port int, current_players int, max_players int, status text, last_heartbeat 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 PRIMARY KEY, player_id uuid, achievement_id uuid, unlocked_at timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, 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 PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )

[User] Find all in-game items that have a 'mana_cost' attribute in their attributes JSON. Show the item ID, item name, and the value of the 'mana_cost'.

[Assistant] SELECT item_id, item_name, attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items WHERE attributes ? 'mana_cost'

[User] Now, only include items where the 'mana_cost' is greater than 50.

[Assistant] SELECT item_id, item_name, attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items WHERE attributes ? 'mana_cost' AND (attributes ->> 'mana_cost')::int > 50

[User] Add the item's rarity and the title of the game it belongs to in the output.

[Assistant] SELECT t1.item_id, t1.item_name, t1.rarity, t2.title, t1.attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items AS t1 JOIN gaming_technology.games AS t2 ON t1.game_id = t2.game_id WHERE t1.attributes ? 'mana_cost' AND (t1.attributes ->> 'mana_cost')::int > 50

[User] Filter the results to only include items from games in the 'Fantasy' genre.

[Assistant] SELECT t1.item_id, t1.item_name, t1.rarity, t2.title, t1.attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items AS t1 JOIN gaming_technology.games AS t2 ON t1.game_id = t2.game_id WHERE t1.attributes ? 'mana_cost' AND (t1.attributes ->> 'mana_cost')::int > 50 AND t2.genre = 'Fantasy'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)

[User] For each customer, show the number of open accounts and their combined balance, joining the accounts table with itself on customer_id for demonstration.

[Assistant]
SELECT a.customer_id, COUNT(a.account_id) AS open_accounts_count, SUM(a.balance) AS combined_balance
FROM financial_services.accounts a
WHERE a.status = 'Open'
GROUP BY a.customer_id;

[User] I got an error, can you show how to join the table to itself even though we are just using one source of data?

[Assistant]
SELECT a.customer_id, COUNT(a.account_id) AS open_accounts_count, SUM(a.balance) AS combined_balance
FROM financial_services.accounts a
JOIN financial_services.accounts b ON a.customer_id = b.customer_id
WHERE a.status = 'Open'
GROUP BY a.customer_id;

[User] Now, only show those customers who have more than 2 open accounts.

[Assistant]
SELECT a.customer_id, COUNT(a.account_id) AS open_accounts_count, SUM(a.balance) AS combined_balance
FROM financial_services.accounts a
JOIN financial_services.accounts b ON a.customer_id = b.customer_id
WHERE a.status = 'Open'
GROUP BY a.customer_id
HAVING COUNT(a.account_id) > 2;


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

[User] List the product_id, product_name, and base_premium for all products that are currently inactive.

[Assistant]
SELECT product_id, product_name, base_premium
FROM insurance.insurance_products
WHERE is_active = false;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.agents (
    agent_id character varying(64) NOT NULL, -- unique identifier for the agent
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    agency_name character varying(150),
    license_number character varying(100) NOT NULL UNIQUE, -- state insurance license number
    license_state character varying(50) NOT NULL,
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(30),
    hire_date date,
    termination_date date,
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Terminated, On Leave
    commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, -- percentage commission
    manager_id character varying(64), -- identifier for the agent's manager (FK to agents or employees)
    PRIMARY KEY (agent_id)
)
CREATE TABLE insurance.claim_documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document
    claim_id character varying(64) NOT NULL, -- identifier of the claim this document relates to (FK to claims)
    document_type character varying(50) NOT NULL, -- e.g., Police Report, Photo, Invoice, Medical Bill
    file_name character varying(255) NOT NULL, -- original name of the uploaded file
    file_path character varying(512) NOT NULL, -- storage path (e.g., S3 URL, network path)
    file_size_bytes integer, -- size of the file in bytes
    mime_type character varying(100), -- MIME type of the file (e.g., 'image/jpeg', 'application/pdf')
    uploaded_by character varying(64), -- identifier of the user/system who uploaded (FK to users/customers)
    uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- time of upload
    description text, -- optional description of the document
    PRIMARY KEY (document_id)
)
CREATE TABLE insurance.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)

[User] List all insurance products that have not been updated in the past year. Include product_id, product_name, and updated_at, and order by updated_at ascending.

[Assistant]
SELECT product_id, product_name, updated_at
FROM insurance.insurance_products
WHERE updated_at IS NULL
   OR updated_at < CURRENT_DATE - INTERVAL '1 year'
ORDER BY updated_at ASC;


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 legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id text, first_name text, last_name text, bar_number text, firm_id text, email text, phone text, specialization text, hire_date timestamp, is_partner boolean )

[User] Find all clients and lawyers who share the same phone area code, and show each client's first and last name, each lawyer's first and last name, and the shared area code.

[Assistant] SELECT c.first_name AS client_first_name, c.last_name AS client_last_name, l.first_name AS lawyer_first_name, l.last_name AS lawyer_last_name, SUBSTRING(c.phone, 1, 3) AS area_code FROM legal_services.clients c JOIN legal_services.lawyers l ON SUBSTRING(c.phone, 1, 3) = SUBSTRING(l.phone, 1, 3);


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.transactions ( transaction_id text, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.smart_contracts ( contract_id text, creator_address text, code text, timestamp timestamp )

[User] I want to know how many times each smart contract has been invoked by transactions; also include the contract creator.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(t.transaction_id) AS invocation_count
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
GROUP BY sc.contract_id, sc.creator_address;

[User] I'd like to see only contracts with more than 100 invocations.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(t.transaction_id) AS invocation_count
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
GROUP BY sc.contract_id, sc.creator_address
HAVING COUNT(t.transaction_id) > 100;

[User] Actually, I want to order them by invocation_count descending and limit to the top 5.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(t.transaction_id) AS invocation_count
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
GROUP BY sc.contract_id, sc.creator_address
HAVING COUNT(t.transaction_id) > 100
ORDER BY invocation_count DESC
LIMIT 5;

[User] Also, show the timestamp when each of those top 5 contracts was created.

[Assistant]
SELECT sc.contract_id, sc.creator_address, sc.timestamp AS creation_time, COUNT(t.transaction_id) AS invocation_count
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
GROUP BY sc.contract_id, sc.creator_address, sc.timestamp
HAVING COUNT(t.transaction_id) > 100
ORDER BY invocation_count DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text PRIMARY KEY, case_number text UNIQUE, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )

[User] I need the case_number and case_name along with the total billing amount (hours_spent * billing_rate) for cases that are currently open.

[Assistant]
SELECT c.case_number, c.case_name, SUM(te.hours_spent * te.billing_rate) AS total_billing
FROM legal_services.cases c
JOIN legal_services.time_entries te ON c.case_id = te.case_id
WHERE c.status = 'Open'
GROUP BY c.case_number, c.case_name;

[User] Now order the results by total_billing in descending order and limit to the top 5.

[Assistant]
SELECT c.case_number, c.case_name, SUM(te.hours_spent * te.billing_rate) AS total_billing
FROM legal_services.cases c
JOIN legal_services.time_entries te ON c.case_id = te.case_id
WHERE c.status = 'Open'
GROUP BY c.case_number, c.case_name
ORDER BY total_billing DESC
LIMIT 5;


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

[User] List the medication_id, medication_name, and description for all medications whose generic_name starts with 'A'.

[Assistant]
SELECT medication_id, medication_name, description
FROM healthcare.medications
WHERE generic_name LIKE 'A%';


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

[User] List each conversation_id and the number of unread messages (where read_at is null).

[Assistant] SELECT m.conversation_id, COUNT(*) AS unread_messages FROM social_media.messages m WHERE m.read_at IS NULL GROUP BY m.conversation_id;

[User] Now only include group chats and show the group_name.

[Assistant] SELECT c.conversation_id, c.group_name, COUNT(m.message_id) AS unread_messages FROM social_media.conversations c JOIN social_media.messages m ON c.conversation_id = m.conversation_id WHERE c.is_group_chat = true AND m.read_at IS NULL GROUP BY c.conversation_id, c.group_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )

[User] For each customer, calculate the average number of days between their consecutive premium payments.

[Assistant]
SELECT t.customer_id,
       AVG(t.days_diff) AS avg_days_between
FROM (
  SELECT p1.customer_id,
         EXTRACT(DAY FROM p2.payment_date - p1.payment_date) AS days_diff
  FROM insurance.premium_payments p1
  JOIN insurance.premium_payments p2
    ON p1.customer_id = p2.customer_id
   AND p2.payment_date > p1.payment_date
) AS t
GROUP BY t.customer_id;

[User] Exclude any payments that are not 'Completed'.

[Assistant]
SELECT t.customer_id,
       AVG(t.days_diff) AS avg_days_between
FROM (
  SELECT p1.customer_id,
         EXTRACT(DAY FROM p2.payment_date - p1.payment_date) AS days_diff
  FROM insurance.premium_payments p1
  JOIN insurance.premium_payments p2
    ON p1.customer_id = p2.customer_id
   AND p2.payment_date > p1.payment_date
  WHERE p1.status = 'Completed'
    AND p2.status = 'Completed'
) AS t
GROUP BY t.customer_id;

[User] Only include customers whose average days between payments is greater than 30 and show that value.

[Assistant]
SELECT customer_id,
       AVG(days_diff) AS avg_days_between
FROM (
  SELECT p1.customer_id,
         EXTRACT(DAY FROM p2.payment_date - p1.payment_date) AS days_diff
  FROM insurance.premium_payments p1
  JOIN insurance.premium_payments p2
    ON p1.customer_id = p2.customer_id
   AND p2.payment_date > p1.payment_date
  WHERE p1.status = 'Completed'
    AND p2.status = 'Completed'
) AS t
GROUP BY customer_id
HAVING AVG(days_diff) > 30;

[User] Limit the result to the top 5 customers by average days between payments in descending order.

[Assistant]
SELECT customer_id,
       AVG(days_diff) AS avg_days_between
FROM (
  SELECT p1.customer_id,
         EXTRACT(DAY FROM p2.payment_date - p1.payment_date) AS days_diff
  FROM insurance.premium_payments p1
  JOIN insurance.premium_payments p2
    ON p1.customer_id = p2.customer_id
   AND p2.payment_date > p1.payment_date
  WHERE p1.status = 'Completed'
    AND p2.status = 'Completed'
) AS t
GROUP BY customer_id
HAVING AVG(days_diff) > 30
ORDER BY avg_days_between DESC
LIMIT 5;


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

[User] For each game, which server has hosted the most sessions?

[Assistant] SELECT game_id, server_id, COUNT(*) AS session_count FROM gaming_technology.game_sessions GROUP BY game_id, server_id;

[User] I want the server with the highest session count per game, not all servers.

[Assistant] SELECT t.game_id, t.server_id, t.session_count FROM (SELECT game_id, server_id, COUNT(*) AS session_count, RANK() OVER (PARTITION BY game_id ORDER BY COUNT(*) DESC) AS rnk FROM gaming_technology.game_sessions GROUP BY game_id, server_id) t WHERE t.rnk = 1;

[User] If two servers have the same highest count for a game, will both be shown?

[Assistant] Yes, the RANK() function ensures all servers tied for the highest session count per game are shown. The SQL will return all such tied servers for each game where they share the top session count.

[User] Can you also show the total duration of all sessions for the top server(s) per game?

[Assistant] WITH top_servers AS (SELECT game_id, server_id, COUNT(*) AS session_count, RANK() OVER (PARTITION BY game_id ORDER BY COUNT(*) DESC) AS rnk FROM gaming_technology.game_sessions GROUP BY game_id, server_id) SELECT ts.game_id, ts.server_id, ts.session_count, SUM(gs.duration_seconds) AS total_duration FROM top_servers ts JOIN gaming_technology.game_sessions gs ON ts.game_id = gs.game_id AND ts.server_id = gs.server_id WHERE ts.rnk = 1 GROUP BY ts.game_id, ts.server_id, ts.session_count;


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 legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )

[User] List all appointments handled by lawyers from law firms founded after 2015, showing the appointment subject and the lawyer's firm name.

[Assistant]
SELECT a.subject, f.firm_name
FROM legal_services.appointments a
JOIN legal_services.lawyers l ON a.lawyer_id = l.lawyer_id
JOIN legal_services.law_firms f ON l.firm_id = f.firm_id
WHERE f.founded_date > '2015-12-31';

[User] Actually, only include appointments with status 'Scheduled'.

[Assistant]
SELECT a.subject, f.firm_name
FROM legal_services.appointments a
JOIN legal_services.lawyers l ON a.lawyer_id = l.lawyer_id
JOIN legal_services.law_firms f ON l.firm_id = f.firm_id
WHERE f.founded_date > '2015-12-31' AND a.status = 'Scheduled';

[User] Also, include the lawyer's first and last name in the results.

[Assistant]
SELECT a.subject, f.firm_name, l.first_name, l.last_name
FROM legal_services.appointments a
JOIN legal_services.lawyers l ON a.lawyer_id = l.lawyer_id
JOIN legal_services.law_firms f ON l.firm_id = f.firm_id
WHERE f.founded_date > '2015-12-31' AND a.status = 'Scheduled';


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 government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    application_id character varying(64), -- FK to applications table (optional)
    message_subject character varying(255),
    message_body text NOT NULL,
    channel character varying(30) NOT NULL, -- e.g., Email, SMS, Portal Message, Mail
    sent_at timestamp NOT NULL,
    status character varying(30) NOT NULL, -- e.g., Queued, Sent, Delivered, Failed, Read
    related_entity_type character varying(50), -- e.g., Application, Appointment, Document Request
    related_entity_id character varying(64), -- ID of the related entity
    PRIMARY KEY (notification_id)
)

[User] Retrieve the agency name and the most recent notification sent date for each agency, considering only notifications related to agencies.

[Assistant]
SELECT a.agency_name, MAX(n.sent_at) AS last_notification_date
FROM government_services.agencies a
JOIN government_services.notifications n
  ON n.related_entity_type = 'Agency'
  AND n.related_entity_id = a.agency_id
GROUP BY a.agency_name;


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 legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)

[User] Get me all unbilled billable time entries with their entry_id, case_id, lawyer_id, hours_spent, and billing_rate.

[Assistant]
SELECT entry_id,
       case_id,
       lawyer_id,
       hours_spent,
       billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE;

[User] Actually, I only want entries for lawyer 'lawyer_123'.

[Assistant]
SELECT entry_id,
       case_id,
       lawyer_id,
       hours_spent,
       billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND lawyer_id = 'lawyer_123';

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

[Assistant]
SELECT entry_id,
       case_id,
       lawyer_id,
       hours_spent,
       billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND lawyer_id = 'lawyer_123'
ORDER BY hours_spent DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )

[User] How many beneficiaries are there for each relationship type?

[Assistant]
SELECT relationship,
       COUNT(*) AS beneficiary_count
FROM insurance.policy_beneficiaries
GROUP BY relationship;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )

[User] List all policies that expired in the last 30 days, along with their product IDs and premium amounts.

[Assistant] SELECT policy_id, product_id, premium_amount FROM insurance.policies WHERE end_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND CURRENT_DATE AND status = 'expired';

[User] Now include only policies that had a deductible of $1000 or more.

[Assistant] SELECT policy_id, product_id, premium_amount, deductible FROM insurance.policies WHERE end_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND CURRENT_DATE AND status = 'expired' AND deductible >= 1000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.agents (
    agent_id character varying(64) NOT NULL, -- unique identifier for the agent
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    agency_name character varying(150),
    license_number character varying(100) NOT NULL UNIQUE, -- state insurance license number
    license_state character varying(50) NOT NULL,
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(30),
    hire_date date,
    termination_date date,
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Terminated, On Leave
    commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, -- percentage commission
    manager_id character varying(64), -- identifier for the agent's manager (FK to agents or employees)
    PRIMARY KEY (agent_id)
)
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
CREATE TABLE insurance.claim_documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document
    claim_id character varying(64) NOT NULL, -- identifier of the claim this document relates to (FK to claims)
    document_type character varying(50) NOT NULL, -- e.g., Police Report, Photo, Invoice, Medical Bill
    file_name character varying(255) NOT NULL, -- original name of the uploaded file
    file_path character varying(512) NOT NULL, -- storage path (e.g., S3 URL, network path)
    file_size_bytes integer, -- size of the file in bytes
    mime_type character varying(100), -- MIME type of the file (e.g., 'image/jpeg', 'application/pdf')
    uploaded_by character varying(64), -- identifier of the user/system who uploaded (FK to users/customers)
    uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- time of upload
    description text, -- optional description of the document
    PRIMARY KEY (document_id)
)
CREATE TABLE insurance.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)

[User] Show me all active policies with coverage limits above $1,000,000, along with the customer names and agent names, sorted by coverage limit in descending order.

[Assistant] SELECT p.policy_id, p.policy_number, p.coverage_limit, c.first_name AS customer_first_name, c.last_name AS customer_last_name, a.first_name AS agent_first_name, a.last_name AS agent_last_name FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.agents a ON p.agent_id = a.agent_id WHERE p.status = 'Active' AND p.coverage_limit > 1000000 ORDER BY p.coverage_limit DESC;

[User] Actually, I only want to see policies that started in the last year and have a deductible of $1000 or more.

[Assistant] SELECT p.policy_id, p.policy_number, p.coverage_limit, p.deductible, c.first_name AS customer_first_name, c.last_name AS customer_last_name, a.first_name AS agent_first_name, a.last_name AS agent_last_name FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.agents a ON p.agent_id = a.agent_id WHERE p.status = 'Active' AND p.coverage_limit > 1000000 AND p.start_date >= CURRENT_DATE - INTERVAL '1 year' AND p.deductible >= 1000 ORDER BY p.coverage_limit DESC;

[User] Now include the count of claims each of these policies has had.

[Assistant] SELECT p.policy_id, p.policy_number, p.coverage_limit, p.deductible, c.first_name AS customer_first_name, c.last_name AS customer_last_name, a.first_name AS agent_first_name, a.last_name AS agent_last_name, COUNT(cl.claim_id) AS claim_count FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.agents a ON p.agent_id = a.agent_id LEFT JOIN insurance.claims cl ON p.policy_id = cl.policy_id WHERE p.status = 'Active' AND p.coverage_limit > 1000000 AND p.start_date >= CURRENT_DATE - INTERVAL '1 year' AND p.deductible >= 1000 GROUP BY p.policy_id, p.policy_number, p.coverage_limit, p.deductible, c.first_name, c.last_name, a.first_name, a.last_name ORDER BY p.coverage_limit DESC;

[User] Finally, order the results by claim count in descending order and then by coverage limit in descending order.

[Assistant] SELECT p.policy_id, p.policy_number, p.coverage_limit, p.deductible, c.first_name AS customer_first_name, c.last_name AS customer_last_name, a.first_name AS agent_first_name, a.last_name AS agent_last_name, COUNT(cl.claim_id) AS claim_count FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.agents a ON p.agent_id = a.agent_id LEFT JOIN insurance.claims cl ON p.policy_id = cl.policy_id WHERE p.status = 'Active' AND p.coverage_limit > 1000000 AND p.start_date >= CURRENT_DATE - INTERVAL '1 year' AND p.deductible >= 1000 GROUP BY p.policy_id, p.policy_number, p.coverage_limit, p.deductible, c.first_name, c.last_name, a.first_name, a.last_name ORDER BY claim_count DESC, p.coverage_limit DESC;


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 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 character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
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, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, 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 character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, 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] I want to see each user's username and the number of posts they've made that include a media attachment of type 'image'.

[Assistant]
SELECT u.username, COUNT(*) AS image_post_count
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.media_url IS NOT NULL
  AND p.media_type = 'image'
GROUP BY u.username;

[User] Only include users with more than 2 image posts.

[Assistant]
SELECT u.username, COUNT(*) AS image_post_count
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.media_url IS NOT NULL
  AND p.media_type = 'image'
GROUP BY u.username
HAVING COUNT(*) > 2;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Collection 'assembly_steps'. Document structure: { _id: <ObjectId (or step_id)>, step_id: String, line_id: String (reference), step_number: NumberInt, step_name: String, description: String, standard_duration_hours: Decimal128, required_skill_level: String, workstation: String }. Required: step_id, line_id, step_number, step_name. Index on line_id, step_number.
Collection 'employees'. Document structure: { _id: <ObjectId (or employee_id)>, employee_id: String, first_name: String, last_name: String, job_title: String, skill_certifications: [String], hire_date: ISODate, assigned_line_id: String (reference, optional), employment_status: String, supervisor_employee_id: String (reference, optional) }. Required: employee_id, first_name, last_name, job_title, hire_date, employment_status.

[User] 特定の組み立てラインに関連するすべての手順を取得したいです。ラインIDと手順名、手順番号、必要なスキルレベルを含めてください。

[Assistant]
db.assembly_steps.find(
    { line_id: '<specific_line_id>' },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] さらに、必要なスキルレベルが「Senior Technician」以上の手順だけを表示できますか？

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician'
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 標準作業時間が3時間以上の手順も条件に追加できますか？

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician',
        standard_duration_hours: { $gte: 3 }
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 最後に、作業場所が「Workstation_B」の手順だけに絞り込んでください。

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician',
        standard_duration_hours: { $gte: 3 },
        workstation: 'Workstation_B'
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })


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 trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] Show me the user ID and the total count of wallets associated with each user who owns at least one wallet.

[Assistant] SELECT T1.user_id, COUNT(T2.wallet_id) FROM trading_platform.users AS T1 JOIN trading_platform.wallets AS T2 ON T1.user_id = T2.user_id GROUP BY 1;

[User] Filter the results to only include users who have more than 3 wallets.

[Assistant] SELECT T1.user_id, COUNT(T2.wallet_id) FROM trading_platform.users AS T1 JOIN trading_platform.wallets AS T2 ON T1.user_id = T2.user_id GROUP BY 1 HAVING COUNT(T2.wallet_id) > 3;


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.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id character varying(64) NOT NULL, contract_address character varying(128) NOT NULL, token_name character varying(128) NOT NULL, token_symbol character varying(32) NOT NULL, decimals integer NOT NULL, total_supply numeric(38,14) NOT NULL, PRIMARY KEY (token_id) )
CREATE TABLE web3.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )

[User] Show the number of wallets created for each user. Return user_id and wallet_count.

[Assistant]
SELECT user_id, COUNT(*) AS wallet_count
FROM web3.wallets
GROUP BY user_id;

[User] Now, can you only show users with more than 2 wallets in the result?

[Assistant]
SELECT user_id, COUNT(*) AS wallet_count
FROM web3.wallets
GROUP BY user_id
HAVING COUNT(*) > 2;