[User] Find the contract ID, address, and deployer address for all contracts that have not emitted any events.

[Assistant] SELECT c.contract_id, c.address, c.deployer_address FROM web3.contracts AS c LEFT JOIN web3.events AS e ON c.contract_id = e.contract_id WHERE e.event_id IS NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] For each narrative in smart money token inflow, calculate the total usd_value and list the token symbol that has the highest liquidity from the DEX pool.

[Assistant]
SELECT i.narrative, SUM(i.usd_value) AS total_usd_inflow,
       (SELECT d.token_symbol
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity_token,
       (SELECT d.liquidity
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity
FROM smart_money_token_inflow i
GROUP BY i.narrative;

[User] Also include the average price_change_percentage_24h of that top liquidity token.

[Assistant]
SELECT i.narrative, SUM(i.usd_value) AS total_usd_inflow,
       (SELECT d.token_symbol
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity_token,
       (SELECT d.liquidity
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity,
       (SELECT d.price_change_percentage_24h
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS price_change_24h
FROM smart_money_token_inflow i
GROUP BY i.narrative;

[User] Filter to include only narratives that have more than 2 distinct tokens in the inflow records.

[Assistant]
SELECT i.narrative, SUM(i.usd_value) AS total_usd_inflow,
       (SELECT d.token_symbol
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity_token,
       (SELECT d.liquidity
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity,
       (SELECT d.price_change_percentage_24h
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS price_change_24h
FROM smart_money_token_inflow i
GROUP BY i.narrative
HAVING COUNT(DISTINCT i.token_symbol) > 2;

[User] Finally, only show narratives where the total usd_value exceeds 20000.

[Assistant]
SELECT i.narrative, SUM(i.usd_value) AS total_usd_inflow,
       (SELECT d.token_symbol
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity_token,
       (SELECT d.liquidity
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity,
       (SELECT d.price_change_percentage_24h
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS price_change_24h
FROM smart_money_token_inflow i
GROUP BY i.narrative
HAVING COUNT(DISTINCT i.token_symbol) > 2
   AND SUM(i.usd_value) > 20000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )
  "CREATE TABLE smart_money_token_inflow (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token",
    "usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token",
    "avg_price numeric(38,6), -- the average cost price of user spent on this token",
    "type int, -- the direction of the trade on this token. 1 means buying, 2 means selling",
    "address_amount integer, -- the amount of the user bought this token",
    "narrative character varying(100), -- the category or narrative of the token",
    "chain character varying(100), -- the chain that the token resides",
    ",PRIMARY KEY (token_address, chain)",


[User] Show me the top 5 narratives by market cap, along with their 24-hour trading volume and 7-day price change percentage.

[Assistant] SELECT narrative.text, volume_24h.numeric, price_change_percentage_7d.numeric FROM narrative_info ORDER BY market_cap.numeric DESC LIMIT 5;

[User] Can you also include the top 3 coins for each of these narratives?

[Assistant] SELECT narrative.text, volume_24h.numeric, price_change_percentage_7d.numeric, top_3_coins.text FROM narrative_info ORDER BY market_cap.numeric DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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 all medical records with the record_id, record_date, the patient's insurance policy_number, and the doctor's ID, for records linked to a currently active insurance policy.

[Assistant]
SELECT mr.record_id, mr.record_date, pi.policy_number, mr.doctor_id
FROM healthcare.medical_records mr
INNER JOIN healthcare.patient_insurance pi ON mr.patient_id = pi.patient_id
WHERE pi.expiration_date IS NULL OR pi.expiration_date >= CURRENT_DATE;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.medical_records ( record_id.text, patient_id.text, appointment_id.text, doctor_id.text, record_date.timestamp, chief_complaint.text, present_illness_history.text, past_medical_history.text, physical_examination_notes.text, assessment.text, treatment_plan.text, vitals.json, created_at.timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] List properties and the average base rate of their room types.

[Assistant] SELECT T1.property_name ,  AVG(T2.base_rate) FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id  =  T2.property_id GROUP BY T1.property_name

[User] Filter to only show properties where the average base rate is above 250.

[Assistant] SELECT T1.property_name ,  AVG(T2.base_rate) FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id  =  T2.property_id GROUP BY T1.property_name HAVING AVG(T2.base_rate)  >  250

[User] Also, only include properties in 'New York' or 'Florida' and order by average base rate descending.

[Assistant] SELECT T1.property_name ,  AVG(T2.base_rate) AS avg_base_rate FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id  =  T2.property_id WHERE T1.state IN ('New York', 'Florida') GROUP BY T1.property_name HAVING AVG(T2.base_rate)  >  250 ORDER BY avg_base_rate DESC

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


[User] Get the average overall review rating for each property. Return property_name and avg_rating.

[Assistant]
SELECT pr.property_name, AVG(r.rating_overall) AS avg_rating
FROM hospitality_technology.reviews r
JOIN hospitality_technology.properties pr ON r.property_id = pr.property_id
GROUP BY pr.property_name;

[User] Filter to only include properties with an average overall rating above 4.0.

[Assistant]
SELECT pr.property_name, AVG(r.rating_overall) AS avg_rating
FROM hospitality_technology.reviews r
JOIN hospitality_technology.properties pr ON r.property_id = pr.property_id
GROUP BY pr.property_name
HAVING AVG(r.rating_overall) > 4.0;

[User] Additionally, include the total number of reviews per property and order the results by avg_rating descending.

[Assistant]
SELECT pr.property_name,
       AVG(r.rating_overall) AS avg_rating,
       COUNT(r.review_id) AS review_count
FROM hospitality_technology.reviews r
JOIN hospitality_technology.properties pr ON r.property_id = pr.property_id
GROUP BY pr.property_name
HAVING AVG(r.rating_overall) > 4.0
ORDER BY avg_rating DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.guests (
    guest_id character varying(64) NOT NULL,  -- unique identifier for the guest profile
    first_name character varying(100) NOT NULL, -- guest's first name
    last_name character varying(100) NOT NULL, -- guest's last name
    email character varying(255) UNIQUE, -- guest's email address (unique identifier?)
    phone_number character varying(30), -- guest's phone number
    date_of_birth date, -- guest's date of birth
    address_line1 character varying(255), -- guest's home address
    city character varying(100),
    state_province character varying(100),
    postal_code character varying(20),
    country_code character varying(3),
    preferences text, -- notes on guest preferences (e.g., allergies, room location)
    loyalty_member_id character varying(64) UNIQUE, -- FK to loyalty_members table
    communication_consent boolean DEFAULT true, -- consent for marketing communications
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (guest_id)
)
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.payments (
    payment_id 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 guests who have made at least one reservation. Show their first and last names and the number of reservations they have made.

[Assistant]
SELECT g.first_name, g.last_name, COUNT(r.reservation_id) AS reservation_count
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r ON g.guest_id = r.guest_id
GROUP BY g.guest_id, g.first_name, g.last_name;

[User] Show only the guests who made 3 or more reservations and order by reservation_count descending.

[Assistant]
SELECT g.first_name, g.last_name, COUNT(r.reservation_id) AS reservation_count
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r ON g.guest_id = r.guest_id
GROUP BY g.guest_id, g.first_name, g.last_name
HAVING COUNT(r.reservation_id) >= 3
ORDER BY reservation_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.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.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )


[User] Calculate the total billable hours spent by each lawyer for entries in March 2024.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2024-03-01' AND '2024-03-31'
GROUP BY lawyer_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)


[User] What are the safety ratings or crash statistics for the Boeing 787 Dreamliner?

[Assistant] I'm sorry, but I don't have access to safety ratings or crash statistics for specific aircraft models like the Boeing 787 Dreamliner. My data is limited to the information in the aircraft_models table, which includes details such as model name, manufacturer, passenger capacity, and technical specifications. For safety-related information, I recommend consulting official aviation authorities or safety reports.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE manufacturing.aircraft_models ( model_id text, model_name text, manufacturer text, passenger_capacity integer, max_range_km integer, engine_type text, wingspan_m numeric, status text, first_flight_date date )


[User] Show me the first name, last name, and email for all clients registered in January 2023.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1;

[User] Only show those who have provided a phone number.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1 AND phone IS NOT NULL;

[User] Also, exclude any clients whose status is 'inactive'.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1 AND phone IS NOT NULL AND status != 'inactive';

[User] Order the results by last name, then first name.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1 AND phone IS NOT NULL AND status != 'inactive' ORDER BY last_name, first_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients (
    client_id character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_id)
)


[User] Show the number of users registered each month for 2024.

[Assistant]
SELECT
  date_trunc('month', created_at) AS month,
  COUNT(*) AS user_count
FROM trading_platform.users
WHERE created_at >= '2024-01-01'
  AND created_at < '2025-01-01'
GROUP BY month
ORDER BY month;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )


[User] Show me the total traded volume and the average price per security for trades executed last month.

[Assistant]
SELECT s.ticker_symbol,
       SUM(t.quantity) AS total_volume,
       AVG(t.price_per_unit) AS avg_price
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month')
  AND t.trade_timestamp < date_trunc('month', CURRENT_DATE)
GROUP BY s.ticker_symbol;

[User] Filter to only include those trades with status 'SETTLED' and execution_venue 'NYSE'.

[Assistant]
SELECT s.ticker_symbol,
       SUM(t.quantity) AS total_volume,
       AVG(t.price_per_unit) AS avg_price
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month')
  AND t.trade_timestamp < date_trunc('month', CURRENT_DATE)
  AND t.status = 'SETTLED'
  AND t.execution_venue = 'NYSE'
GROUP BY s.ticker_symbol;

[User] Now exclude any securities where the summed quantity is less than 1000.

[Assistant]
SELECT s.ticker_symbol,
       SUM(t.quantity) AS total_volume,
       AVG(t.price_per_unit) AS avg_price
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month')
  AND t.trade_timestamp < date_trunc('month', CURRENT_DATE)
  AND t.status = 'SETTLED'
  AND t.execution_venue = 'NYSE'
GROUP BY s.ticker_symbol
HAVING SUM(t.quantity) >= 1000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.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.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)
)
CREATE TABLE financial_services.trades ( trade_id.text, account_id.text, security_id.text, order_id.text, trade_type.text, quantity.numeric, price_per_unit.numeric, total_amount.numeric, commission.numeric, trade_timestamp.timestamp, settlement_date.date, status.text, execution_venue.text )
CREATE TABLE financial_services.market_data ( data_point_id bigint, security_id text, data_timestamp timestamp, open_price numeric, high_price numeric, low_price numeric, close_price numeric, adjusted_close_price numeric, volume bigint, source text )
CREATE TABLE financial_services.employees ( employee_id text, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )


[User] For each route type, show the total number of trips taken and the total distance covered across all trips for that type.

[Assistant] SELECT T1.type, COUNT(T2.trip_id), SUM(T1.distance_km) FROM transportation.routes AS T1 JOIN transportation.trips AS T2 ON T1.route_id = T2.route_id GROUP BY T1.type;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, 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.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )


[User] List the names of services for which documents are set to expire in the next 90 days.

[Assistant] SELECT DISTINCT T1.service_name FROM government_services.services AS T1 JOIN applications AS T2 ON T1.service_id = T2.service_id JOIN government_services.documents AS T3 ON T2.application_id = T3.application_id WHERE T3.expiry_date IS NOT NULL AND T3.expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '90 days'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
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 )


[User] List the username and the total number of notifications each user has received, and also count how many of those are still unread.

[Assistant]
SELECT u.username,
       COUNT(n.notification_id) AS total_notifications,
       SUM(CASE WHEN n.read_at IS NULL THEN 1 ELSE 0 END) AS unread_notifications
FROM trading_platform.users u
LEFT JOIN trading_platform.notifications n
  ON u.user_id = n.user_id
GROUP BY u.username;

[User] Actually, limit it to notifications sent in the last 7 days and only show users with at least 1 unread notification.

[Assistant]
SELECT u.username,
       COUNT(n.notification_id) AS total_notifications,
       SUM(CASE WHEN n.read_at IS NULL THEN 1 ELSE 0 END) AS unread_notifications
FROM trading_platform.users u
LEFT JOIN trading_platform.notifications n
  ON u.user_id = n.user_id
  AND n.sent_at >= NOW() - INTERVAL '7 days'
GROUP BY u.username
HAVING SUM(CASE WHEN n.read_at IS NULL THEN 1 ELSE 0 END) > 0;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.utxos ( utxo_id character varying(64) NOT NULL, transaction_id character varying(64) NOT NULL, output_index integer NOT NULL, address character varying(128) NOT NULL, amount numeric(38,14) NOT NULL, spent boolean NOT NULL, PRIMARY KEY (utxo_id) )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )
CREATE TABLE trading_platform.notifications ( notification_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, message text NOT NULL, sent_at timestamp NOT NULL, read_at timestamp, PRIMARY KEY (notification_id) )


[User] List all beneficiaries added in the last 6 months with a percentage share greater than 25%. Include their beneficiary ID, policy ID, customer ID, first name, last name, relationship, and percentage share. Order the results by the date they were added, oldest first.

[Assistant] SELECT beneficiary_id, policy_id, customer_id, first_name, last_name, relationship, percentage_share FROM insurance.policy_beneficiaries WHERE added_at >= CURRENT_DATE - INTERVAL '6 months' AND percentage_share > 25 ORDER BY added_at ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] Can you list the number of citizens registered each month in 2024? Please show the month and the citizen count.

[Assistant] SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month ORDER BY registration_month;

[User] Now, can you also show the number of verified citizens for each month?

[Assistant] SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count, SUM(CASE WHEN is_verified = true THEN 1 ELSE 0 END) AS verified_citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month ORDER BY registration_month;

[User] I see some months with zero verified citizens, but they still show up. Can you exclude months with zero verified citizens from the result?

[Assistant] SELECT registration_month, citizen_count, verified_citizen_count FROM (SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count, SUM(CASE WHEN is_verified = true THEN 1 ELSE 0 END) AS verified_citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month) sub WHERE verified_citizen_count > 0 ORDER BY registration_month;

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


[User] Show me the top 5 ERC20 tokens with the highest total supply on Ethereum, including their names, symbols, and contract addresses.

[Assistant] SELECT name, symbol, contract_address FROM token_metas WHERE is_erc20 = 1 ORDER BY CAST(total_supply AS decimal) DESC LIMIT 5;

[User] Can you join this with the token_prices_latest table to include the current price of each token?

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] Now filter these results to only show tokens where the price is greater than $0.10.

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price > 0.10 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_coins_metadata ( object_id varchar NOT NULL, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_collections ( blockchain.text, contract_address.text, name.text, symbol.text, deploy_block_number.bigint, deploy_block_time.bigint, erc_type.text, owner.text, traits.text, description.text, slug.text, media_info.text, image_url.text, banner_image_url.text, updated_at.bigint, banner.text, token_count.bigint, floor_price.text, floor_price_symbol.text, floor_price_contract.text, pk.integer )
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_bitcoin (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_bitcoin (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(255) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities_bitcoin (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(62) NOT NULL, -- Address sending the inscription
    to_address varchar(62) NOT NULL  -- Address receiving the inscription
)
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )


[User] Show me all room types with 'King' in the bed_type field, along with their property IDs and base rates.

[Assistant] SELECT room_type_id, property_id, type_name, bed_type, base_rate FROM hospitality_technology.room_types WHERE bed_type LIKE '%King%';

[User] Now, join this with the guests table to show only room types from properties where the guest's country code is 'USA' and the guest is a loyalty member.

[Assistant] SELECT rt.room_type_id, rt.property_id, rt.type_name, rt.bed_type, rt.base_rate FROM hospitality_technology.room_types rt JOIN hospitality_technology.guests g ON rt.property_id = g.property_id WHERE rt.bed_type LIKE '%King%' AND g.country_code = 'USA' AND g.loyalty_member_id IS NOT NULL;

[User] The query is missing the max occupancy. Can you include that as well?

[Assistant] SELECT rt.room_type_id, rt.property_id, rt.type_name, rt.bed_type, rt.base_rate, rt.max_occupancy FROM hospitality_technology.room_types rt JOIN hospitality_technology.guests g ON rt.property_id = g.property_id WHERE rt.bed_type LIKE '%King%' AND g.country_code = 'USA' AND g.loyalty_member_id IS NOT NULL;

[User] Actually, I need to see only room types with a base rate below $300, and order them by max occupancy in descending order.

[Assistant] SELECT rt.room_type_id, rt.property_id, rt.type_name, rt.bed_type, rt.base_rate, rt.max_occupancy FROM hospitality_technology.room_types rt JOIN hospitality_technology.guests g ON rt.property_id = g.property_id WHERE rt.bed_type LIKE '%King%' AND g.country_code = 'USA' AND g.loyalty_member_id IS NOT NULL AND rt.base_rate < 300 ORDER BY rt.max_occupancy DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text, 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 )


[User] Show the invoice number, issue date, total amount, and the client's full name for all invoices, including only those invoices that have not been paid fully.

[Assistant] SELECT i.invoice_number, i.issue_date, i.total_amount, c.first_name || ' ' || c.last_name AS client_full_name FROM legal_services.invoices i JOIN legal_services.clients c ON i.client_id = c.client_id WHERE i.amount_paid < i.total_amount;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id.text, first_name.text, last_name.text, company_name.text, email.text, phone.text, address.text, date_registered.timestamp, status.text )
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.time_entries ( entry_id.text, case_id.text, lawyer_id.text, date_worked.date, hours_spent.numeric, billing_rate.numeric, description.text, is_billable.boolean, is_billed.boolean, invoice_id.text, created_at.timestamp )
CREATE TABLE legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )


[User] List all unique pairs of routes that share the same destination location, and show the route numbers and their type for both routes.

[Assistant]
SELECT r1.route_number AS route_number_1, r1.type AS type_1, r2.route_number AS route_number_2, r2.type AS type_2, r1.destination_location_id
FROM transportation.routes r1
JOIN transportation.routes r2
  ON r1.destination_location_id = r2.destination_location_id
  AND r1.route_id < r2.route_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )


[User] Which chain has the highest total USD inflow from buy transactions (type=1), and how many distinct tokens were involved in that inflow?

[Assistant]
SELECT chain, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY chain
ORDER BY total_inflow DESC
LIMIT 1;

[User] I also want to see the average price at which those tokens were bought for that chain.

[Assistant]
WITH inflow AS (
  SELECT chain, SUM(usd_value) AS total_inflow
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY chain
), top_chain AS (
  SELECT chain FROM inflow ORDER BY total_inflow DESC LIMIT 1
)
SELECT i.chain, AVG(i.avg_price) AS avg_buy_price
FROM smart_money_token_inflow i
JOIN top_chain t ON i.chain = t.chain
WHERE i.type = 1;

[User] Actually, filter to narratives where the total USD inflow is above 50000.

[Assistant]
SELECT narrative, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY narrative
HAVING SUM(usd_value) > 50000;

