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.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )

[User] For each driver status, find the earliest and latest hire date. Show status, earliest hire date, and latest hire date.

[Assistant]
SELECT
  status,
  MIN(hire_date) AS earliest_hire_date,
  MAX(hire_date) AS latest_hire_date
FROM transportation.drivers
GROUP BY
  status
ORDER BY
  status;

[User] The SQL seems correct, but can you also include the total number of drivers for each status?

[Assistant]
SELECT
  status,
  COUNT(*) AS driver_count,
  MIN(hire_date) AS earliest_hire_date,
  MAX(hire_date) AS latest_hire_date
FROM transportation.drivers
GROUP BY
  status
ORDER BY
  status;

[User] Now, restrict the results to only show statuses that have more than 5 drivers and where the latest hire date is after '2023-01-01'. Order the results by the total number of drivers in descending order.

[Assistant]
SELECT
  status,
  COUNT(*) AS driver_count,
  MIN(hire_date) AS earliest_hire_date,
  MAX(hire_date) AS latest_hire_date
FROM transportation.drivers
GROUP BY
  status
HAVING
  COUNT(*) > 5 AND MAX(hire_date) > '2023-01-01'
ORDER BY
  driver_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 web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )

[User] For each transaction, find the next transaction by the same sender. Show the original transaction_id as current_tx, the next transaction_id as next_tx, from_address, and the time difference in minutes between them.

[Assistant]
SELECT t1.transaction_id AS current_tx,
       t2.transaction_id AS next_tx,
       t1.from_address,
       EXTRACT(EPOCH FROM (t2.timestamp - t1.timestamp)) / 60 AS diff_minutes
FROM web3.transactions t1
JOIN web3.transactions t2
  ON t1.from_address = t2.from_address
  AND t2.timestamp = (
    SELECT MIN(t3.timestamp)
    FROM web3.transactions t3
    WHERE t3.from_address = t1.from_address
      AND t3.timestamp > t1.timestamp
  );


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.guests (
    guest_id character varying(64) NOT NULL,  -- unique identifier for the guest profile
    first_name character varying(100) NOT NULL, -- guest's first name
    last_name character varying(100) NOT NULL, -- guest's last name
    email character varying(255) UNIQUE, -- guest's email address (unique identifier?)
    phone_number character varying(30), -- guest's phone number
    date_of_birth date, -- guest's date of birth
    address_line1 character varying(255), -- guest's home address
    city character varying(100),
    state_province character varying(100),
    postal_code character varying(20),
    country_code character varying(3),
    preferences text, -- notes on guest preferences (e.g., allergies, room location)
    loyalty_member_id character varying(64) UNIQUE, -- FK to loyalty_members table
    communication_consent boolean DEFAULT true, -- consent for marketing communications
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (guest_id)
)
CREATE TABLE hospitality_technology.reservations (
    reservation_id character varying(64) NOT NULL,  -- unique identifier for the booking
    property_id character varying(64) NOT NULL, -- FK to properties table
    guest_id character varying(64) NOT NULL, -- FK to guests table (primary guest)
    room_id character varying(64), -- FK to rooms table (assigned room, might be null initially)
    room_type_id character varying(64) NOT NULL, -- FK to room_types table (booked room type)
    check_in_date date NOT NULL, -- scheduled check-in date
    check_out_date date NOT NULL, -- scheduled check-out date
    actual_check_in_ts timestamp with time zone, -- actual check-in time
    actual_check_out_ts timestamp with time zone, -- actual check-out time
    num_adults integer NOT NULL, -- number of adults
    num_children integer DEFAULT 0, -- number of children
    status character varying(50) NOT NULL, -- e.g., Pending, Confirmed, CheckedIn, CheckedOut, Cancelled, NoShow
    booking_source character varying(100), -- e.g., Website, OTA (Expedia, Booking.com), Phone, WalkIn
    rate_plan_id character varying(64), -- FK to rate_plans table (optional)
    total_amount numeric(12, 2), -- estimated or final total cost
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    special_requests text, -- specific guest requests for this booking
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (reservation_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.reviews (
    review_id character varying(64) NOT NULL,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    PRIMARY KEY (review_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id)
)

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )

[User] Retrieve the average base premium of insurance products for each product_type, including only types that have more than 5 products.

[Assistant]
SELECT product_type, AVG(base_premium) AS avg_premium
FROM insurance.insurance_products
GROUP BY product_type
HAVING COUNT(*) > 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, token_address character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, highest_price_24h double precision, lowest_price_24h double precision, market_cap double precision, market_cap_rank bigint, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank bigint )
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_6h double precision, price_change_percentage_24h double precision, makers_24h double precision, volume_24h double precision, liquidity double precision, market_cap double precision, trend_rank bigint )
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, token_symbol character varying(100), token_amount numeric(38,2), usd_value numeric(38,2), avg_price numeric(38,6), type int, address_amount integer, narrative character varying(100), chain character varying(100) )

