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

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

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

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

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

[User] I also want to see the count of police report documents per claim for these large files.

[Assistant] SELECT claim_id, COUNT(*) AS police_report_count FROM insurance.claim_documents WHERE document_type = 'police_report' AND uploaded_at >= CURRENT_DATE - INTERVAL '30 days' AND file_size_bytes > 1000000 GROUP BY claim_id;

[User] Finally, show me the average file size of these police reports by document type.

[Assistant] SELECT document_type, AVG(file_size_bytes) AS avg_file_size FROM insurance.claim_documents WHERE document_type = 'police_report' AND uploaded_at >= CURRENT_DATE - INTERVAL '30 days' AND file_size_bytes > 1000000 GROUP BY document_type;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
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] I want to see for each security the ticker_symbol, security_name, and the highest single-day close_price from the market_data.

[Assistant]
SELECT s.ticker_symbol, s.security_name, MAX(m.close_price) AS highest_close_price
FROM financial_services.securities s
JOIN financial_services.market_data m ON s.security_id = m.security_id
GROUP BY s.ticker_symbol, s.security_name;

[User] Also include the data_timestamp corresponding to the highest close_price for each security.

[Assistant]
SELECT s.ticker_symbol, s.security_name, m.close_price AS highest_close_price, m.data_timestamp
FROM financial_services.securities s
JOIN financial_services.market_data m
  ON s.security_id = m.security_id
WHERE (s.security_id, m.close_price) IN (
  SELECT security_id, MAX(close_price)
  FROM financial_services.market_data
  GROUP BY security_id
);

[User] Show only the results where highest_close_price is greater than 100.

[Assistant]
SELECT s.ticker_symbol, s.security_name, m.close_price AS highest_close_price, m.data_timestamp
FROM financial_services.securities s
JOIN financial_services.market_data m
  ON s.security_id = m.security_id
WHERE (s.security_id, m.close_price) IN (
  SELECT security_id, MAX(close_price)
  FROM financial_services.market_data
  GROUP BY security_id
)
AND m.close_price > 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
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )

[User] List all appointments along with their scheduled start time and the purpose, as well as the name of the location where each appointment is scheduled.

[Assistant]
SELECT a.appointment_id, a.scheduled_start_time, a.purpose, l.location_name
FROM government_services.appointments a
JOIN government_services.service_locations l ON a.location_id = l.location_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] Retrieve review comments and their overall rating for properties that currently have at least one room with a status of 'Available'. Include the review ID, property ID, and review date.

[Assistant] SELECT r.review_id, r.comment, r.rating_overall, r.property_id, r.review_date FROM hospitality_technology.reviews r JOIN hospitality_technology.rooms rm ON r.property_id = rm.property_id WHERE rm.status = 'Available'

[User] Refine this to only show reviews where the overall rating is 4 or 5, and the review was submitted in 2023.

[Assistant] SELECT r.review_id, r.comment, r.rating_overall, r.property_id, r.review_date FROM hospitality_technology.reviews r JOIN hospitality_technology.rooms rm ON r.property_id = rm.property_id WHERE rm.status = 'Available' AND r.rating_overall IN (4, 5) AND r.review_date >= '2023-01-01' AND r.review_date < '2024-01-01'

[User] Exclude duplicate reviews if a property has multiple available rooms, and sort the results by review date descending.

[Assistant] SELECT DISTINCT r.review_id, r.comment, r.rating_overall, r.property_id, r.review_date FROM hospitality_technology.reviews r JOIN hospitality_technology.rooms rm ON r.property_id = rm.property_id WHERE rm.status = 'Available' AND r.rating_overall IN (4, 5) AND r.review_date >= '2023-01-01' AND r.review_date < '2024-01-01' ORDER BY r.review_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.service_orders (
    order_id character varying(64) NOT NULL, -- unique identifier for a specific service order
    reservation_id character varying(64), -- FK to reservations (if associated with a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who ordered)
    service_id character varying(64) NOT NULL, -- FK to services (what was ordered)
    staff_id_ordered character varying(64), -- FK to staff (who took the order)
    staff_id_delivered character varying(64), -- FK to staff (who fulfilled/delivered)
    order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the order was placed
    delivery_timestamp timestamp with time zone, -- when the order was fulfilled/delivered
    quantity integer NOT NULL DEFAULT 1,
    unit_price numeric(10, 2) NOT NULL, -- price at the time of order (may differ from service.price)
    total_price numeric(12, 2) NOT NULL, -- quantity * unit_price
    status character varying(50) NOT NULL, -- e.g., Requested, InProgress, Delivered, Billed, Cancelled
    notes text, -- special instructions or notes about the order
    bill_id character varying(64), -- FK to bills/invoices (optional, links to folio)
    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] For each guest, show the count of service orders they placed for services in the 'Food & Beverage' department. Include the guest's full name and the order count.