[User] Please order the results by average price descending and show the top 2 chains.

[Assistant]
SELECT chain, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens, AVG(avg_price) AS avg_buy_price
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY chain
ORDER BY avg_buy_price DESC
LIMIT 2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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] I want a list of all claims where at least one document is larger than 2 megabytes. Include the claim ID, incident date, and the file name of such documents.

[Assistant]
SELECT c.claim_id, c.incident_date, d.file_name
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.file_size_bytes > 2097152;

[User] Actually, please also show the document type and only include documents uploaded after June 1, 2024.

[Assistant]
SELECT c.claim_id, c.incident_date, d.file_name, d.document_type
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.file_size_bytes > 2097152
  AND d.uploaded_at > '2024-06-01';

[User] Add the file size in kilobytes and order the results by file size descending.

[Assistant]
SELECT c.claim_id, c.incident_date, d.file_name, d.document_type, (d.file_size_bytes/1024) AS file_size_kb
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.file_size_bytes > 2097152
  AND d.uploaded_at > '2024-06-01'
ORDER BY d.file_size_bytes DESC;

[User] Sorry, I'm getting some records where file_size_bytes is NULL. Please exclude those from the results.

[Assistant]
SELECT c.claim_id, c.incident_date, d.file_name, d.document_type, (d.file_size_bytes/1024) AS file_size_kb
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.file_size_bytes > 2097152
  AND d.uploaded_at > '2024-06-01'
  AND d.file_size_bytes IS NOT NULL