[User] Show the top 3 tokens on Polygon with the greatest positive price change over the last 6 hours, including their symbol, price, 6h change, and the number of smart money buy addresses in the last 24h.

[Assistant]
SELECT tdi.token_symbol, tdi.price, tdi.price_change_percentage_6h,
  COALESCE(SUM(CASE WHEN smti.type = 1 AND smti.chain = 'Polygon' THEN smti.address_amount ELSE 0 END), 0) AS buy_address_count
FROM token_dexpool_info tdi
LEFT JOIN smart_money_token_inflow smti
  ON tdi.token_symbol = smti.token_symbol AND tdi.chain = smti.chain
WHERE tdi.chain = 'Polygon' AND tdi.price_change_percentage_6h > 0
GROUP BY tdi.token_symbol, tdi.price, tdi.price_change_percentage_6h
ORDER BY tdi.price_change_percentage_6h DESC
LIMIT 3;

[User] Instead of just Polygon, can you show the top 3 tokens with the greatest positive 6h price change across both Polygon and BSC? Still include the number of smart money buys.

[Assistant]
SELECT tdi.token_symbol, tdi.chain, tdi.price, tdi.price_change_percentage_6h,
  COALESCE(SUM(CASE WHEN smti.type = 1 THEN smti.address_amount ELSE 0 END), 0) AS buy_address_count
FROM token_dexpool_info tdi
LEFT JOIN smart_money_token_inflow smti
  ON tdi.token_symbol = smti.token_symbol AND tdi.chain = smti.chain
WHERE tdi.chain IN ('Polygon', 'BSC') AND tdi.price_change_percentage_6h > 0
GROUP BY tdi.token_symbol, tdi.chain, tdi.price, tdi.price_change_percentage_6h
ORDER BY tdi.price_change_percentage_6h DESC
LIMIT 3;

[User] Now, only display tokens with at least 10 smart money buy addresses. Also, add their 24h trading volume.

[Assistant]
SELECT tdi.token_symbol, tdi.chain, tdi.price, tdi.price_change_percentage_6h, tdi.volume_24h,
  COALESCE(SUM(CASE WHEN smti.type = 1 THEN smti.address_amount ELSE 0 END), 0) AS buy_address_count
FROM token_dexpool_info tdi
LEFT JOIN smart_money_token_inflow smti
  ON tdi.token_symbol = smti.token_symbol AND tdi.chain = smti.chain
WHERE tdi.chain IN ('Polygon', 'BSC') AND tdi.price_change_percentage_6h > 0
GROUP BY tdi.token_symbol, tdi.chain, tdi.price, tdi.price_change_percentage_6h, tdi.volume_24h
HAVING COALESCE(SUM(CASE WHEN smti.type = 1 THEN smti.address_amount ELSE 0 END), 0) >= 10
ORDER BY tdi.price_change_percentage_6h 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 insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )

[User] Show me all premium payments made by customer with ID 'CUST789'.

[Assistant] SELECT * FROM insurance.premium_payments WHERE customer_id = 'CUST789';

[User] From those payments, only include the ones with status 'Completed'.

[Assistant] SELECT * FROM insurance.premium_payments WHERE customer_id = 'CUST789' AND status = 'Completed';

[User] Also, filter the results to only show payments made between '2023-01-01' and '2023-12-31'.

[Assistant] SELECT * FROM insurance.premium_payments WHERE customer_id = 'CUST789' AND status = 'Completed' AND payment_date BETWEEN '2023-01-01' AND '2023-12-31';

[User] Okay, instead of all columns, just show the policy ID, payment date, and amount paid, ordered by payment date descending.

