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 text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id.text, 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.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
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
)

[User] Which users joined conversations that are NOT group chats after May 1, 2024? Return their usernames and the conversation IDs.

[Assistant]
SELECT u.username, cp.conversation_id
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = false AND cp.joined_at > '2024-05-01';

[User] Now, also include the time they joined and the full name of the user.

[Assistant]
SELECT u.username, u.full_name, cp.conversation_id, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = false AND cp.joined_at > '2024-05-01';

[User] Only show users whose email ends with '.org' and order the results by joined_at descending.

[Assistant]
SELECT u.username, u.full_name, cp.conversation_id, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = false AND cp.joined_at > '2024-05-01' AND u.email LIKE '%.org'
ORDER BY cp.joined_at 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 hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.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)
)

[User] For each property, list the property name and the count of payments processed.

[Assistant]
SELECT
  prop.property_name,
  COUNT(p.payment_id) AS payment_count
FROM hospitality_technology.properties AS prop
JOIN hospitality_technology.reservations AS r ON prop.property_id = r.property_id -- Assuming reservations links properties and payments
JOIN hospitality_technology.payments AS p ON r.reservation_id = p.reservation_id
GROUP BY
  prop.property_name
ORDER BY
  payment_count DESC;

[User] Filter the list to only include properties that have processed more than 20 payments.

[Assistant]
SELECT
  prop.property_name,
  COUNT(p.payment_id) AS payment_count
FROM hospitality_technology.properties AS prop
JOIN hospitality_technology.reservations AS r ON prop.property_id = r.property_id
JOIN hospitality_technology.payments AS p ON r.reservation_id = p.reservation_id
GROUP BY
  prop.property_name
HAVING
  COUNT(p.payment_id) > 20
ORDER BY
  payment_count DESC;

[User] Actually, instead of the count, show the average payment amount for these properties, still limited to properties with more than 20 payments.

[Assistant]
SELECT
  prop.property_name,
  AVG(p.amount) AS average_payment_amount
FROM hospitality_technology.properties AS prop
JOIN hospitality_technology.reservations AS r ON prop.property_id = r.property_id
JOIN hospitality_technology.payments AS p ON r.reservation_id = p.reservation_id
GROUP BY
  prop.property_name
HAVING
  COUNT(p.payment_id) > 20
ORDER BY
  average_payment_amount 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 hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] For each overall rating level (1-5), count how many reviews received that rating.

[Assistant] SELECT rating_overall, COUNT(*) FROM reviews GROUP BY rating_overall ORDER BY rating_overall;

[User] Only show ratings with more than 100 reviews and sort by the count descending.

[Assistant] SELECT rating_overall, COUNT(*) FROM reviews GROUP BY rating_overall HAVING COUNT(*) > 100 ORDER BY COUNT(*) 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 healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] Show me the number of primary insurance policies per insurance provider, including the provider name and the count.

[Assistant]
SELECT ip.insurance_provider, COUNT(*) AS primary_policy_count
FROM healthcare.patient_insurance pi
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE pi.is_primary = TRUE
GROUP BY ip.insurance_provider;

[User] Can you also show the breakdown by plan type within each insurance provider?

[Assistant]
SELECT ip.insurance_provider, ip.plan_type, COUNT(*) AS primary_policy_count
FROM healthcare.patient_insurance pi
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE pi.is_primary = TRUE
GROUP BY ip.insurance_provider, ip.plan_type;

[User] Actually, only include insurance providers where the total number of primary policies is greater than 5.

[Assistant]
SELECT provider_stats.insurance_provider, ip.plan_type, COUNT(*) AS primary_policy_count
FROM healthcare.patient_insurance pi
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
JOIN (
  SELECT ip2.insurance_provider
  FROM healthcare.patient_insurance pi2
  JOIN healthcare.insurance_plans ip2 ON pi2.plan_id = ip2.plan_id
  WHERE pi2.is_primary = TRUE
  GROUP BY ip2.insurance_provider
  HAVING COUNT(*) > 5
) AS provider_stats ON ip.insurance_provider = provider_stats.insurance_provider
WHERE pi.is_primary = TRUE
GROUP BY provider_stats.insurance_provider, ip.plan_type;

[User] Instead, only include primary policies that have not expired yet (expiration_date IS NULL or expiration_date > CURRENT_DATE).