ORDER BY d.file_size_bytes DESC;

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


[User] Show me the top 5 users who have created the most wallets, along with their email addresses and the creation date of their first wallet.

[Assistant] SELECT u.user_id, u.email, MIN(w.created_at) AS first_wallet_date, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.user_id, u.email ORDER BY wallet_count DESC LIMIT 5;

[User] Now modify the query to only include wallets created in the last 6 months.

[Assistant] SELECT u.user_id, u.email, MIN(w.created_at) AS first_wallet_date, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id WHERE w.created_at >= NOW() - INTERVAL '6 months' GROUP BY u.user_id, u.email ORDER BY wallet_count DESC LIMIT 5;

[User] Actually, I want to see the total balance across all wallets for each of these users, calculated from unspent UTXOs.

[Assistant] SELECT u.user_id, u.email, MIN(w.created_at) AS first_wallet_date, COUNT(w.wallet_id) AS wallet_count, COALESCE(SUM(ut.amount), 0) AS total_balance FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id LEFT JOIN trading_platform.utxos ut ON w.address = ut.address AND ut.spent = false WHERE w.created_at >= NOW() - INTERVAL '6 months' GROUP BY u.user_id, u.email ORDER BY wallet_count DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)


[User] Show all room types that offer 'WiFi' in their amenities.