[Assistant] SELECT T1.first_name, T1.last_name, COUNT(T2.order_id) FROM hospitality_technology.guests AS T1 JOIN hospitality_technology.service_orders AS T2 ON T1.guest_id = T2.guest_id JOIN hospitality_technology.services AS T3 ON T2.service_id = T3.service_id WHERE T3.department = 'Food & Beverage' GROUP BY T1.guest_id, T1.first_name, T1.last_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.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] List all reviews where the cleanliness rating is 3 or below. Include the review comment and the full name of the guest who submitted it.

[Assistant] SELECT T1.comment, T2.first_name, T2.last_name FROM hospitality_technology.reviews AS T1 JOIN hospitality_technology.guests AS T2 ON T1.guest_id = T2.guest_id WHERE T1.rating_cleanliness <= 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 smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )

[User] List tokens with net outflow (type=2) on the 'Ethereum' chain. Show token_symbol and total usd_value sold.

[Assistant]
SELECT token_symbol, SUM(usd_value) AS total_sold
FROM smart_money_token_inflow
WHERE type = 2 AND chain = 'Ethereum'
GROUP BY token_symbol;

[User] Now limit to tokens with total_sold above 10000 and order by total_sold descending.

[Assistant]
SELECT token_symbol, SUM(usd_value) AS total_sold
FROM smart_money_token_inflow
WHERE type = 2 AND chain = 'Ethereum'
GROUP BY token_symbol
HAVING SUM(usd_value) > 10000
ORDER BY total_sold DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)

[User] List the names of all open cases, the name of the client for each case, and the name of the lead lawyer, but only for cases where the lead lawyer specializes in 'Family Law'.

[Assistant] SELECT T1.case_name ,  T2.first_name ,  T2.last_name ,  T3.first_name ,  T3.last_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T3 ON T1.lead_lawyer_id  =  T3.lawyer_id WHERE T1.status  =  'Open' AND T3.specialization  =  'Family Law'

[User] Actually, could you change the specialization filter to 'Criminal Law' and include the case number? Also, please sort the results by the client's last name.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.first_name ,  T2.last_name ,  T3.first_name ,  T3.last_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T3 ON T1.lead_lawyer_id  =  T3.lawyer_id WHERE T1.status  =  'Open' AND T3.specialization  =  'Criminal Law' ORDER BY T2.last_name

[User] Okay, now just show the cases that were opened after '2023-07-01'.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.first_name ,  T2.last_name ,  T3.first_name ,  T3.last_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T3 ON T1.lead_lawyer_id  =  T3.lawyer_id WHERE T1.status  =  'Open' AND T3.specialization  =  'Criminal Law' AND T1.date_opened  >  '2023-07-01' ORDER BY T2.last_name


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )
CREATE TABLE financial_services.transactions ( transaction_id text, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.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 character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
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] Show me the average high price and average low price for each security sector using market data.

[Assistant] SELECT T1.sector, AVG(T2.high_price) AS average_high_price, AVG(T2.low_price) AS average_low_price FROM financial_services.securities AS T1 JOIN financial_services.market_data AS T2 ON T1.security_id = T2.security_id WHERE T1.sector IS NOT NULL GROUP BY T1.sector

[User] Restrict the data to market data points from 2023.

[Assistant] SELECT T1.sector, AVG(T2.high_price) AS average_high_price, AVG(T2.low_price) AS average_low_price FROM financial_services.securities AS T1 JOIN financial_services.market_data AS T2 ON T1.security_id = T2.security_id WHERE T1.sector IS NOT NULL AND EXTRACT(YEAR FROM T2.data_timestamp) = 2023 GROUP BY T1.sector


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.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )

[User] How many posts are currently marked as 'private' visibility?

[Assistant] SELECT COUNT(*) FROM social_media.posts WHERE visibility = 'private'


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.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, 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.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )

[User] List all unique service categories and the count of services in each category.

[Assistant] SELECT category, COUNT(service_id) FROM hospitality_technology.services GROUP BY category;