[Assistant]
SELECT provider_stats.insurance_provider, ip.plan_type, COUNT(*) AS primary_policy_count
FROM healthcare.patient_insurance pi
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
JOIN (
  SELECT ip2.insurance_provider
  FROM healthcare.patient_insurance pi2
  JOIN healthcare.insurance_plans ip2 ON pi2.plan_id = ip2.plan_id
  WHERE pi2.is_primary = TRUE AND (pi2.expiration_date IS NULL OR pi2.expiration_date > CURRENT_DATE)
  GROUP BY ip2.insurance_provider
  HAVING COUNT(*) > 5
) AS provider_stats ON ip.insurance_provider = provider_stats.insurance_provider
WHERE pi.is_primary = TRUE AND (pi.expiration_date IS NULL OR pi.expiration_date > CURRENT_DATE)
GROUP BY provider_stats.insurance_provider, ip.plan_type;


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] Show me the total number of time entries for each case.

[Assistant]
SELECT case_id, COUNT(*) AS entry_count
FROM legal_services.time_entries
GROUP BY case_id;

[User] Only include cases where the total is greater than 10.

[Assistant]
SELECT case_id, COUNT(*) AS entry_count
FROM legal_services.time_entries
GROUP BY case_id
HAVING COUNT(*) > 10;


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.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )

[User] Show me the first and last names of citizens along with their dates of birth and contact emails for all citizens who registered after January 1, 2023.

[Assistant] SELECT first_name, last_name, date_of_birth, contact_email FROM government_services.citizens WHERE registration_date > '2023-01-01';

[User] Only include citizens whose accounts are verified.

[Assistant] SELECT first_name, last_name, date_of_birth, contact_email FROM government_services.citizens WHERE registration_date > '2023-01-01' AND is_verified = true;


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. 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 train_station_management.platforms ( platform_id text, station_id text, platform_number text, track_number text, status text, length_meters numeric, accessible boolean )

[User] What is the maintenance schedule for platform 3 at station DEF for the next month?

[Assistant] I'm sorry, but I don't have access to the maintenance schedule for platforms. The data I have only includes static information about platform details such as ID, station, number, track, status, length, and accessibility. For maintenance schedules, you may need to consult the station management or relevant department.


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.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )
CREATE TABLE transportation.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )

[User] Retrieve the vehicle_id, make, model, and the next_service_due_date for each vehicle based on the most recent maintenance log.

[Assistant] SELECT DISTINCT ON (ml.vehicle_id) v.vehicle_id, v.make, v.model, ml.next_service_due_date FROM transportation.maintenance_logs ml JOIN transportation.vehicles v ON v.vehicle_id = ml.vehicle_id ORDER BY ml.vehicle_id, ml.service_date DESC;

[User] Now, only include vehicles with status 'Active' and whose next_service_due_date is within the next 30 days, ordering by next_service_due_date ascending.

[Assistant] SELECT v.vehicle_id, v.make, v.model, ml.next_service_due_date FROM transportation.vehicles v JOIN (SELECT DISTINCT ON (vehicle_id) vehicle_id, next_service_due_date FROM transportation.maintenance_logs ORDER BY vehicle_id, service_date DESC) ml ON v.vehicle_id = ml.vehicle_id WHERE v.status = 'Active' AND ml.next_service_due_date BETWEEN current_date AND current_date + INTERVAL '30 days' ORDER BY ml.next_service_due_date 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 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)
)

[User] List all staff who report directly to a manager with access_level 5. Include staff full name, position, and the name of their manager.

[Assistant]
SELECT s.staff_id, s.first_name AS staff_first_name, s.last_name AS staff_last_name, s.position, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM hospitality_technology.staff s
JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id
WHERE m.access_level = 5;

[User] Show only those staff who were hired after 2023-01-01.

[Assistant]
SELECT s.staff_id, s.first_name AS staff_first_name, s.last_name AS staff_last_name, s.position, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM hospitality_technology.staff s
JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id
WHERE m.access_level = 5 AND s.hire_date > '2023-01-01';

[User] Also add their work_email in the results, and sort by staff last_name alphabetically.

[Assistant]
SELECT s.staff_id, s.first_name AS staff_first_name, s.last_name AS staff_last_name, s.position, s.work_email, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM hospitality_technology.staff s
JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id
WHERE m.access_level = 5 AND s.hire_date > '2023-01-01'
ORDER BY s.last_name 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 healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)

[User] List all appointments that were marked as 'No-show'. Show appointment ID, patient ID, and appointment time.

[Assistant] SELECT appointment_id, patient_id, appointment_time FROM healthcare.appointments WHERE status = 'No-show';


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

[User] Calculate the total quantity traded for each day in the dataset.

[Assistant] SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at) ORDER BY trade_day;

[User] Could you also include the total trade value (quantity * price) for each day in that report?

[Assistant] SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity, SUM(quantity * price) AS total_daily_value FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at) ORDER BY trade_day;

[User] Now, for each day, show how the total quantity compares to the overall average daily quantity across all days in the dataset.

[Assistant] WITH DailySummary AS (SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at)) SELECT trade_day, total_daily_quantity, total_daily_quantity - AVG(total_daily_quantity) OVER () AS quantity_difference_from_average FROM DailySummary ORDER BY trade_day;

[User] Finally, only show the days where the total quantity was higher than the overall average daily quantity.

[Assistant] WITH DailySummary AS (SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at)) SELECT trade_day, total_daily_quantity FROM DailySummary WHERE total_daily_quantity > (SELECT AVG(total_daily_quantity) FROM DailySummary) ORDER BY trade_day;


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.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] Can you show me all wallet address pairs that are owned by the same user but have different private keys, along with their wallet_ids and user_id?

[Assistant]
SELECT w1.user_id, w1.wallet_id AS wallet_id_1, w1.address AS address_1, w1.private_key AS private_key_1, w2.wallet_id AS wallet_id_2, w2.address AS address_2, w2.private_key AS private_key_2
FROM web3.wallets w1
JOIN web3.wallets w2 ON w1.user_id = w2.user_id AND w1.wallet_id < w2.wallet_id
WHERE w1.private_key <> w2.private_key;


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 text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types (
    room_type_id 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.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews (
    review_id 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] List all service orders, including the service name and quantity, along with the full name of the staff member who placed the order.

[Assistant] SELECT so.order_id, s.service_name, so.quantity, st.first_name, st.last_name FROM hospitality_technology.service_orders AS so JOIN hospitality_technology.services AS s ON so.service_id = s.service_id JOIN hospitality_technology.staff AS st ON so.staff_id_ordered = st.staff_id;

[User] Filter this list to only include orders placed by staff members with position 'Concierge'.

[Assistant] SELECT so.order_id, s.service_name, so.quantity, st.first_name, st.last_name FROM hospitality_technology.service_orders AS so JOIN hospitality_technology.services AS s ON so.service_id = s.service_id JOIN hospitality_technology.staff AS st ON so.staff_id_ordered = st.staff_id WHERE st.position = 'Concierge';


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.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )

[User] Find law firms that share the same managing partner. Show the names of both firms and the managing_partner_id.

[Assistant]
SELECT a.firm_name AS firm1, b.firm_name AS firm2, a.managing_partner_id
FROM legal_services.law_firms a
JOIN legal_services.law_firms b
  ON a.managing_partner_id = b.managing_partner_id
  AND a.firm_id < b.firm_id;

[User] Exclude any pairs where the managing_partner_id is null.

[Assistant]
SELECT a.firm_name AS firm1, b.firm_name AS firm2, a.managing_partner_id
FROM legal_services.law_firms a
JOIN legal_services.law_firms b
  ON a.managing_partner_id = b.managing_partner_id
  AND a.firm_id < b.firm_id
WHERE a.managing_partner_id IS NOT NULL;

[User] Also, sort the results by managing_partner_id and then by the first firm's name.

[Assistant]
SELECT a.firm_name AS firm1, b.firm_name AS firm2, a.managing_partner_id
FROM legal_services.law_firms a
JOIN legal_services.law_firms b
  ON a.managing_partner_id = b.managing_partner_id
  AND a.firm_id < b.firm_id
WHERE a.managing_partner_id IS NOT NULL
ORDER BY a.managing_partner_id, a.firm_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 healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )

[User] I need a list showing each patient along with their current primary insurance policy number and their immediately previous primary policy number.

[Assistant]
SELECT ci.patient_id,
       ci.policy_number AS current_policy,
       pi.policy_number AS previous_policy
FROM healthcare.patient_insurance ci
LEFT JOIN healthcare.patient_insurance pi
  ON ci.patient_id = pi.patient_id
  AND pi.is_primary = TRUE
  AND pi.effective_date < ci.effective_date
WHERE ci.is_primary = TRUE
  AND (ci.expiration_date IS NULL OR ci.expiration_date > CURRENT_DATE)
  AND pi.effective_date = (
      SELECT MAX(pii.effective_date)
      FROM healthcare.patient_insurance pii
      WHERE pii.patient_id = ci.patient_id
        AND pii.is_primary = TRUE
        AND pii.effective_date < ci.effective_date
  );

[User] Actually, I only want to include previous policies that have an expiration_date set.

[Assistant]
SELECT ci.patient_id,
       ci.policy_number AS current_policy,
       pi.policy_number AS previous_policy
FROM healthcare.patient_insurance ci
LEFT JOIN healthcare.patient_insurance pi
  ON ci.patient_id = pi.patient_id
  AND pi.is_primary = TRUE
  AND pi.expiration_date IS NOT NULL
  AND pi.effective_date = (
      SELECT MAX(pii.effective_date)
      FROM healthcare.patient_insurance pii
      WHERE pii.patient_id = ci.patient_id
        AND pii.is_primary = TRUE
        AND pii.expiration_date IS NOT NULL
        AND pii.effective_date < ci.effective_date
  )
WHERE ci.is_primary = TRUE
  AND (ci.expiration_date IS NULL OR ci.expiration_date > CURRENT_DATE);


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.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] Get the total number of participants per conversation along with the number of participants who have private profiles.

[Assistant] SELECT cp.conversation_id, COUNT(cp.user_id) AS total_participants, SUM(CASE WHEN us.private_profile THEN 1 ELSE 0 END) AS private_profile_count FROM social_media.conversation_participants cp LEFT JOIN social_media.user_settings us ON cp.user_id = us.user_id GROUP BY cp.conversation_id;

[User] Exclude conversations with fewer than 3 private profile participants.

[Assistant] SELECT cp.conversation_id, COUNT(cp.user_id) AS total_participants, SUM(CASE WHEN us.private_profile THEN 1 ELSE 0 END) AS private_profile_count FROM social_media.conversation_participants cp LEFT JOIN social_media.user_settings us ON cp.user_id = us.user_id GROUP BY cp.conversation_id HAVING SUM(CASE WHEN us.private_profile THEN 1 ELSE 0 END) >= 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 government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )

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

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

[User] Now exclude jurisdiction levels that have fewer than 5 agencies.

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

[User] Also, show me the average establishment year for those jurisdiction levels.

[Assistant]
SELECT jurisdiction_level,
       COUNT(*) AS agency_count,
       AVG(EXTRACT(YEAR FROM established_date)) AS avg_established_year
FROM government_services.agencies
GROUP BY jurisdiction_level
HAVING COUNT(*) >= 5;

[User] Sort the results by agency_count descending and limit to 3.

[Assistant]
SELECT jurisdiction_level,
       COUNT(*) AS agency_count,
       AVG(EXTRACT(YEAR FROM established_date)) AS avg_established_year
FROM government_services.agencies
GROUP BY jurisdiction_level
HAVING COUNT(*) >= 5
ORDER BY agency_count DESC
LIMIT 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 gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
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, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
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.player_achievements ( player_achievement_id uuid PRIMARY KEY, player_id uuid, achievement_id uuid, unlocked_at timestamptz )

[User] Show me all servers, the title of the game they host, and the name of the game's developer.

[Assistant] SELECT s.server_name, g.title AS game_title, d.name AS developer_name FROM gaming_technology.servers s JOIN gaming_technology.games g ON s.game_id = g.game_id JOIN gaming_technology.developers d ON g.developer_id = d.developer_id;

[User] Now filter this list to only include servers that are currently 'online'.

[Assistant] SELECT s.server_name, g.title AS game_title, d.name AS developer_name FROM gaming_technology.servers s JOIN gaming_technology.games g ON s.game_id = g.game_id JOIN gaming_technology.developers d ON g.developer_id = d.developer_id WHERE s.status = 'online';


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.citizens ( citizen_id.text, national_id_number.text, first_name.text, last_name.text, date_of_birth.date, gender.text, primary_address.text, contact_email.text, contact_phone.text, registration_date.timestamp, is_verified.boolean )
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )

[User] Retrieve the service name and the count of applications currently in 'Under Review' status for each service.

[Assistant]
SELECT s.service_name, COUNT(a.application_id) AS under_review_count
FROM government_services.services s
LEFT JOIN government_services.applications a ON s.service_id = a.service_id AND a.status = 'Under Review'
GROUP BY s.service_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 web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.token_transfers ( transfer_id.text, token_id.text, from_address.text, to_address.text, value.numeric, transaction_id.text, log_index.integer )
CREATE TABLE web3.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE web3.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )

[User] Find the usernames of users who have deployed contracts and list the address of the contract they deployed.

[Assistant] SELECT T1.username, T3.address FROM web3.users AS T1 JOIN web3.wallets AS T2 ON T1.user_id = T2.user_id JOIN web3.contracts AS T3 ON T2.address = T3.deployer_address;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )

[User] Find pairs of servers in the same region where one server's last heartbeat was recorded within the last hour, and the other server's last heartbeat was recorded between 1 and 2 hours ago. Show the server names, regions, and last heartbeat timestamps for both servers in each pair.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.last_heartbeat AS server1_heartbeat, s2.last_heartbeat AS server2_heartbeat FROM gaming_technology.servers AS s1 JOIN gaming_technology.servers AS s2 ON s1.region = s2.region AND s1.server_id != s2.server_id WHERE s1.last_heartbeat IS NOT NULL AND s2.last_heartbeat IS NOT NULL AND s1.last_heartbeat > NOW() - INTERVAL '1 hour' AND s2.last_heartbeat <= NOW() - INTERVAL '1 hour' AND s2.last_heartbeat > NOW() - INTERVAL '2 hours';

[User] Only include pairs where both servers are currently online.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.last_heartbeat AS server1_heartbeat, s2.last_heartbeat AS server2_heartbeat FROM gaming_technology.servers AS s1 JOIN gaming_technology.servers AS s2 ON s1.region = s2.region AND s1.server_id != s2.server_id WHERE s1.last_heartbeat IS NOT NULL AND s2.last_heartbeat IS NOT NULL AND s1.last_heartbeat > NOW() - INTERVAL '1 hour' AND s2.last_heartbeat <= NOW() - INTERVAL '1 hour' AND s2.last_heartbeat > NOW() - INTERVAL '2 hours' AND s1.status = 'online' AND s2.status = 'online';

[User] Could you also filter the list to only show pairs from regions starting with 'us-'?

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.last_heartbeat AS server1_heartbeat, s2.last_heartbeat AS server2_heartbeat FROM gaming_technology.servers AS s1 JOIN gaming_technology.servers AS s2 ON s1.region = s2.region AND s1.server_id != s2.server_id WHERE s1.last_heartbeat IS NOT NULL AND s2.last_heartbeat IS NOT NULL AND s1.last_heartbeat > NOW() - INTERVAL '1 hour' AND s2.last_heartbeat <= NOW() - INTERVAL '1 hour' AND s2.last_heartbeat > NOW() - INTERVAL '2 hours' AND s1.status = 'online' AND s2.status = 'online' AND s1.region LIKE 'us-%';

[User] Order the results by the region ascending, then by the earlier heartbeat timestamp ascending.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.last_heartbeat AS server1_heartbeat, s2.last_heartbeat AS server2_heartbeat FROM gaming_technology.servers AS s1 JOIN gaming_technology.servers AS s2 ON s1.region = s2.region AND s1.server_id != s2.server_id WHERE s1.last_heartbeat IS NOT NULL AND s2.last_heartbeat IS NOT NULL AND s1.last_heartbeat > NOW() - INTERVAL '1 hour' AND s2.last_heartbeat <= NOW() - INTERVAL '1 hour' AND s2.last_heartbeat > NOW() - INTERVAL '2 hours' AND s1.status = 'online' AND s2.status = 'online' AND s1.region LIKE 'us-%' ORDER BY s1.region ASC, s2.last_heartbeat 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 hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] Show me the count of rooms by status.

[Assistant]
SELECT status,
       COUNT(*) AS room_count
FROM hospitality_technology.rooms
GROUP BY status;

[User] Actually, I need that breakdown by property as well.

[Assistant]
SELECT property_id,
       status,
       COUNT(*) AS room_count
FROM hospitality_technology.rooms
GROUP BY property_id, status
ORDER BY property_id, status;


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 erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid.text, blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_balances (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar NOT NULL, -- Token tick
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )

[User] Which ERC1155 NFT contracts have received approval-for-all events, and for each contract, how many total approval events were recorded?

[Assistant] SELECT contract_address, COUNT(*) AS approval_count FROM erc1155_approval_for_all GROUP BY contract_address;

[User] Can you also show how many unique wallet addresses currently hold NFTs from each of these contracts?

[Assistant] SELECT ea.contract_address, COUNT(*) AS approval_count, COUNT(DISTINCT nh.wallet_address) AS holder_count FROM erc1155_approval_for_all ea LEFT JOIN nft_holders nh ON ea.contract_address = nh.contract_address GROUP BY ea.contract_address;

[User] Only include contracts where the holder count is greater than 10, sorted by approval_count descending.

[Assistant] SELECT ea.contract_address, COUNT(*) AS approval_count, COUNT(DISTINCT nh.wallet_address) AS holder_count FROM erc1155_approval_for_all ea LEFT JOIN nft_holders nh ON ea.contract_address = nh.contract_address GROUP BY ea.contract_address HAVING COUNT(DISTINCT nh.wallet_address) > 10 ORDER BY approval_count DESC;

[User] Add a limit to return only the top 10 contracts.

[Assistant] SELECT ea.contract_address, COUNT(*) AS approval_count, COUNT(DISTINCT nh.wallet_address) AS holder_count FROM erc1155_approval_for_all ea LEFT JOIN nft_holders nh ON ea.contract_address = nh.contract_address GROUP BY ea.contract_address HAVING COUNT(DISTINCT nh.wallet_address) > 10 ORDER BY approval_count DESC LIMIT 10;


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.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.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.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] List the names of active services offered by agencies with at least one accessible service location in the state of 'New York'. Show the service name, category, agency name, and the location name.

[Assistant] SELECT T1.service_name, T1.category, T2.agency_name, T3.location_name FROM government_services.services AS T1 JOIN government_services.agencies AS T2 ON T1.agency_id = T2.agency_id JOIN government_services.service_locations AS T3 ON T2.agency_id = T3.agency_id WHERE T1.is_active IS TRUE AND T3.is_accessible IS TRUE AND T3.state = 'New York';


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.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] List all service orders with quantity greater than 3, showing the order ID, total price, and the staff member who placed the order.

[Assistant]
SELECT order_id, total_price, staff_id_ordered
FROM hospitality_technology.service_orders
WHERE quantity > 3;

[User] Please add the delivery timestamp, and only show orders that were actually delivered (delivery_timestamp is not null).

[Assistant]
SELECT order_id, total_price, staff_id_ordered, delivery_timestamp
FROM hospitality_technology.service_orders
WHERE quantity > 3
  AND delivery_timestamp IS NOT NULL;

[User] Now, show only those orders where the delivered staff is different from the ordered staff, and sort by delivery timestamp ascending.

[Assistant]
SELECT order_id, total_price, staff_id_ordered, staff_id_delivered, delivery_timestamp
FROM hospitality_technology.service_orders
WHERE quantity > 3
  AND delivery_timestamp IS NOT NULL
  AND staff_id_ordered <> staff_id_delivered
ORDER BY delivery_timestamp 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 web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )

[User] For each user, what is the average time difference in days between their wallet creations? Return user_id and avg_diff_days.

[Assistant]
WITH diffs AS (
  SELECT
    user_id,
    EXTRACT(EPOCH FROM (created_at - LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at))) / 86400 AS diff_days
  FROM web3.wallets
)
SELECT
  user_id,
  AVG(diff_days) AS avg_diff_days
FROM diffs
WHERE diff_days IS NOT NULL
GROUP BY user_id;

[User] Actually, only include users who have created more than 2 wallets.

[Assistant]
WITH diffs AS (
  SELECT
    user_id,
    EXTRACT(EPOCH FROM (created_at - LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at))) / 86400 AS diff_days
  FROM web3.wallets
)
SELECT
  user_id,
  AVG(diff_days) AS avg_diff_days
FROM diffs
WHERE diff_days IS NOT NULL
GROUP BY user_id
HAVING COUNT(diff_days) > 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 gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )

[User] Show me all servers in the same region that have different statuses. I want to see the server names, regions, and their statuses for each pair.

[Assistant]
SELECT s1.server_name AS server1, s2.server_name AS server2, s1.region, s1.status AS status1, s2.status AS status2
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
  AND s1.server_id <> s2.server_id
  AND s1.status <> s2.status;

[User] Please also include the current_players of both servers in the result.

[Assistant]
SELECT s1.server_name AS server1, s2.server_name AS server2, s1.region, s1.status AS status1, s2.status AS status2, s1.current_players AS server1_current_players, s2.current_players AS server2_current_players
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
  AND s1.server_id <> s2.server_id
  AND s1.status <> s2.status;


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.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )

[User] Calculate the total fuel quantity and total cost consumed for each trip where passenger_count > 50. List trip_id, total_quantity, and total_cost.

[Assistant]
SELECT f.trip_id,
       SUM(f.quantity) AS total_quantity,
       SUM(f.total_cost) AS total_cost
FROM transportation.fuel_logs f
JOIN transportation.trips t
  ON f.trip_id = t.trip_id
WHERE t.passenger_count > 50
GROUP BY f.trip_id;

[User] Also include the vehicle make and model for each trip, and order by total_cost descending.

[Assistant]
SELECT f.trip_id,
       SUM(f.quantity) AS total_quantity,
       SUM(f.total_cost) AS total_cost,
       v.make,
       v.model
FROM transportation.fuel_logs f
JOIN transportation.trips t
  ON f.trip_id = t.trip_id
JOIN transportation.vehicles v
  ON t.vehicle_id = v.vehicle_id
WHERE t.passenger_count > 50
GROUP BY f.trip_id, v.make, v.model
ORDER BY total_cost 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 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.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)

[User] Find all invoices with status 'Paid' where the total amount is between 2000 and 5000. Show invoice number, total amount, issue date, and due date. Sort the results by issue date descending.

[Assistant] SELECT invoice_number, total_amount, issue_date, due_date FROM legal_services.invoices WHERE status = 'Paid' AND total_amount BETWEEN 2000 AND 5000 ORDER BY issue_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 token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances_historical (
    block_number bigint NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract
    amount varchar NOT NULL, -- Wallet's on-chain balance at the corresponding block height
    pk integer NOT NULL  -- Partition key for the table(floor(block_number / 7200))
)
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE sui_coins ( object_id varchar, status varchar, coin_type varchar, balance varchar, owner varchar )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE token_balances (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar NOT NULL, -- Token tick
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_info_avalanche (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(20) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL, -- Address originating the inscription (matches from_address in transactions table)
    minted decimal(38,0) NOT NULL, -- Sum of minted amount
    holders decimal(38,0) NOT NULL, -- Count of holders
    txs decimal(38,0) NOT NULL, -- Count of transactions
    updated_timestamp timestamp(3) NOT NULL, -- Timestamp of update
    completed_timestamp timestamp(3) NOT NULL, -- Timestamp of minted completed
    id varchar(255) NOT NULL  -- id fields for the functionType  in contract asc20
)

[User] Show me the total balance and number of distinct holders for each Avalanche token, including its tick and creator address.

[Assistant]
SELECT ti.tick, ti.creator, SUM(tb.amount) AS total_balance, COUNT(DISTINCT tb.wallet_address) AS holder_count
FROM token_balances tb
JOIN token_info_avalanche ti ON tb.tick = ti.tick
GROUP BY ti.tick, ti.creator;

[User] I also want to see the max_supply for each token in the result.

[Assistant]
SELECT ti.tick, ti.creator, ti.max_supply, SUM(tb.amount) AS total_balance, COUNT(DISTINCT tb.wallet_address) AS holder_count
FROM token_balances tb
JOIN token_info_avalanche ti ON tb.tick = ti.tick
GROUP BY ti.tick, ti.creator, ti.max_supply;

[User] Only include tokens where max_supply is greater than 10000 and sort by total_balance descending.

[Assistant]
SELECT ti.tick, ti.creator, ti.max_supply, SUM(tb.amount) AS total_balance, COUNT(DISTINCT tb.wallet_address) AS holder_count
FROM token_balances tb
JOIN token_info_avalanche ti ON tb.tick = ti.tick
WHERE ti.max_supply > 10000
GROUP BY ti.tick, ti.creator, ti.max_supply
ORDER BY total_balance DESC;

[User] Add a column for the difference between max_supply and total_balance, call it available_supply.

[Assistant]
SELECT ti.tick, ti.creator, ti.max_supply, SUM(tb.amount) AS total_balance, (ti.max_supply - SUM(tb.amount)) AS available_supply, COUNT(DISTINCT tb.wallet_address) AS holder_count
FROM token_balances tb
JOIN token_info_avalanche ti ON tb.tick = ti.tick
WHERE ti.max_supply > 10000
GROUP BY ti.tick, ti.creator, ti.max_supply
ORDER BY total_balance 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.customers ( customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, ssn_hash character varying(128), address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL DEFAULT 'USA', phone_number character varying(30), email character varying(128) UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, status character varying(20) NOT NULL DEFAULT 'Active', PRIMARY KEY (customer_id) )

[User] How many customers are there in each state?

[Assistant]
SELECT state, COUNT(*) AS customer_count
FROM insurance.customers
GROUP BY state;


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 project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE token_dexpool_info ( pair_address text, token_name text, token_symbol text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_6h numeric, price_change_percentage_24h numeric, makers_24h numeric, volume_24h numeric, liquidity numeric, market_cap numeric, trend_rank numeric )
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

[User] List projects that have raised funds and also have an associated token, showing their name, fundraising amount, and current token price.

[Assistant] SELECT T1.project_name, T1.investment_value, T2.price FROM project_fundraising_record AS T1 INNER JOIN token_basic_info AS T2 ON T1.project_name = T2.token_symbol

[User] Only show results for projects that raised funds in 2023, and also include the token's market cap.

[Assistant] SELECT T1.project_name, T1.investment_value, T2.price, T2.market_cap FROM project_fundraising_record AS T1 INNER JOIN token_basic_info AS T2 ON T1.project_name = T2.token_symbol WHERE T1.investment_date LIKE '%2023%'

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

[Assistant] SELECT T1.project_name, T1.investment_value, T2.price, T2.market_cap FROM project_fundraising_record AS T1 INNER JOIN token_basic_info AS T2 ON T1.project_name = T2.token_symbol WHERE T1.investment_date LIKE '%2023%' ORDER BY T1.investment_value DESC LIMIT 10

[User] Filter to only include tokens on the 'Ethereum' chain.

[Assistant] SELECT T1.project_name, T1.investment_value, T2.price, T2.market_cap FROM project_fundraising_record AS T1 INNER JOIN token_basic_info AS T2 ON T1.project_name = T2.token_symbol WHERE T1.investment_date LIKE '%2023%' AND T2.chain = 'Ethereum' ORDER BY T1.investment_value DESC LIMIT 10


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.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] Can you show me the details of all medical records for patients that had their vitals recorded with a temperature above 38 degrees Celsius, along with any medication descriptions that mention 'antipyretic'?

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.record_date, mr.chief_complaint, mr.treatment_plan, m.medication_name, m.description
FROM healthcare.medical_records mr
JOIN healthcare.medications m ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE (mr.vitals->>'Temp')::numeric > 38 AND m.description ILIKE '%antipyretic%';

[User] Refine the query to only include records created after January 1st, 2024.

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.record_date, mr.chief_complaint, mr.treatment_plan, m.medication_name, m.description
FROM healthcare.medical_records mr
JOIN healthcare.medications m ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE (mr.vitals->>'Temp')::numeric > 38
  AND m.description ILIKE '%antipyretic%'
  AND mr.record_date >= '2024-01-01';

[User] Actually, could you also include the doctor's ID who created each medical record?

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.doctor_id, mr.record_date, mr.chief_complaint, mr.treatment_plan, m.medication_name, m.description
FROM healthcare.medical_records mr
JOIN healthcare.medications m ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE (mr.vitals->>'Temp')::numeric > 38
  AND m.description ILIKE '%antipyretic%'
  AND mr.record_date >= '2024-01-01';


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 )
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.time_entries ( entry_id.text, case_id.text, lawyer_id.text, date_worked.date, hours_spent.numeric, billing_rate.numeric, description.text, is_billable.boolean, is_billed.boolean, invoice_id.text, created_at.timestamp )
CREATE TABLE legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )
CREATE TABLE legal_services.appointments ( appointment_id.text, 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 the full name, specialization, and firm name for all lawyers who are not partners.

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization, T2.firm_name FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = 0;

[User] Could you narrow it down to only those whose specialization is 'Criminal Defense'?

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization, T2.firm_name FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = 0 AND T1.specialization = 'Criminal Defense';

[User] Also include their hire date and only show those hired after '2022-01-01'.

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization, T2.firm_name, T1.hire_date FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = 0 AND T1.specialization = 'Criminal Defense' AND T1.hire_date > '2022-01-01';


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 smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )

[User] How many distinct addresses achieved a realized_ratio higher than 0.9 last month?

[Assistant] SELECT COUNT(DISTINCT address) FROM smart_money_profit WHERE realized_ratio > 0.9;

[User] Can you also break down the count by chain?

[Assistant] SELECT chain, COUNT(DISTINCT address) AS address_count FROM smart_money_profit WHERE realized_ratio > 0.9 GROUP BY chain;


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

[User] Show me the names of law firms founded after 2010, along with the full name of their managing partner.

[Assistant] SELECT f.firm_name, l.first_name, l.last_name FROM legal_services.law_firms AS f JOIN legal_services.lawyers AS l ON f.managing_partner_id = l.lawyer_id WHERE f.founded_date > '2010-12-31';


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, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.law_firms ( firm_id.text, 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.time_entries ( entry_id.text, case_id.text, lawyer_id.text, date_worked.date, hours_spent.numeric, billing_rate.numeric, description.text, is_billable.boolean, is_billed.boolean, invoice_id.text, created_at.timestamp )

[User] List the full name (first and last) and specialization of all lawyers who work for law firms founded before the year 2000.

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T2.founded_date < '2000-01-01'

[User] From that list, could you only show those lawyers whose specialization is 'Environmental Law'?

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T2.founded_date < '2000-01-01' AND T1.specialization = 'Environmental Law'

[User] Also include their hire date and order the results by specialization then hire date.

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization, T1.hire_date FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T2.founded_date < '2000-01-01' AND T1.specialization = 'Environmental Law' ORDER BY T1.specialization, T1.hire_date


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, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
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 text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] Show the usernames and email addresses of users who have commented on their own posts.

[Assistant]
SELECT DISTINCT u.username, u.email
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
JOIN social_media.posts p ON c.post_id = p.post_id
WHERE c.user_id = p.user_id;

[User] Please also include the total number of such comments each user made.

[Assistant]
SELECT u.username, u.email, COUNT(*) AS comment_count
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
JOIN social_media.posts p ON c.post_id = p.post_id
WHERE c.user_id = p.user_id
GROUP BY u.username, u.email;


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. 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 manufacturing.component_inventory (
    inventory_record_id character varying(64) NOT NULL, -- unique ID for this inventory record/batch
    component_id character varying(64) NOT NULL, -- FK to the component
    quantity integer NOT NULL, -- number of units of this component in stock for this batch
    location_warehouse character varying(100), -- warehouse identifier
    location_bin character varying(100), -- specific bin or shelf location
    received_date timestamp NOT NULL, -- when this batch was received
    expiry_date date, -- expiry date if applicable (e.g., for sealants, adhesives)
    batch_number character varying(100), -- supplier batch number
    last_updated timestamp NOT NULL, -- timestamp of the last update to this record
    PRIMARY KEY (inventory_record_id)
)

[User] What is the purchase price of the components in a specific batch with batch_number 'BATCH123'?

[Assistant] I'm sorry, but I can't provide information on the purchase price of components as this data is not stored in the component_inventory table. If you have other questions or need assistance with data available in the table, such as quantity or location, I'm happy to help.