[Assistant] SELECT room_type_id, property_id, type_name, amenities FROM hospitality_technology.room_types WHERE amenities LIKE '%WiFi%';

[User] Only include those with a base rate below 100 and return the results sorted by base_rate ascending.

[Assistant] SELECT room_type_id, property_id, type_name, amenities, base_rate FROM hospitality_technology.room_types WHERE amenities LIKE '%WiFi%' AND base_rate < 100 ORDER BY base_rate ASC;

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


[User] List all appointments scheduled in the next 7 days along with the appointment_id, appointment_time, patient's full name, doctor's full name, and the patient's primary insurance plan_name.

[Assistant]
SELECT ap.appointment_id,
       ap.appointment_time,
       pt.first_name || ' ' || pt.last_name AS patient_name,
       d.first_name || ' ' || d.last_name AS doctor_name,
       ip.plan_name
FROM healthcare.appointments ap
JOIN healthcare.patients pt ON ap.patient_id = pt.patient_id
JOIN healthcare.doctors d ON ap.doctor_id = d.doctor_id
JOIN healthcare.patient_insurance pi ON pt.patient_id = pi.patient_id AND pi.is_primary = TRUE
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE ap.appointment_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '7 days';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] Calculate for each player the timespan between their earliest and latest achievement unlocks.