[User] Only include categories with more than 10 services and order the results by the count descending.

[Assistant] SELECT category, COUNT(service_id) FROM hospitality_technology.services GROUP BY category HAVING COUNT(service_id) > 10 ORDER BY COUNT(service_id) DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)

[User] I want to find regions where the average number of current_players across servers exceeds 200. Provide a SQL query that lists each region and its average current_players.

[Assistant]
SELECT region, AVG(current_players) AS avg_players
FROM gaming_technology.servers
GROUP BY region
HAVING AVG(current_players) > 200;

[User] Now list all servers in those regions alongside the computed average.

[Assistant]
SELECT s.region, s.server_id, s.server_name, s.current_players, stats.avg_players
FROM gaming_technology.servers s
JOIN (
  SELECT region, AVG(current_players) AS avg_players
  FROM gaming_technology.servers
  GROUP BY region
  HAVING AVG(current_players) > 200
) stats ON s.region = stats.region;

[User] Exclude any servers that are currently offline.

[Assistant]
SELECT s.region, s.server_id, s.server_name, s.current_players, stats.avg_players
FROM gaming_technology.servers s
JOIN (
  SELECT region, AVG(current_players) AS avg_players
  FROM gaming_technology.servers
  GROUP BY region
  HAVING AVG(current_players) > 200
) stats ON s.region = stats.region
WHERE s.status <> 'offline';

[User] Finally, order the results by stats.avg_players descending and then by s.current_players descending.

[Assistant]
SELECT s.region, s.server_id, s.server_name, s.current_players, stats.avg_players
FROM gaming_technology.servers s
JOIN (
  SELECT region, AVG(current_players) AS avg_players
  FROM gaming_technology.servers
  GROUP BY region
  HAVING AVG(current_players) > 200
) stats ON s.region = stats.region
WHERE s.status <> 'offline'
ORDER BY stats.avg_players DESC, s.current_players DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )

[User] Show me the number of fuel logs per location, including the location name and city.

[Assistant]
SELECT fl.location_id, loc.name AS location_name, loc.city, COUNT(*) AS fuel_log_count
FROM transportation.fuel_logs fl
JOIN transportation.locations loc ON fl.location_id = loc.location_id
GROUP BY fl.location_id, loc.name, loc.city;

[User] Can you only include locations where there were more than 10 fueling events?

[Assistant]
SELECT fl.location_id, loc.name AS location_name, loc.city, COUNT(*) AS fuel_log_count
FROM transportation.fuel_logs fl
JOIN transportation.locations loc ON fl.location_id = loc.location_id
GROUP BY fl.location_id, loc.name, loc.city
HAVING COUNT(*) > 10;

[User] Also, show the total fuel quantity supplied at each of these locations.

[Assistant]
SELECT fl.location_id, loc.name AS location_name, loc.city, COUNT(*) AS fuel_log_count, SUM(fl.quantity) AS total_fuel_quantity
FROM transportation.fuel_logs fl
JOIN transportation.locations loc ON fl.location_id = loc.location_id
GROUP BY fl.location_id, loc.name, loc.city
HAVING COUNT(*) > 10;

[User] Sort the result so that the location with the highest total fuel quantity supplied comes first.

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

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

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


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

[User] Show all active customers who live in the same zip_code.

[Assistant]
SELECT a.customer_id AS cust1,
       b.customer_id AS cust2,
       a.zip_code
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.zip_code = b.zip_code
 AND a.customer_id < b.customer_id
WHERE a.status = 'Active'
  AND b.status = 'Active';

[User] Please ensure we don't list duplicate pairs and order by zip_code and cust1.

[Assistant]
SELECT a.customer_id AS cust1,
       b.customer_id AS cust2,
       a.zip_code
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.zip_code = b.zip_code
 AND a.customer_id < b.customer_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
ORDER BY a.zip_code, a.customer_id;

[User] Include the city and state in the result as well.

[Assistant]
SELECT a.customer_id AS cust1,
       b.customer_id AS cust2,
       a.zip_code,
       a.city,
       a.state
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.zip_code = b.zip_code
 AND a.customer_id < b.customer_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
ORDER BY a.zip_code, a.customer_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.addresses ( address_id.text, public_key.text, balance.numeric )
CREATE TABLE blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )

[User] Show me all wallet addresses along with their public keys and balances, but only for wallets that have a balance greater than 1000.