[Assistant] SELECT policy_id, payment_date, amount_paid FROM insurance.premium_payments WHERE customer_id = 'CUST789' AND status = 'Completed' AND payment_date BETWEEN '2023-01-01' AND '2023-12-31' ORDER BY payment_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 hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
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.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.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] Which room types have a base rate above 250, and what are their property names and maximum occupancy?

[Assistant]
SELECT rt.room_type_id, rt.type_name, p.property_name, rt.base_rate, rt.max_occupancy
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
WHERE rt.base_rate > 250;

[User] I only want to see room types with a maximum occupancy greater than 2.

[Assistant]
SELECT rt.room_type_id, rt.type_name, p.property_name, rt.base_rate, rt.max_occupancy
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
WHERE rt.base_rate > 250 AND rt.max_occupancy > 2;

[User] Also include the bed type and the area in square feet for each room type.

[Assistant]
SELECT rt.room_type_id, rt.type_name, p.property_name, rt.base_rate, rt.max_occupancy, rt.bed_type, rt.area_sqft
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
WHERE rt.base_rate > 250 AND rt.max_occupancy > 2;


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

[User] Find cases where an address received tokens in one transfer and then sent tokens in another. List the receive transfer_id, the send transfer_id, the address, and both transfer values.

[Assistant]
SELECT recv.transfer_id AS receive_transfer_id,
       send.transfer_id AS send_transfer_id,
       recv.to_address AS address,
       recv.value       AS received_value,
       send.value       AS sent_value
FROM web3.token_transfers recv
JOIN web3.token_transfers send
  ON recv.to_address = send.from_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 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] List public reviews whose comment contains the word 'slow'.

[Assistant] SELECT review_id, comment, review_date, rating_overall, property_id FROM hospitality_technology.reviews WHERE is_public = TRUE AND LOWER(comment) LIKE '%slow%';

[User] Also, only include reviews submitted for property 'P007'.

[Assistant] SELECT review_id, comment, review_date, rating_overall, property_id FROM hospitality_technology.reviews WHERE is_public = TRUE AND LOWER(comment) LIKE '%slow%' AND property_id = 'P007';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] Show me all users and the posts they have created, including the user's username and the post content.

[Assistant]
SELECT u.username, p.post_id, p.content
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id;

[User] Actually, can you please also include the post creation time and only show posts that have a media attachment?

[Assistant]
SELECT u.username, p.post_id, p.content, p.created_at
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.media_url IS NOT NULL AND p.media_url <> '';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] List all beneficiaries who have a null contact_info. Return beneficiary_id, first_name, last_name, policy_id.

[Assistant]
SELECT beneficiary_id, first_name, last_name, policy_id
FROM insurance.policy_beneficiaries
WHERE contact_info IS NULL;

[User] Also show the relationship for each of these beneficiaries and sort the results alphabetically by last_name.

[Assistant]
SELECT beneficiary_id, first_name, last_name, policy_id, relationship
FROM insurance.policy_beneficiaries
WHERE contact_info IS NULL
ORDER BY 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 financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 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.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)

[User] Show me all users who have been notified by the system (i.e. notifications where the sender_user_id is NULL). Please include their username and the type of each notification.

[Assistant]
SELECT u.username, n.notification_type, n.notification_id
FROM social_media.users u
JOIN social_media.notifications n ON u.user_id = n.recipient_user_id
WHERE n.sender_user_id IS NULL;

[User] I'd like to know which of these users have private profiles. Please add that column to the results.

[Assistant]
SELECT u.username, n.notification_type, n.notification_id, us.private_profile
FROM social_media.users u
JOIN social_media.notifications n ON u.user_id = n.recipient_user_id
JOIN social_media.user_settings us ON u.user_id = us.user_id
WHERE n.sender_user_id IS NULL;

[User] Now, restrict the list to only show system notifications sent after June 1, 2024.