[Assistant]
SELECT pa_min.player_id,
       pa_max.max_time - pa_min.min_time AS span
FROM (
  SELECT player_id,
         MIN(unlocked_at) AS min_time
  FROM gaming_technology.player_achievements
  GROUP BY player_id
) pa_min
JOIN (
  SELECT player_id,
         MAX(unlocked_at) AS max_time
  FROM gaming_technology.player_achievements
  GROUP BY player_id
) pa_max
  ON pa_min.player_id = pa_max.player_id;

[User] Exclude players who only have one achievement.

[Assistant]
WITH extremes AS (
  SELECT player_id,
         MIN(unlocked_at) AS min_time,
         MAX(unlocked_at) AS max_time,
         COUNT(*) AS cnt
  FROM gaming_technology.player_achievements
  GROUP BY player_id
  HAVING COUNT(*) > 1
)
SELECT player_id,
       max_time - min_time AS span
FROM extremes;

[User] Also only keep players where the span is greater than 30 days.

[Assistant]
WITH extremes AS (
  SELECT player_id,
         MIN(unlocked_at) AS min_time,
         MAX(unlocked_at) AS max_time,
         COUNT(*) AS cnt
  FROM gaming_technology.player_achievements
  GROUP BY player_id
  HAVING COUNT(*) > 1
)
SELECT player_id,
       max_time - min_time AS span