[Assistant] SELECT w.address_id, a.public_key, a.balance FROM blockchain.wallets w JOIN blockchain.addresses a ON w.address_id = a.address_id WHERE a.balance > 1000;

[User] Now filter these results to only show wallets where the private_key starts with '0x1'.

[Assistant] SELECT w.address_id, a.public_key, a.balance FROM blockchain.wallets w JOIN blockchain.addresses a ON w.address_id = a.address_id WHERE a.balance > 1000 AND w.private_key LIKE '0x1%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)

[User] I need a list of departments and the number of current employees in each department.

[Assistant]
SELECT department,
       COUNT(*) AS employee_count
FROM government_services.employees
WHERE termination_date IS NULL
GROUP BY department;

[User] Only include departments with more than 3 employees.

[Assistant]
SELECT department,
       COUNT(*) AS employee_count
FROM government_services.employees
WHERE termination_date IS NULL
GROUP BY department
HAVING COUNT(*) > 3;

[User] Now include the earliest hire date for each department as well.

[Assistant]
SELECT department,
       COUNT(*) AS employee_count,
       MIN(hire_date) AS earliest_hire_date
FROM government_services.employees
WHERE termination_date IS NULL
GROUP BY department
HAVING COUNT(*) > 3;

[User] Also exclude employees whose access_level is 'Intern'.

[Assistant]
SELECT department,
       COUNT(*) AS employee_count,
       MIN(hire_date) AS earliest_hire_date
FROM government_services.employees
WHERE termination_date IS NULL
  AND access_level <> 'Intern'
GROUP BY department
HAVING COUNT(*) > 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.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, show the transaction id and the total number of unique addresses involved in token transfers for that transaction (both as sender and receiver).

[Assistant]
SELECT transaction_id, COUNT(DISTINCT addr) AS unique_address_count
FROM (
    SELECT transaction_id, from_address AS addr FROM web3.token_transfers
    UNION ALL
    SELECT transaction_id, to_address AS addr FROM web3.token_transfers
) a
GROUP BY transaction_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)
CREATE TABLE insurance.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )

[User] List all agents who have sold policies with a coverage limit above 500000. Show agent_id, first_name, last_name, and the count of such policies as policy_count.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, COUNT(p.policy_id) AS policy_count
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE p.coverage_limit > 500000
GROUP BY a.agent_id, a.first_name, a.last_name;

[User] Actually, include the sum of premium_amount for each of those agents as total_premium as well.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, COUNT(p.policy_id) AS policy_count, SUM(p.premium_amount) AS total_premium
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE p.coverage_limit > 500000
GROUP BY a.agent_id, a.first_name, a.last_name;

[User] And restrict to agents whose commission_rate is greater than 0.06.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, COUNT(p.policy_id) AS policy_count, SUM(p.premium_amount) AS total_premium
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE p.coverage_limit > 500000
  AND a.commission_rate > 0.06
GROUP BY a.agent_id, a.first_name, a.last_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )

[User] I want to know the number of agencies established each year by jurisdiction level.

[Assistant]
SELECT jurisdiction_level, EXTRACT(YEAR FROM established_date) AS year, COUNT(*) AS agency_count
FROM government_services.agencies
group by jurisdiction_level, year
ORDER BY jurisdiction_level, year;

[User] Only show years where more than 2 agencies were established.

[Assistant]
SELECT jurisdiction_level, year, agency_count
FROM (
  SELECT jurisdiction_level, EXTRACT(YEAR FROM established_date) AS year, COUNT(*) AS agency_count
  FROM government_services.agencies
  GROUP BY jurisdiction_level, year
) t
WHERE agency_count > 2
ORDER BY jurisdiction_level, year;

[User] Now only include agencies in the 'State' jurisdiction level.

[Assistant]
SELECT jurisdiction_level, year, agency_count
FROM (
  SELECT jurisdiction_level, EXTRACT(YEAR FROM established_date) AS year, COUNT(*) AS agency_count
  FROM government_services.agencies
  WHERE jurisdiction_level = 'State'
  GROUP BY jurisdiction_level, year
) t
WHERE agency_count > 2
ORDER BY year;

[User] Sort the results by agency_count in descending order.