[Assistant]
SELECT u.username, n.notification_type, n.notification_id, us.private_profile
FROM social_media.users u
JOIN social_media.notifications n ON u.user_id = n.recipient_user_id
JOIN social_media.user_settings us ON u.user_id = us.user_id
WHERE n.sender_user_id IS NULL AND n.created_at > '2024-06-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 web3.contracts (
    contract_id character varying(64) NOT NULL,  -- unique identifier for the contract
    address character varying(128) NOT NULL, -- address of the deployed contract
    abi text NOT NULL, -- application binary interface of the contract
    bytecode text NOT NULL, -- bytecode of the contract
    deployer_address character varying(128) NOT NULL, -- address of the deployer
    deployed_at timestamp NOT NULL, -- time when the contract was deployed
    network_id character varying(64) NOT NULL, -- identifier of the network where the contract is deployed
    status character varying(32) NOT NULL, -- status of the contract (e.g., active, deprecated)
    PRIMARY KEY (contract_id)
)
CREATE TABLE web3.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)

[User] For each transaction status, what is the average transaction value?

[Assistant] SELECT status, AVG(value) FROM web3.transactions GROUP BY status

[User] Could you filter this to only show statuses where the average value is greater than 100?

[Assistant] SELECT status, AVG(value) FROM web3.transactions GROUP BY status HAVING AVG(value) > 100


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
// PUT /schedules
{
  "mappings": {
    "properties": {
      "schedule_id": { "type": "keyword" },
      "train_id": { "type": "keyword" }, // References trains index
      "route_id": { "type": "keyword" }, // References routes index
      "departure_datetime": { "type": "date" }, // ISO 8601 format recommended
      "arrival_datetime": { "type": "date" },
      "status": { "type": "keyword" },
      "notes": { "type": "text" }
    }
  }
}
// PUT /passengers
{
  "mappings": {
    "properties": {
      "passenger_id": { "type": "keyword" },
      "first_name": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 100 } }
      },
      "last_name": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 100 } }
       },
      "email": { "type": "keyword" }, // Often used for exact matches
      "phone_number": { "type": "keyword" },
      "date_of_birth": { "type": "date", "format": "yyyy-MM-dd" },
      "loyalty_program_id": { "type": "keyword" },
      "created_at": { "type": "date" }
    }
  }
}

[User] 能否帮我查询特定路线(route_id 为 'RT001')的所有行程信息，并关联到乘客的联系方式？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.phone_number, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.route_id = 'RT001';

[User] 能否只显示状态为‘On Time’的行程，并按出发时间升序排列？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.phone_number, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.route_id = 'RT001' AND s.status = 'On Time'
ORDER BY s.departure_datetime ASC;

[User] 如果乘客信息为空，能否仍然显示行程信息，并限制结果前10条？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.phone_number, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.route_id = 'RT001' AND s.status = 'On Time'
ORDER BY s.departure_datetime ASC
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 financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )
CREATE TABLE financial_services.transactions ( transaction_id.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.trades ( trade_id.text, account_id.text, security_id.text, order_id.text, trade_type.text, quantity.numeric, price_per_unit.numeric, total_amount.numeric, commission.numeric, trade_timestamp.timestamp, settlement_date.date, status.text, execution_venue.text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees ( employee_id.text, first_name.text, last_name.text, job_title.text, department.text, branch_id.text, email.text, phone_extension.text, hire_date.date, termination_date.date, manager_id.text, status.text )
CREATE TABLE financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )

[User] List each security’s ticker symbol and the total number of trades executed for it, along with the sum of quantities traded.

[Assistant]
SELECT s.ticker_symbol, COUNT(t.trade_id) AS total_trades, SUM(t.quantity) AS total_quantity
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
GROUP BY s.ticker_symbol;

[User] Show only those securities with more than 10 trades.

[Assistant]
SELECT s.ticker_symbol, COUNT(t.trade_id) AS total_trades, SUM(t.quantity) AS total_quantity
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
GROUP BY s.ticker_symbol
HAVING COUNT(t.trade_id) > 10;

[User] Add the security_name and order the list by total_quantity descending.

[Assistant]
SELECT s.ticker_symbol, s.security_name, COUNT(t.trade_id) AS total_trades, SUM(t.quantity) AS total_quantity
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
GROUP BY s.ticker_symbol, s.security_name
HAVING COUNT(t.trade_id) > 10
ORDER BY total_quantity 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(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata ( object_id varchar NOT NULL, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id varchar NOT NULL, status varchar NOT NULL, collection_type varchar NOT NULL, package_id varchar NOT NULL, previous_transaction varchar NOT NULL, display varchar NOT NULL, owner varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )

[User] List the symbol, name, and total supply for all ERC20 tokens.

[Assistant] SELECT symbol, name, total_supply FROM token_metas WHERE is_erc20 = 1;

[User] Include the decimals and tell me if each token is marked as a proxy.

[Assistant] SELECT symbol, name, total_supply, decimals, is_proxy FROM token_metas WHERE is_erc20 = 1;

[User] Only show non-proxy tokens with a total supply greater than '1000000000000000000000'.

[Assistant] SELECT symbol, name, total_supply, decimals, is_proxy FROM token_metas WHERE is_erc20 = 1 AND is_proxy = 0 AND CAST(total_supply AS DECIMAL) > 1000000000000000000000;

[User] For these non-proxy, high-supply tokens, show the latest USD price and order by price descending. Limit the results to 10.

[Assistant] SELECT tm.symbol, tm.name, tm.total_supply, tm.decimals, tm.is_proxy, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tm.is_proxy = 0 AND CAST(tm.total_supply AS DECIMAL) > 1000000000000000000000 ORDER BY tpl.price 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.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )

[User] List appointments with a duration longer than 45 minutes where the 'reason' includes the word 'follow-up'. Show the appointment ID, patient ID, duration, and reason.

[Assistant] SELECT appointment_id, patient_id, duration_minutes, reason FROM healthcare.appointments WHERE duration_minutes > 45 AND reason LIKE '%follow-up%';

[User] Further filter this list to only include appointments created in the year 2023.

[Assistant] SELECT appointment_id, patient_id, duration_minutes, reason FROM healthcare.appointments WHERE duration_minutes > 45 AND reason LIKE '%follow-up%' AND created_at >= '2023-01-01 00:00:00+00' AND created_at < '2024-01-01 00:00:00+00';


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_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )

[User] Which token symbols have the highest number of addresses buying them on the Ethereum chain? Show the top 3 symbols, their total address_amount, and narrative.

[Assistant]
SELECT token_symbol, narrative, SUM(address_amount) AS total_buying_addresses
FROM smart_money_token_inflow
WHERE type = 1 AND chain = 'Ethereum'
GROUP BY token_symbol, narrative
ORDER BY total_buying_addresses DESC
LIMIT 3;

[User] I got incorrect results. I only want results where the summed address_amount is at least 10.

[Assistant]
SELECT token_symbol, narrative, SUM(address_amount) AS total_buying_addresses
FROM smart_money_token_inflow
WHERE type = 1 AND chain = 'Ethereum'
GROUP BY token_symbol, narrative
HAVING SUM(address_amount) >= 10
ORDER BY total_buying_addresses DESC
LIMIT 3;

[User] Please add the total usd_value spent on buying each of these tokens.

[Assistant]
SELECT token_symbol, narrative, SUM(address_amount) AS total_buying_addresses, SUM(usd_value) AS total_buy_usd_value
FROM smart_money_token_inflow
WHERE type = 1 AND chain = 'Ethereum'
GROUP BY token_symbol, narrative
HAVING SUM(address_amount) >= 10
ORDER BY total_buying_addresses DESC
LIMIT 3;

[User] Also include the average price (avg_price) for each token.

[Assistant]
SELECT token_symbol, narrative, SUM(address_amount) AS total_buying_addresses, SUM(usd_value) AS total_buy_usd_value, AVG(avg_price) AS average_price
FROM smart_money_token_inflow
WHERE type = 1 AND chain = 'Ethereum'
GROUP BY token_symbol, narrative
HAVING SUM(address_amount) >= 10
ORDER BY total_buying_addresses 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 insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )

[User] List all claim IDs that have both an 'Accident Report' and a 'Damage Assessment' document type.

[Assistant]
SELECT claim_id
FROM insurance.claim_documents
WHERE document_type IN ('Accident Report', 'Damage Assessment')
GROUP BY claim_id
HAVING COUNT(DISTINCT document_type) = 2;

[User] This returns claim IDs even if they have only multiple 'Accident Report' entries and no 'Damage Assessment'. I want to ensure each claim_id has at least one of each type.

[Assistant]
SELECT claim_id
FROM insurance.claim_documents
GROUP BY claim_id
HAVING SUM(CASE WHEN document_type = 'Accident Report' THEN 1 ELSE 0 END) > 0
   AND SUM(CASE WHEN document_type = 'Damage Assessment' THEN 1 ELSE 0 END) > 0;

[User] Also, only include documents uploaded after '2024-01-01'.

[Assistant]
SELECT claim_id
FROM insurance.claim_documents
WHERE uploaded_at > '2024-01-01'
GROUP BY claim_id
HAVING SUM(CASE WHEN document_type = 'Accident Report' THEN 1 ELSE 0 END) > 0
   AND SUM(CASE WHEN document_type = 'Damage Assessment' THEN 1 ELSE 0 END) > 0;

[User] Finally, sort the result by claim_id in ascending order.

[Assistant]
SELECT claim_id
FROM insurance.claim_documents
WHERE uploaded_at > '2024-01-01'
GROUP BY claim_id
HAVING SUM(CASE WHEN document_type = 'Accident Report' THEN 1 ELSE 0 END) > 0
   AND SUM(CASE WHEN document_type = 'Damage Assessment' THEN 1 ELSE 0 END) > 0
ORDER BY claim_id 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 trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id text, transaction_id text, output_index integer, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.metadata ( metadata_id text, asset_id text, key text, value text )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] List all unspent UTXOs, including their utxo_id, address, amount, and transaction_id.

[Assistant]
SELECT utxo_id, address, amount, transaction_id
FROM trading_platform.utxos
WHERE spent = false;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )

[User] I want to list pairs of insurance plans from the same provider, showing both plan IDs and names alongside the provider.

[Assistant]
SELECT p1.plan_id, p1.plan_name, p2.plan_id AS plan_id_2, p2.plan_name AS plan_name_2, p1.insurance_provider
FROM healthcare.insurance_plans p1
JOIN healthcare.insurance_plans p2
  ON p1.insurance_provider = p2.insurance_provider
  AND p1.plan_id < p2.plan_id;

[User] Actually, only include pairs where the plan types are different.

[Assistant]
SELECT p1.plan_id, p1.plan_name, p2.plan_id AS plan_id_2, p2.plan_name AS plan_name_2, p1.insurance_provider
FROM healthcare.insurance_plans p1
JOIN healthcare.insurance_plans p2
  ON p1.insurance_provider = p2.insurance_provider
  AND p1.plan_id < p2.plan_id
WHERE p1.plan_type <> p2.plan_type;

[User] Also, sort the results by provider ascending and then by the first plan_id.

[Assistant]
SELECT p1.plan_id, p1.plan_name, p2.plan_id AS plan_id_2, p2.plan_name AS plan_name_2, p1.insurance_provider
FROM healthcare.insurance_plans p1
JOIN healthcare.insurance_plans p2
  ON p1.insurance_provider = p2.insurance_provider
  AND p1.plan_id < p2.plan_id
WHERE p1.plan_type <> p2.plan_type
ORDER BY p1.insurance_provider ASC, p1.plan_id 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 text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] Find appointments and prescriptions associated with the same patient and doctor. Show the appointment ID, prescription ID, patient ID, and doctor ID.

[Assistant] SELECT T1.appointment_id ,  T2.prescription_id ,  T1.patient_id ,  T1.doctor_id FROM healthcare.appointments AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id  =  T2.patient_id AND T1.doctor_id  =  T2.doctor_id

[User] Refine the list to only include cases where the prescription start date is before the appointment time. Add the start date and appointment time to the results.

[Assistant] SELECT T1.appointment_id ,  T2.prescription_id ,  T1.patient_id ,  T1.doctor_id ,  T2.start_date ,  T1.appointment_time FROM healthcare.appointments AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id  =  T2.patient_id AND T1.doctor_id  =  T2.doctor_id WHERE T2.start_date  <  DATE(T1.appointment_time)


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 token_basic_info ( coin_id.text, token_name.text, token_symbol.text, token_address.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, highest_price_24h.numeric, lowest_price_24h.numeric, market_cap.numeric, market_cap_rank.numeric, market_cap_change_percentage_24h.text, total_volume.text, narrative.text, trend_rank.numeric )

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id uuid, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
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 timestamp with time zone )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )

[User] List all game titles and corresponding server names for servers that are located in the same region as 'us-central-1'.

[Assistant]
SELECT g.title, s.server_name
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
WHERE s.region = 'us-central-1';

[User] Additionally, include the username of every player who has had a session on each of those servers.

[Assistant]
SELECT g.title, s.server_name, p.username
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
JOIN gaming_technology.game_sessions gs ON gs.server_id = s.server_id
JOIN gaming_technology.players p ON gs.player_id = p.player_id
WHERE s.region = 'us-central-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 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 character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
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.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)

[User] List the full name and firm name for all lawyers who are not partners.

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

[User] Now, only show those non-partner lawyers whose specialization is 'Litigation'.

[Assistant] SELECT T1.first_name, T1.last_name, T2.firm_name FROM legal_services.lawyers AS T1 JOIN legal_services.law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = FALSE AND T1.specialization = 'Litigation'

[User] Filter this list to only include those hired after 2021-01-01 and order by hire date.

[Assistant] SELECT T1.first_name, T1.last_name, T2.firm_name FROM legal_services.lawyers AS T1 JOIN legal_services.law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = FALSE AND T1.specialization = 'Litigation' AND T1.hire_date > '2021-01-01' ORDER BY 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 narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )

[User] List all narratives with a trend rank better than 50, showing the narrative name and their listed 'Top 3 Coins'.

[Assistant] SELECT narrative, top_3_coins FROM narrative_info WHERE trend_rank < 50

[User] Could you also include the 24-hour trading volume for these narratives and only show those where the volume is greater than 10,000,000 USD?

[Assistant] SELECT narrative, top_3_coins, volume_24h FROM narrative_info WHERE trend_rank < 50 AND volume_24h > 10000000

[User] Please order the results by 24-hour trading volume in descending order.

[Assistant] SELECT narrative, top_3_coins, volume_24h FROM narrative_info WHERE trend_rank < 50 AND volume_24h > 10000000 ORDER BY volume_24h DESC

[User] Finally, limit the output to the top 10 and add the total number of tokens for each narrative.

[Assistant] SELECT narrative, top_3_coins, volume_24h, token_num FROM narrative_info WHERE trend_rank < 50 AND volume_24h > 10000000 ORDER BY volume_24h 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 web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)

[User] List all tokens with a total supply greater than 1,000,000.

[Assistant]
SELECT token_id, token_name, token_symbol, contract_address, total_supply
FROM web3.tokens
WHERE total_supply > 1000000;

[User] Can you also include the decimals for each token in the result?

[Assistant]
SELECT token_id, token_name, token_symbol, contract_address, total_supply, decimals
FROM web3.tokens
WHERE total_supply > 1000000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )

[User] I want to see each user's username and the number of posts they've made that include a media attachment of type 'image'.

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.securities ( security_id text, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )

[User] List all securities (security_id, ticker_symbol, security_name) that are traded on the NASDAQ exchange (exchange = 'NASDAQ') and belong to the 'Technology' sector.

[Assistant] SELECT security_id, ticker_symbol, security_name FROM financial_services.securities WHERE exchange = 'NASDAQ' AND sector = 'Technology';


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.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )
CREATE TABLE web3.tokens ( token_id text, contract_address text, token_name text, token_symbol text, decimals integer, total_supply numeric )
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 )

[User] Show all token transfers where the token_symbol contains 'ETH' and include the transfer id, value, transaction id, and the contract address where the token was created.

[Assistant]
SELECT tt.transfer_id, tt.value, tt.transaction_id, t.contract_address
FROM web3.token_transfers tt
JOIN web3.tokens t ON tt.token_id = t.token_id
WHERE t.token_symbol LIKE '%ETH%';


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 train_station_management.platforms (
    platform_id character varying(64) NOT NULL, -- Unique identifier for the platform
    station_id character varying(64) NOT NULL, -- Foreign key referencing stations
    platform_number character varying(10) NOT NULL, -- Platform identifier (e.g., '1A', '5')
    track_number character varying(10), -- Associated track number, if different
    status character varying(32) NOT NULL DEFAULT 'Operational', -- e.g., Operational, Maintenance, Closed
    length_meters numeric(8,2), -- Length of the platform in meters
    accessible boolean NOT NULL DEFAULT false, -- Is the platform accessible (e.g., wheelchair)?
    PRIMARY KEY (platform_id),
    FOREIGN KEY (station_id) REFERENCES train_station_management.stations(station_id)
)
CREATE TABLE train_station_management.trains (
    train_id character varying(64) NOT NULL, -- Unique identifier for the train set
    train_number character varying(32) NOT NULL, -- Operational number of the train (e.g., 'Acela 2151')
    model character varying(128), -- Model of the train (e.g., 'Siemens Velaro')
    manufacturer character varying(128), -- Manufacturer of the train
    year_manufactured integer, -- Year the train was built
    capacity integer NOT NULL, -- Total passenger capacity
    status character varying(32) NOT NULL DEFAULT 'Active', -- e.g., Active, Maintenance, Retired
    last_maintenance_date date, -- Date of last scheduled maintenance
    next_maintenance_date date, -- Date of next scheduled maintenance
    PRIMARY KEY (train_id),
    UNIQUE (train_number)
)
CREATE TABLE train_station_management.staff (
    staff_id character varying(64) NOT NULL, -- Unique identifier for the staff member
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    role character varying(64) NOT NULL, -- e.g., Station Master, Ticket Agent, Conductor, Engineer, Maintenance Crew
    primary_station_id character varying(64), -- Base station for the staff member (nullable for mobile staff)
    employee_number character varying(32) UNIQUE NOT NULL, -- Unique employee identifier
    hire_date date NOT NULL,
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    is_active boolean NOT NULL DEFAULT true, -- Is the staff member currently employed?
    PRIMARY KEY (staff_id),
    FOREIGN KEY (primary_station_id) REFERENCES train_station_management.stations(station_id)
)

[User] Can you provide the total number of active trains in the database?

[Assistant]
SELECT COUNT(*)
FROM train_station_management.trains
WHERE status = 'Active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )

[User] I need a list of all documents associated with claims, showing the document ID, file name, document type, and the status of the claim it belongs to.

[Assistant]
SELECT
  cd.document_id,
  cd.file_name,
  cd.document_type,
  c.status AS claim_status
FROM insurance.claim_documents AS cd
JOIN insurance.claims AS c
  ON cd.claim_id = c.claim_id;

[User] Okay, now filter those results to only include documents where the claim status is 'Processing'.

[Assistant]
SELECT
  cd.document_id,
  cd.file_name,
  cd.document_type,
  c.status AS claim_status
FROM insurance.claim_documents AS cd
JOIN insurance.claims AS c
  ON cd.claim_id = c.claim_id
WHERE
  c.status = 'Processing';

[User] Could you also add the estimated loss for these 'Processing' claims and order the results by file size descending?

[Assistant]
SELECT
  cd.document_id,
  cd.file_name,
  cd.document_type,
  c.status AS claim_status,
  c.estimated_loss,
  cd.file_size_bytes
FROM insurance.claim_documents AS cd
JOIN insurance.claims AS c
  ON cd.claim_id = c.claim_id
WHERE
  c.status = 'Processing'
ORDER BY
  cd.file_size_bytes DESC;

[User] Actually, forget the estimated loss and file size. Just show the document ID, file name, document type, claim status, and the incident date of the claim for those 'Processing' claims, ordered by incident date descending.

[Assistant]
SELECT
  cd.document_id,
  cd.file_name,
  cd.document_type,
  c.status AS claim_status,
  c.incident_date
FROM insurance.claim_documents AS cd
JOIN insurance.claims AS c
  ON cd.claim_id = c.claim_id
WHERE
  c.status = 'Processing'
ORDER BY
  c.incident_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 legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )

[User] Can you show me the number of lawyers grouped by specialization?

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count FROM lawyers GROUP BY specialization;

[User] Include only specializations that have more than two lawyers.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2;

[User] Also show the average tenure in years for each of those specializations.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count, AVG(EXTRACT(EPOCH FROM (NOW() - hire_date)) / 31536000) AS avg_tenure_years FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2;

[User] Order the result by average tenure in descending order.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count, AVG(EXTRACT(EPOCH FROM (NOW() - hire_date)) / 31536000) AS avg_tenure_years FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2 ORDER BY avg_tenure_years DESC;


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.maintenance_records ( record_id.text, asset_id.text, asset_type.text, maintenance_type.text, staff_id.text, start_datetime.timestamp, end_datetime.timestamp, description.text, cost.numeric, status.text )

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

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