FROM extremes
WHERE max_time - min_time > INTERVAL '30 days';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)


[User] List the first and last names of employees and the full name of the citizens for whom they have scheduled appointments.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T3.first_name ,  T3.last_name FROM government_services.employees AS T1 JOIN government_services.appointments AS T2 ON T1.employee_id  =  T2.employee_id JOIN government_services.citizens AS T3 ON T2.citizen_id  =  T3.citizen_id

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text 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.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, 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 )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] Show me all active electric vehicles along with their make, model, and license plate, ordered by acquisition date with the newest first.

[Assistant] SELECT vehicle_id, make, model, license_plate, acquisition_date FROM transportation.vehicles WHERE status = 'active' AND fuel_type = 'electric' ORDER BY acquisition_date DESC;

[User] Now include the depot_id for these vehicles and filter to only show vehicles acquired in the last 2 years.

[Assistant] SELECT vehicle_id, make, model, license_plate, acquisition_date, depot_id FROM transportation.vehicles WHERE status = 'active' AND fuel_type = 'electric' AND acquisition_date >= CURRENT_DATE - INTERVAL '2 years' ORDER BY acquisition_date DESC;

[User] Can you also include the vehicle's capacity and order the results by capacity in descending order?

[Assistant] SELECT vehicle_id, make, model, license_plate, acquisition_date, depot_id, capacity FROM transportation.vehicles WHERE status = 'active' AND fuel_type = 'electric' AND acquisition_date >= CURRENT_DATE - INTERVAL '2 years' ORDER BY capacity DESC;

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


[User] Show the first name, last name, and position of all staff members who are not currently active.

[Assistant] SELECT first_name ,  last_name ,  position FROM hospitality_technology.staff WHERE is_active  =  false

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.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 prescription ID, medication ID, and the record ID for all prescriptions linked to medical records where the chief complaint contains 'cough'.

[Assistant] SELECT T1.prescription_id, T1.medication_id, T1.record_id FROM healthcare.prescriptions AS T1 JOIN healthcare.medical_records AS T2 ON T1.record_id = T2.record_id WHERE T2.chief_complaint LIKE '%cough%';

[User] Add the dosage and quantity dispensed for these prescriptions.

[Assistant] SELECT T1.prescription_id, T1.medication_id, T1.record_id, T1.dosage, T1.quantity_dispensed FROM healthcare.prescriptions AS T1 JOIN healthcare.medical_records AS T2 ON T1.record_id = T2.record_id WHERE T2.chief_complaint LIKE '%cough%';

[User] Instead of record ID, show the record date and the patient's full name.

[Assistant] SELECT T1.prescription_id, T1.medication_id, T1.dosage, T1.quantity_dispensed, T2.record_date, T3.first_name, T3.last_name FROM healthcare.prescriptions AS T1 JOIN healthcare.medical_records AS T2 ON T1.record_id = T2.record_id JOIN healthcare.patients AS T3 ON T1.patient_id = T3.patient_id WHERE T2.chief_complaint LIKE '%cough%';

[User] Now, filter the results to only include prescriptions issued after January 1, 2023, and order by record date.