[Assistant]
SELECT jurisdiction_level, year, agency_count
FROM (
  SELECT jurisdiction_level, EXTRACT(YEAR FROM established_date) AS year, COUNT(*) AS agency_count
  FROM government_services.agencies
  WHERE jurisdiction_level = 'State'
  GROUP BY jurisdiction_level, year
) t
WHERE agency_count > 2
ORDER BY agency_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 insurance.customers ( customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, ssn_hash character varying(128), address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL DEFAULT 'USA', phone_number character varying(30), email character varying(128) UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, status character varying(20) NOT NULL DEFAULT 'Active', PRIMARY KEY (customer_id) )
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )

[User] List all premium payments along with the payment date, amount, and the status of the related policy.

[Assistant]
SELECT pp.payment_id, pp.payment_date, pp.amount_paid, p.status AS policy_status
FROM insurance.premium_payments pp
JOIN insurance.policies p ON pp.policy_id = p.policy_id;

[User] Only include payments where the policy status is 'Expired'.

[Assistant]
SELECT pp.payment_id, pp.payment_date, pp.amount_paid, p.status AS policy_status
FROM insurance.premium_payments pp
JOIN insurance.policies p ON pp.policy_id = p.policy_id
WHERE p.status = 'Expired';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )

[User] List the citizen_id, first_name, last_name, and registration_date for all citizens who registered during March 2024.

[Assistant]
SELECT citizen_id, first_name, last_name, registration_date
FROM government_services.citizens
WHERE registration_date >= '2024-03-01'
  AND registration_date < '2024-04-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 gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)

[User] Can you show me the total number of each item acquired by every player, along with their player_id and item_id?

[Assistant] SELECT player_id, item_id, SUM(quantity) AS total_acquired FROM gaming_technology.player_inventory GROUP BY player_id, item_id;

[User] I think I also need the most recent acquisition timestamp for each player and item combination.

[Assistant] SELECT player_id, item_id, SUM(quantity) AS total_acquired, MAX(acquired_at) AS last_acquired_at FROM gaming_technology.player_inventory GROUP BY player_id, item_id;

[User] Can you only include combinations where total_acquired is greater than 3?

[Assistant] SELECT player_id, item_id, SUM(quantity) AS total_acquired, MAX(acquired_at) AS last_acquired_at FROM gaming_technology.player_inventory GROUP BY player_id, item_id HAVING SUM(quantity) > 3;

[User] Also, please order the results by last_acquired_at descending.

[Assistant] SELECT player_id, item_id, SUM(quantity) AS total_acquired, MAX(acquired_at) AS last_acquired_at FROM gaming_technology.player_inventory GROUP BY player_id, item_id HAVING SUM(quantity) > 3 ORDER BY last_acquired_at DESC;


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

[User] Retrieve the first and last names of passengers along with the total sum of fares they've paid for bookings with status 'Completed', ordered by the sum descending.

[Assistant]
SELECT p.first_name, p.last_name, SUM(b.fare) AS total_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.status = 'Completed'
GROUP BY p.first_name, p.last_name
ORDER BY total_fare DESC;

[User] Now, modify the query to include only those passengers who have made more than three completed bookings.

[Assistant]
SELECT p.first_name, p.last_name, SUM(b.fare) AS total_fare, COUNT(b.booking_id) AS booking_count
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.status = 'Completed'
GROUP BY p.first_name, p.last_name
HAVING COUNT(b.booking_id) > 3
ORDER BY total_fare 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 financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)

[User] Show the number of securities per exchange and the average length of their ticker symbols, including only exchanges that have more than 5 securities.

[Assistant]
SELECT exchange, COUNT(*) AS securities_count, AVG(LENGTH(ticker_symbol)) AS avg_ticker_length
FROM financial_services.securities
GROUP BY exchange
HAVING COUNT(*) > 5;

[User] Actually, exclude any entries where exchange is NULL.

[Assistant]
SELECT exchange, COUNT(*) AS securities_count, AVG(LENGTH(ticker_symbol)) AS avg_ticker_length
FROM financial_services.securities
WHERE exchange IS NOT NULL
GROUP BY exchange
HAVING COUNT(*) > 5;

[User] Also, sort the output by the securities_count in descending order.

[Assistant]
SELECT exchange, COUNT(*) AS securities_count, AVG(LENGTH(ticker_symbol)) AS avg_ticker_length
FROM financial_services.securities
WHERE exchange IS NOT NULL
GROUP BY exchange
HAVING COUNT(*) > 5
ORDER BY securities_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 transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] I want to see the total fare and number of bookings for each passenger.

[Assistant]
SELECT b.passenger_id, COUNT(b.booking_id) AS booking_count, SUM(b.fare) AS total_fare
FROM transportation.bookings b
GROUP BY b.passenger_id;

[User] Only show passengers whose total fare exceeds 200.

[Assistant]
SELECT b.passenger_id, COUNT(b.booking_id) AS booking_count, SUM(b.fare) AS total_fare
FROM transportation.bookings b
GROUP BY b.passenger_id
HAVING SUM(b.fare) > 200;

[User] Also include the latest booking_time for each of those passengers.

[Assistant]
SELECT b.passenger_id, COUNT(b.booking_id) AS booking_count, SUM(b.fare) AS total_fare, MAX(b.booking_time) AS last_booking
FROM transportation.bookings b
GROUP BY b.passenger_id
HAVING SUM(b.fare) > 200;

[User] Exclude any bookings with status 'Cancelled'.

[Assistant]
SELECT b.passenger_id, COUNT(b.booking_id) AS booking_count, SUM(b.fare) AS total_fare, MAX(b.booking_time) AS last_booking
FROM transportation.bookings b
WHERE b.status <> 'Cancelled'
GROUP BY b.passenger_id
HAVING SUM(b.fare) > 200;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.reservations ( reservation_id.text, property_id.text, guest_id.text, room_id.text, room_type_id.text, check_in_date.date, check_out_date.date, actual_check_in_ts.timestamp, actual_check_out_ts.timestamp, num_adults.integer, num_children.integer, status.text, booking_source.text, rate_plan_id.text, total_amount.numeric, amount_paid.numeric, special_requests.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services (
    service_id 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.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] For each property, calculate the total outstanding balance from reservations where the amount paid is less than the total amount. Show the property name and the total outstanding balance.

[Assistant] SELECT T2.property_name, SUM(T1.total_amount - T1.amount_paid) AS total_outstanding_balance FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.amount_paid < T1.total_amount GROUP BY T2.property_id, T2.property_name ORDER BY total_outstanding_balance DESC;

[User] Now, filter the results to only include properties where the total outstanding balance is greater than 5000.

[Assistant] SELECT T2.property_name, SUM(T1.total_amount - T1.amount_paid) AS total_outstanding_balance FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.amount_paid < T1.total_amount GROUP BY T2.property_id, T2.property_name HAVING SUM(T1.total_amount - T1.amount_paid) > 5000 ORDER BY total_outstanding_balance DESC;

[User] Also, limit the results to the top 10 properties by total outstanding balance.

[Assistant] SELECT T2.property_name, SUM(T1.total_amount - T1.amount_paid) AS total_outstanding_balance FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.amount_paid < T1.total_amount GROUP BY T2.property_id, T2.property_name HAVING SUM(T1.total_amount - T1.amount_paid) > 5000 ORDER BY total_outstanding_balance 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 insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)

[User] List all active policies, including their policy number, start date, end date, premium amount, and the name of the insurance product.

[Assistant] SELECT T1.policy_number, T1.start_date, T1.end_date, T1.premium_amount, T2.product_name FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id WHERE T1.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 healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text PRIMARY KEY, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] Show the record_id, patient_id, record_date and systolic blood pressure from vitals for all medical records where the systolic blood pressure is above 140.

[Assistant]
SELECT record_id, patient_id, record_date, (vitals->>'systolic')::INT AS systolic
FROM healthcare.medical_records
WHERE (vitals->>'systolic')::INT > 140;

[User] Only include those records for patients who currently have a primary insurance that is active.

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.record_date, (mr.vitals->>'systolic')::INT AS systolic
FROM healthcare.medical_records mr
JOIN healthcare.patient_insurance pi ON mr.patient_id = pi.patient_id
WHERE (mr.vitals->>'systolic')::INT > 140
  AND pi.is_primary = TRUE
  AND pi.effective_date <= CURRENT_DATE
  AND (pi.expiration_date IS NULL OR pi.expiration_date > CURRENT_DATE);


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

[User] Show me the username and email of all users who own at least one wallet.

[Assistant] SELECT DISTINCT T1.username, T1.email FROM blockchain.users AS T1 JOIN blockchain.wallets AS T2 ON T1.user_id = T2.user_id;


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] Show the top 5 narratives by 24h volume, displaying narrative and volume_24h.

[Assistant] SELECT narrative, volume_24h FROM narrative_info ORDER BY volume_24h 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 hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
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, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, 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] Get the total number of guests for each country_code.

[Assistant]
SELECT country_code, COUNT(*) AS guest_count
FROM hospitality_technology.guests
GROUP BY country_code;

[User] Actually, only include countries with at least 5 guests and order by guest_count descending.

[Assistant]
SELECT country_code, COUNT(*) AS guest_count
FROM hospitality_technology.guests
GROUP BY country_code
HAVING COUNT(*) >= 5
ORDER BY guest_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 hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id.text, property_id.text, guest_id.text, room_id.text, room_type_id.text, check_in_date.date, check_out_date.date, actual_check_in_ts.timestamp, actual_check_out_ts.timestamp, num_adults.integer, num_children.integer, status.text, booking_source.text, rate_plan_id.text, total_amount.numeric, amount_paid.numeric, special_requests.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )

[User] List all guests who have made reservations for rooms located on floor 1 along with the property name and the room number.

[Assistant]
SELECT g.guest_id, g.first_name, g.last_name, r.property_id, ro.room_number
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r ON g.guest_id = r.guest_id
JOIN hospitality_technology.rooms ro ON r.room_id = ro.room_id
WHERE ro.floor = 1;

[User] Could you also include the type name of the room and filter to only show guests whose reservations are currently 'CheckedIn'?

[Assistant]
SELECT g.guest_id, g.first_name, g.last_name, r.property_id, ro.room_number, rt.type_name
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r ON g.guest_id = r.guest_id
JOIN hospitality_technology.rooms ro ON r.room_id = ro.room_id
JOIN hospitality_technology.room_types rt ON ro.room_type_id = rt.room_type_id
WHERE ro.floor = 1 AND r.status = 'CheckedIn';


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, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)

[User] I need the total amount and count of payments for each policy.

[Assistant]
SELECT policy_id,
       COUNT(*) AS payment_count,
       SUM(amount_paid) AS total_paid
FROM insurance.premium_payments
GROUP BY policy_id;

[User] Only include policies where the total_paid is greater than 10000.

[Assistant]
SELECT policy_id,
       COUNT(*) AS payment_count,
       SUM(amount_paid) AS total_paid
FROM insurance.premium_payments
GROUP BY policy_id
HAVING SUM(amount_paid) > 10000;

[User] Now consider only completed payments.

[Assistant]
SELECT policy_id,
       COUNT(*) AS payment_count,
       SUM(amount_paid) AS total_paid
FROM insurance.premium_payments
WHERE status = 'Completed'
GROUP BY policy_id
HAVING SUM(amount_paid) > 10000;

[User] Also include the date of the most recent payment for each policy.

[Assistant]
SELECT t.policy_id,
       t.payment_count,
       t.total_paid,
       lp.last_payment_date
FROM (
  SELECT policy_id,
         COUNT(*) AS payment_count,
         SUM(amount_paid) AS total_paid
  FROM insurance.premium_payments
  WHERE status = 'Completed'
  GROUP BY policy_id
  HAVING SUM(amount_paid) > 10000
) t
JOIN (
  SELECT policy_id,
         MAX(payment_date) AS last_payment_date
  FROM insurance.premium_payments
  WHERE status = 'Completed'
  GROUP BY policy_id
) lp ON t.policy_id = lp.policy_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )

[User] List the first and last names of employees and the number of services offered by their agency.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(s.service_id) AS service_count
FROM government_services.employees e
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Include only employees whose agency offers more than 3 services.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(s.service_id) AS service_count
FROM government_services.employees e
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id
GROUP BY e.employee_id, e.first_name, e.last_name
HAVING COUNT(s.service_id) > 3;

[User] Add the agency name to the result.

[Assistant]
SELECT e.first_name, e.last_name, ag.agency_name, COUNT(s.service_id) AS service_count
FROM government_services.employees e
JOIN government_services.agencies ag ON e.agency_id = ag.agency_id
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id
GROUP BY e.employee_id, e.first_name, e.last_name, ag.agency_name
HAVING COUNT(s.service_id) > 3;

[User] Now, only show services that are currently active in the count.

[Assistant]
SELECT e.first_name, e.last_name, ag.agency_name, COUNT(s.service_id) AS active_service_count
FROM government_services.employees e
JOIN government_services.agencies ag ON e.agency_id = ag.agency_id
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id AND s.is_active = TRUE
GROUP BY e.employee_id, e.first_name, e.last_name, ag.agency_name
HAVING COUNT(s.service_id) > 3;