[Assistant] SELECT T1.prescription_id, T1.medication_id, T1.dosage, T1.quantity_dispensed, T2.record_date, T3.first_name, T3.last_name FROM healthcare.prescriptions AS T1 JOIN healthcare.medical_records AS T2 ON T1.record_id = T2.record_id JOIN healthcare.patients AS T3 ON T1.patient_id = T3.patient_id WHERE T2.chief_complaint LIKE '%cough%' AND T1.prescription_date > '2023-01-01' ORDER BY T2.record_date;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )


[User] Can you write a query that retrieves each server's name, its region, and the highest current player count observed in that region?

[Assistant]
SELECT s.server_name, s.region, m.max_current_players
FROM gaming_technology.servers s
JOIN (
  SELECT region, MAX(current_players) AS max_current_players
  FROM gaming_technology.servers
  GROUP BY region
) m ON s.region = m.region;

[User] Actually, only include regions where that maximum current player count exceeds 50.

[Assistant]
SELECT s.server_name, s.region, m.max_current_players
FROM gaming_technology.servers s
JOIN (
  SELECT region, MAX(current_players) AS max_current_players
  FROM gaming_technology.servers
  GROUP BY region
  HAVING MAX(current_players) > 50
) m ON s.region = m.region;

[User] Also, exclude any servers that are already full (where current_players equals max_players).

[Assistant]
SELECT s.server_name, s.region, m.max_current_players
FROM gaming_technology.servers s
JOIN (
  SELECT region, MAX(current_players) AS max_current_players
  FROM gaming_technology.servers
  GROUP BY region
  HAVING MAX(current_players) > 50
) m ON s.region = m.region
WHERE s.current_players < s.max_players;

[User] Finally, sort the results by region ascending and then by the maximum current players in descending order.

[Assistant]
SELECT s.server_name, s.region, m.max_current_players
FROM gaming_technology.servers s
JOIN (
  SELECT region, MAX(current_players) AS max_current_players
  FROM gaming_technology.servers
  GROUP BY region
  HAVING MAX(current_players) > 50
) m ON s.region = m.region
WHERE s.current_players < s.max_players
ORDER BY s.region ASC, m.max_current_players DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )


[User] Show prescriptions with their corresponding chief complaint from the medical record. Return prescription_id, record_id, and chief_complaint.

[Assistant]
SELECT p.prescription_id, p.record_id, mr.chief_complaint
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id;

[User] Only include prescriptions where chief_complaint contains 'fever' and the route is 'Oral'.

[Assistant]
SELECT p.prescription_id, p.record_id, mr.chief_complaint
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id
WHERE mr.chief_complaint ILIKE '%fever%'
  AND p.route = 'Oral';

[User] Also include the medication_name by joining the medications table and sort the results by prescription_date ascending.

[Assistant]
SELECT p.prescription_id,
       p.record_id,
       mr.chief_complaint,
       m.medication_name
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id
LEFT JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE mr.chief_complaint ILIKE '%fever%'
  AND p.route = 'Oral'
ORDER BY p.prescription_date ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] How many smart money addresses are recorded for each chain?

[Assistant] SELECT chain, COUNT(address) FROM smart_money_profit GROUP BY chain;

[User] Now, only show chains that have more than 100 recorded addresses.

[Assistant] SELECT chain, COUNT(address) FROM smart_money_profit GROUP BY chain HAVING COUNT(address) > 100;

[User] Can you order the results by the number of addresses in descending order?

[Assistant] SELECT chain, COUNT(address) FROM smart_money_profit GROUP BY chain HAVING COUNT(address) > 100 ORDER BY COUNT(address) DESC;

[User] Also, include the average ROI for addresses on these chains.

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


[User] For each citizen who has made at least one payment, show the citizen's full name, number of payments, and total amount paid, grouped by currency.

[Assistant]
SELECT
  c.first_name || ' ' || c.last_name AS full_name,
  p.currency,
  COUNT(*) AS payment_count,
  SUM(p.amount) AS total_amount
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
GROUP BY full_name, p.currency;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id 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.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )