[User] Find users who have created wallets on more than one distinct day, listing their user ID and the number of distinct days they created wallets.

[Assistant] SELECT user_id, COUNT(DISTINCT DATE(created_at)) AS distinct_creation_days FROM web3.wallets GROUP BY user_id HAVING COUNT(DISTINCT DATE(created_at)) > 1;

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.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )


[User] Show me the top 5 tokens by USD value held on the Binance Smart Chain, along with their average price and total balance.

[Assistant] SELECT token_symbol, AVG(price) AS average_price, SUM(balance) AS total_balance, SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE chain = 'Binance Smart Chain' GROUP BY token_symbol ORDER BY total_usd_value DESC LIMIT 5;

[User] Actually, I want to see this for the Polygon chain instead, and only include tokens with a total balance over 1000.

[Assistant] SELECT token_symbol, AVG(price) AS average_price, SUM(balance) AS total_balance, SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol HAVING SUM(balance) > 1000 ORDER BY total_usd_value DESC LIMIT 5;

[User] Can you add the exchange name to these results and filter to only show Binance holdings?

[Assistant] SELECT exchange, token_symbol, AVG(price) AS average_price, SUM(balance) AS total_balance, SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND exchange = 'Binance' GROUP BY exchange, token_symbol HAVING SUM(balance) > 1000 ORDER BY total_usd_value DESC LIMIT 5;

[User] Now order these results by total balance instead of USD value.

[Assistant] SELECT exchange, token_symbol, AVG(price) AS average_price, SUM(balance) AS total_balance, SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND exchange = 'Binance' GROUP BY exchange, token_symbol HAVING SUM(balance) > 1000 ORDER BY total_balance 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 cex_token_balance ( snapshot_time text, chain text, address text, exchange text, token_address text, token_symbol text, balance numeric, usd_value numeric, price numeric )


[User] What is the count of customers for each state where the status is 'Active' and the created_at date is within the last 3 months?

[Assistant] SELECT state, COUNT(*) as customer_count FROM financial_services.customers WHERE status = 'Active' AND created_at >= CURRENT_DATE - INTERVAL '3 months' GROUP BY state;

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, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )


[User] What is the current market price of a Boeing 737 MAX aircraft?

[Assistant] I'm sorry, but I don't have access to the current market price of aircraft models. The data I have is limited to technical specifications and general information about aircraft models such as passenger capacity, range, and status. For pricing information, you may need to consult with manufacturers or industry 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 character varying(64) NOT NULL,  -- unique identifier for the aircraft model
    model_name character varying(128) NOT NULL, -- commercial name of the model (e.g., 737 MAX, A320neo)
    manufacturer character varying(128) NOT NULL, -- manufacturer name (e.g., Boeing, Airbus)
    passenger_capacity integer, -- typical passenger capacity
    max_range_km integer, -- maximum flight range in kilometers
    engine_type character varying(100), -- type of engines used
    wingspan_m numeric(6,2), -- wingspan in meters
    status character varying(50) NOT NULL, -- e.g., 'In Production', 'Development', 'Discontinued'
    first_flight_date date, -- date of the model's first flight
    PRIMARY KEY (model_id)
)


[User] Find all pairs of transactions where the sender address and the receiver address are the same, but the transactions occurred on different days. Show transaction IDs, addresses, and their timestamps.

[Assistant]
SELECT t1.transaction_id AS tx1_id, t2.transaction_id AS tx2_id, t1.sender_address, t1.timestamp AS tx1_time, t2.timestamp AS tx2_time
FROM blockchain.transactions t1
JOIN blockchain.transactions t2
  ON t1.sender_address = t2.sender_address
 AND t1.receiver_address = t2.receiver_address
 AND t1.transaction_id <> t2.transaction_id
 AND DATE(t1.timestamp) <> DATE(t2.timestamp)
WHERE t1.sender_address = t1.receiver_address;

[User] Exclude pairs where the two transactions happened more than 7 days apart.

[Assistant]
SELECT t1.transaction_id AS tx1_id, t2.transaction_id AS tx2_id, t1.sender_address, t1.timestamp AS tx1_time, t2.timestamp AS tx2_time
FROM blockchain.transactions t1
JOIN blockchain.transactions t2
  ON t1.sender_address = t2.sender_address
 AND t1.receiver_address = t2.receiver_address
 AND t1.transaction_id <> t2.transaction_id
 AND DATE(t1.timestamp) <> DATE(t2.timestamp)
WHERE t1.sender_address = t1.receiver_address
  AND ABS(DATE_PART('day', t1.timestamp - t2.timestamp)) <= 7;

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 blockchain.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    block_id character varying(64) NOT NULL, -- identifier of the block containing the transaction
    sender_address character varying(128) NOT NULL, -- address of the sender
    receiver_address character varying(128) NOT NULL, -- address of the receiver
    amount numeric(38,14) NOT NULL, -- amount transferred
    timestamp timestamp NOT NULL, -- time when the transaction was created
    signature text NOT NULL, -- digital signature of the transaction
    PRIMARY KEY (transaction_id)
)


[User] Show me the average transaction amount per block, along with the block_id and the count of transactions in each block.

[Assistant] SELECT block_id, AVG(amount) as avg_amount, COUNT(*) as transaction_count FROM blockchain.transactions WHERE block_id IS NOT NULL GROUP BY block_id;

[User] Now filter this to only show blocks that have more than 5 transactions and an average amount greater than 500.

[Assistant] SELECT block_id, AVG(amount) as avg_amount, COUNT(*) as transaction_count FROM blockchain.transactions WHERE block_id IS NOT NULL GROUP BY block_id HAVING COUNT(*) > 5 AND AVG(amount) > 500;

[User] Can you also include the earliest and latest transaction timestamps for each of these blocks?

[Assistant] SELECT block_id, AVG(amount) as avg_amount, COUNT(*) as transaction_count, MIN(timestamp) as earliest_tx, MAX(timestamp) as latest_tx FROM blockchain.transactions WHERE block_id IS NOT NULL GROUP BY block_id HAVING COUNT(*) > 5 AND AVG(amount) > 500;

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 blockchain.transactions ( transaction_id text PRIMARY KEY, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )


[User] List all pairs of users where the first user registered before the second user, including both usernames and their registration dates.

[Assistant]
SELECT a.username AS user1, a.created_at AS user1_created, b.username AS user2, b.created_at AS user2_created
FROM trading_platform.users a
JOIN trading_platform.users b
  ON a.created_at < b.created_at;

[User] Actually, I only want pairs where the second user registered within 3 days of the first user.

[Assistant]
SELECT a.username AS user1, a.created_at AS user1_created, b.username AS user2, b.created_at AS user2_created
FROM trading_platform.users a
JOIN trading_platform.users b
  ON a.created_at < b.created_at
  AND b.created_at <= a.created_at + INTERVAL '3 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 trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )


[User] For each passenger, show their full name, email, and the number of unique trips they have participated in.

[Assistant]
SELECT p.first_name, p.last_name, p.email, COUNT(DISTINCT b.trip_id) AS unique_trips
FROM transportation.passengers p
LEFT JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name, p.email;

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.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)


[User] List all guests who have written at least two reviews, including their full names and the total number of reviews they wrote.

[Assistant]
SELECT g.guest_id, g.first_name, g.last_name, COUNT(rw.review_id) AS review_count
FROM hospitality_technology.guests g
JOIN hospitality_technology.reviews rw ON g.guest_id = rw.guest_id
GROUP BY g.guest_id, g.first_name, g.last_name
HAVING COUNT(rw.review_id) >= 2
ORDER BY review_count DESC;

[User] Now also show the average overall rating they have given in their reviews.

[Assistant]
SELECT g.guest_id, g.first_name, g.last_name,
       COUNT(rw.review_id) AS review_count,
       AVG(rw.rating_overall) AS avg_rating
FROM hospitality_technology.guests g
JOIN hospitality_technology.reviews rw ON g.guest_id = rw.guest_id
GROUP BY g.guest_id, g.first_name, g.last_name
HAVING COUNT(rw.review_id) >= 2
ORDER BY review_count DESC;

[User] Only include guests whose average overall rating is below 3.

[Assistant]
SELECT g.guest_id, g.first_name, g.last_name,
       COUNT(rw.review_id) AS review_count,
       AVG(rw.rating_overall) AS avg_rating
FROM hospitality_technology.guests g
JOIN hospitality_technology.reviews rw ON g.guest_id = rw.guest_id
GROUP BY g.guest_id, g.first_name, g.last_name
HAVING COUNT(rw.review_id) >= 2 AND AVG(rw.rating_overall) < 3
ORDER BY review_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,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews (
    review_id character varying(64) NOT NULL,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    PRIMARY KEY (review_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id)
)


[User] Can you help me find all staff members assigned to a specific station with station_id 'STATION_002', along with their roles and the platform details at that station?

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.role, p.platform_id, p.platform_number, p.status, p.accessible
FROM train_station_management.staff s
JOIN train_station_management.platforms p ON s.primary_station_id = p.station_id
WHERE s.primary_station_id = 'STATION_002' AND s.is_active = true;

[User] Can you filter the results to show only staff with the role of 'Conductor' and platforms that are operational?

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.role, p.platform_id, p.platform_number, p.status, p.accessible
FROM train_station_management.staff s
JOIN train_station_management.platforms p ON s.primary_station_id = p.station_id
WHERE s.primary_station_id = 'STATION_002' AND s.is_active = true AND s.role = 'Conductor' AND p.status = 'Operational';

[User] Can you also sort the results by staff last name and platform number?

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.role, p.platform_id, p.platform_number, p.status, p.accessible
FROM train_station_management.staff s
JOIN train_station_management.platforms p ON s.primary_station_id = p.station_id
WHERE s.primary_station_id = 'STATION_002' AND s.is_active = true AND s.role = 'Conductor' AND p.status = 'Operational'
ORDER BY s.last_name, p.platform_number;

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.platforms (
    platform_id character varying(64) NOT NULL, -- Unique identifier for the platform
    station_id character varying(64) NOT NULL, -- Foreign key referencing stations
    platform_number character varying(10) NOT NULL, -- Platform identifier (e.g., '1A', '5')
    track_number character varying(10), -- Associated track number, if different
    status character varying(32) NOT NULL DEFAULT 'Operational', -- e.g., Operational, Maintenance, Closed
    length_meters numeric(8,2), -- Length of the platform in meters
    accessible boolean NOT NULL DEFAULT false, -- Is the platform accessible (e.g., wheelchair)?
    PRIMARY KEY (platform_id),
    FOREIGN KEY (station_id) REFERENCES train_station_management.stations(station_id)
)
CREATE TABLE train_station_management.trains (
    train_id character varying(64) NOT NULL, -- Unique identifier for the train set
    train_number character varying(32) NOT NULL, -- Operational number of the train (e.g., 'Acela 2151')
    model character varying(128), -- Model of the train (e.g., 'Siemens Velaro')
    manufacturer character varying(128), -- Manufacturer of the train
    year_manufactured integer, -- Year the train was built
    capacity integer NOT NULL, -- Total passenger capacity
    status character varying(32) NOT NULL DEFAULT 'Active', -- e.g., Active, Maintenance, Retired
    last_maintenance_date date, -- Date of last scheduled maintenance
    next_maintenance_date date, -- Date of next scheduled maintenance
    PRIMARY KEY (train_id),
    UNIQUE (train_number)
)
CREATE TABLE train_station_management.staff (
    staff_id character varying(64) NOT NULL, -- Unique identifier for the staff member
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    role character varying(64) NOT NULL, -- e.g., Station Master, Ticket Agent, Conductor, Engineer, Maintenance Crew
    primary_station_id character varying(64), -- Base station for the staff member (nullable for mobile staff)
    employee_number character varying(32) UNIQUE NOT NULL, -- Unique employee identifier
    hire_date date NOT NULL,
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    is_active boolean NOT NULL DEFAULT true, -- Is the staff member currently employed?
    PRIMARY KEY (staff_id),
    FOREIGN KEY (primary_station_id) REFERENCES train_station_management.stations(station_id)
)


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

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

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

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

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

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

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

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

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


[User] List plan_id, plan_name, and contact_phone for all insurance plans whose website ends with '.org' and that have at least one other plan with the same contact_phone.

[Assistant]
SELECT a.plan_id, a.plan_name, a.contact_phone
FROM healthcare.insurance_plans a
JOIN healthcare.insurance_plans b
  ON a.contact_phone = b.contact_phone
  AND a.plan_id <> b.plan_id
WHERE a.website LIKE '%.org';

[User] Now sort by website descending and limit the results to 5 rows.

[Assistant]
SELECT a.plan_id, a.plan_name, a.contact_phone
FROM healthcare.insurance_plans a
JOIN healthcare.insurance_plans b
  ON a.contact_phone = b.contact_phone
  AND a.plan_id <> b.plan_id
WHERE a.website LIKE '%.org'
ORDER BY a.website 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 healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )


[User] How many prescriptions have been issued per patient?

[Assistant]
SELECT patient_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions
GROUP BY patient_id;

[User] Only show patients who have more than 5 prescriptions.

[Assistant]
SELECT patient_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions
GROUP BY patient_id
HAVING COUNT(*) > 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 healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id 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] What is the total market cap for all tokens listed on the 'Polygon' chain?

[Assistant] SELECT SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon';

[User] Only sum the market cap for tokens on 'Polygon' that have a 24-hour volume greater than 500000.

[Assistant] SELECT SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon' AND volume_24h > 500000;

[User] Also show the number of unique tokens that meet these criteria.

[Assistant] SELECT COUNT(DISTINCT token_symbol), SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon' AND volume_24h > 500000;

[User] Can you show the total market cap and token count for *each* chain that meets these volume criteria, ordered by total market cap descending?

[Assistant] SELECT chain, COUNT(DISTINCT token_symbol) AS token_count, SUM(market_cap) AS total_market_cap FROM token_dexpool_info WHERE volume_24h > 500000 GROUP BY chain ORDER BY total_market_cap 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 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) )


[User] List all peer logs, showing the user_id and the action taken, ordered by the most recent log entry.

[Assistant]
SELECT user_id, action, logged_at
FROM trading_platform.logs
ORDER BY logged_at 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 trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] How many distinct projects conducted fundraising in April 2023?

[Assistant]
SELECT COUNT(DISTINCT project_id) AS num_projects
FROM project_fundraising_record
WHERE investment_date LIKE '2023-04%';

[User] Can you also show their names?

[Assistant]
SELECT DISTINCT project_name
FROM project_fundraising_record
WHERE investment_date LIKE '2023-04%';

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 project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )


[User] List tokens with trend rank 5 or better and a price below $1. Show symbol, price, and trend rank.

[Assistant] SELECT token_symbol, price, trend_rank FROM token_dexpool_info WHERE trend_rank IS NOT NULL AND trend_rank <= 5 AND price < 1;


[User] Show me all maintenance logs for 'Engine Repair' service type where the cost is greater than 400, including the vehicle ID, service date, cost, and mechanic name.

[Assistant] SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Engine Repair' AND cost > 400;

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.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)


[User] List all employees and the branch they work at, along with their job title and department.

[Assistant]
SELECT employee_id, first_name || ' ' || last_name AS full_name, job_title, department, branch_id
FROM financial_services.employees;

[User] Add the full name of each employee's manager to the result. If there is no manager, show NULL.

[Assistant]
SELECT e.employee_id, e.first_name || ' ' || e.last_name AS full_name, e.job_title, e.department, e.branch_id, m.first_name || ' ' || m.last_name AS manager_full_name
FROM financial_services.employees e
LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id;

[User] Only include employees who are currently active, and sort the list by department, then by full_name.

[Assistant]
SELECT e.employee_id, e.first_name || ' ' || e.last_name AS full_name, e.job_title, e.department, e.branch_id, m.first_name || ' ' || m.last_name AS manager_full_name
FROM financial_services.employees e
LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id
WHERE e.status = 'Active'
ORDER BY e.department, full_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 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 PRIMARY KEY, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.transactions ( transaction_id text PRIMARY KEY, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.securities ( security_id text PRIMARY KEY, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )
CREATE TABLE financial_services.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )


[User] Find all claims with a settlement amount between 5000 and 10000. List the claim ID, incident date, and settlement date.

[Assistant]
SELECT claim_id, incident_date, settlement_date
FROM insurance.claims
WHERE settlement_amount BETWEEN 5000 AND 10000;

[User] I also want to see the policy ID associated with each claim.

[Assistant]
SELECT claim_id, policy_id, incident_date, settlement_date
FROM insurance.claims
WHERE settlement_amount BETWEEN 5000 AND 10000;

[User] Only show claims where the claim has been settled after March 1, 2024.

[Assistant]
SELECT claim_id, policy_id, incident_date, settlement_date
FROM insurance.claims
WHERE settlement_amount BETWEEN 5000 AND 10000
  AND settlement_date > '2024-03-01';

[User] Now, sort the results by settlement_amount in descending order.

[Assistant]
SELECT claim_id, policy_id, incident_date, settlement_date
FROM insurance.claims
WHERE settlement_amount BETWEEN 5000 AND 10000
  AND settlement_date > '2024-03-01'
ORDER BY settlement_amount 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 character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )


[User] Show me all drivers hired in 2023, including their full name and email address.

[Assistant] SELECT first_name, last_name, email FROM transportation.drivers WHERE hire_date >= '2023-01-01' AND hire_date < '2024-01-01';

[User] Just provide their license numbers and order the results by hire date descending.

[Assistant] SELECT license_number FROM transportation.drivers WHERE hire_date >= '2023-01-01' AND hire_date < '2024-01-01' ORDER BY hire_date 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.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 )


[User] I'm interested in pairs of players who registered on the exact same calendar date and in the same country. Can you show two columns, player1_id and player2_id, along with that date and country code?

[Assistant]
SELECT p1.player_id AS player1_id,
       p2.player_id AS player2_id,
       DATE(p1.registration_date) AS reg_date,
       p1.country_code
FROM gaming_technology.players p1
JOIN gaming_technology.players p2
  ON p1.country_code = p2.country_code
 AND DATE(p1.registration_date) = DATE(p2.registration_date)
 AND p1.player_id < p2.player_id;

[User] Actually, I'd like to only see dates and countries where at least three such pairs exist, and show the number of pairs per date and country as pair_count.

[Assistant]
WITH pairs AS (
  SELECT p1.player_id, p2.player_id,
         DATE(p1.registration_date) AS reg_date,
         p1.country_code
  FROM gaming_technology.players p1
  JOIN gaming_technology.players p2
    ON p1.country_code = p2.country_code
   AND DATE(p1.registration_date) = DATE(p2.registration_date)
   AND p1.player_id < p2.player_id
)
SELECT country_code,
       reg_date,
       COUNT(*) AS pair_count
FROM pairs
GROUP BY country_code, reg_date
HAVING COUNT(*) >= 3;

[User] Also, sort these results by pair_count descending and then by country_code ascending.

[Assistant]
WITH pairs AS (
  SELECT p1.player_id, p2.player_id,
         DATE(p1.registration_date) AS reg_date,
         p1.country_code
  FROM gaming_technology.players p1
  JOIN gaming_technology.players p2
    ON p1.country_code = p2.country_code
   AND DATE(p1.registration_date) = DATE(p2.registration_date)
   AND p1.player_id < p2.player_id
)
SELECT country_code,
       reg_date,
       COUNT(*) AS pair_count
FROM pairs
GROUP BY country_code, reg_date
HAVING COUNT(*) >= 3
ORDER BY pair_count DESC, country_code ASC;

[User] Could you exclude any pairs where either player1 or player2 is not currently 'active'? And still count pairs per date/country with having >= 3.

[Assistant]
WITH active_pairs AS (
  SELECT p1.player_id AS player1_id,
         p2.player_id AS player2_id,
         DATE(p1.registration_date) AS reg_date,
         p1.country_code
  FROM gaming_technology.players p1
  JOIN gaming_technology.players p2
    ON p1.country_code = p2.country_code
   AND DATE(p1.registration_date) = DATE(p2.registration_date)
   AND p1.player_id < p2.player_id
  WHERE p1.status = 'active'
    AND p2.status = 'active'
)
SELECT country_code,
       reg_date,
       COUNT(*) AS pair_count
FROM active_pairs
GROUP BY country_code, reg_date
HAVING COUNT(*) >= 3
ORDER BY pair_count DESC, country_code 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 gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )


[User] For each customer, provide a summary of their account statuses, showing their full name, account status, and the count of accounts for each status.

[Assistant] SELECT c.first_name, c.last_name, a.status, COUNT(a.account_id) AS account_count FROM financial_services.accounts a JOIN financial_services.customers c ON a.customer_id = c.customer_id GROUP BY c.customer_id, c.first_name, c.last_name, a.status ORDER BY c.last_name, c.first_name, a.status;

[User] Refine this to only include customers who have accounts in at least two different statuses.

[Assistant] SELECT c.first_name, c.last_name, a.status, COUNT(a.account_id) AS account_count FROM financial_services.accounts a JOIN financial_services.customers c ON a.customer_id = c.customer_id GROUP BY c.customer_id, c.first_name, c.last_name, a.status HAVING c.customer_id IN ( SELECT customer_id FROM financial_services.accounts GROUP BY customer_id HAVING COUNT(DISTINCT status) >= 2 ) ORDER BY c.last_name, c.first_name, a.status;

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


[User] For each state, show the total number of service locations and the number of employees working at agencies within those states.

[Assistant]
SELECT sl.state, COUNT(DISTINCT sl.location_id) AS location_count, COUNT(DISTINCT e.employee_id) AS employee_count
FROM government_services.service_locations sl
JOIN government_services.employees e ON sl.agency_id = e.agency_id
GROUP BY sl.state;

[User] Only include states with more than 3 service locations.

[Assistant]
SELECT sl.state, COUNT(DISTINCT sl.location_id) AS location_count, COUNT(DISTINCT e.employee_id) AS employee_count
FROM government_services.service_locations sl
JOIN government_services.employees e ON sl.agency_id = e.agency_id
GROUP BY sl.state
HAVING COUNT(DISTINCT sl.location_id) > 3;

[User] Now, order the results by employee_count in descending order.

[Assistant]
SELECT sl.state, COUNT(DISTINCT sl.location_id) AS location_count, COUNT(DISTINCT e.employee_id) AS employee_count
FROM government_services.service_locations sl
JOIN government_services.employees e ON sl.agency_id = e.agency_id
GROUP BY sl.state
HAVING COUNT(DISTINCT sl.location_id) > 3
ORDER BY employee_count DESC;

[User] Show only the top 5 states.

[Assistant]
SELECT sl.state, COUNT(DISTINCT sl.location_id) AS location_count, COUNT(DISTINCT e.employee_id) AS employee_count
FROM government_services.service_locations sl
JOIN government_services.employees e ON sl.agency_id = e.agency_id
GROUP BY sl.state
HAVING COUNT(DISTINCT sl.location_id) > 3
ORDER BY employee_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 government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.payments ( payment_id text, 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, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )


[User] Show the route number and description for routes that have bookings associated with them.

[Assistant] SELECT DISTINCT T1.route_number, T1.description FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id;

[User] For these routes, what is the average fare of the associated bookings?

[Assistant] SELECT T1.route_number, AVG(T2.fare) FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id GROUP BY T1.route_number;

[User] Also, only include routes where the average fare is greater than 75.

[Assistant] SELECT T1.route_number, AVG(T2.fare) FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id GROUP BY T1.route_number HAVING AVG(T2.fare) > 75;

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.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text, 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.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] Show me all products where the description or coverage details contain the word 'insurance'.

[Assistant] SELECT product_id, product_name, product_type, description, coverage_details FROM insurance.insurance_products WHERE description LIKE '%insurance%' OR coverage_details LIKE '%insurance%';

[User] From that list, only include products that are currently active.

[Assistant] SELECT product_id, product_name, product_type, description, coverage_details FROM insurance.insurance_products WHERE (description LIKE '%insurance%' OR coverage_details LIKE '%insurance%') AND is_active = TRUE;

[User] Also, filter to show only products with a base premium between 1000 and 5000, and order the results by product name.

[Assistant] SELECT product_id, product_name, product_type, description, coverage_details FROM insurance.insurance_products WHERE (description LIKE '%insurance%' OR coverage_details LIKE '%insurance%') AND is_active = TRUE AND base_premium BETWEEN 1000 AND 5000 ORDER BY product_name;

[User] Okay, instead of all details, just list the product name and base premium for these filtered products, and limit to the first 10 results.

[Assistant] SELECT product_name, base_premium FROM insurance.insurance_products WHERE (description LIKE '%insurance%' OR coverage_details LIKE '%insurance%') AND is_active = TRUE AND base_premium BETWEEN 1000 AND 5000 ORDER BY product_name LIMIT 10;

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.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )


[User] List pairs of documents uploaded by the same lawyer, showing uploader ID and both document names.

[Assistant] SELECT d1.uploaded_by_lawyer_id, d1.document_name AS doc1, d2.document_name AS doc2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.uploaded_by_lawyer_id = d2.uploaded_by_lawyer_id AND d1.document_id < d2.document_id;

[User] Only include pairs where the upload timestamps are within 7 days of each other.

[Assistant] SELECT d1.uploaded_by_lawyer_id, d1.document_name AS doc1, d2.document_name AS doc2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.uploaded_by_lawyer_id = d2.uploaded_by_lawyer_id AND d1.document_id < d2.document_id AND ABS(EXTRACT(EPOCH FROM (d1.upload_timestamp - d2.upload_timestamp)))/86400 <= 7;

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.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)


[User] Find all patients who have both a primary insurance plan and at least one completed appointment, along with their insurance policy numbers and the count of appointments.

[Assistant] SELECT p.first_name, p.last_name, pi.policy_number, COUNT(a.appointment_id) AS appointment_count FROM healthcare.patients p JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id JOIN healthcare.appointments a ON p.patient_id = a.patient_id WHERE pi.is_primary = true AND a.status = 'Completed' GROUP BY p.patient_id, p.first_name, p.last_name, pi.policy_number HAVING COUNT(a.appointment_id) >= 1;

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 character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )


[User] List the file name and document type for all documents uploaded by the user with ID 'agent456'.

[Assistant] SELECT file_name, document_type FROM insurance.claim_documents WHERE uploaded_by = 'agent456';

[User] Can you also include the file size in bytes and only show documents uploaded in the year 2023?

[Assistant] SELECT file_name, document_type, file_size_bytes FROM insurance.claim_documents WHERE uploaded_by = 'agent456' AND uploaded_at >= '2023-01-01' AND uploaded_at < '2024-01-01';

[User] Actually, just show the document ID, file name, and uploaded time for all documents uploaded by 'agent456' before 2024, ordered by upload time descending.

[Assistant] SELECT document_id, file_name, uploaded_at FROM insurance.claim_documents WHERE uploaded_by = 'agent456' AND uploaded_at < '2024-01-01' ORDER BY uploaded_at 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.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )


[User] List employees and the name of the agency they work for, who were hired in the year 2023.

[Assistant] SELECT e.first_name, e.last_name, a.agency_name FROM government_services.employees AS e JOIN government_services.agencies AS a ON e.agency_id = a.agency_id WHERE e.hire_date >= '2023-01-01' AND e.hire_date < '2024-01-01';

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, 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, 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.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.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, 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, 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 trips that were delayed by more than 30 minutes, including their vehicle_id, driver_id, and the delay time in minutes.

[Assistant] SELECT trip_id, vehicle_id, driver_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS delay_minutes FROM transportation.trips WHERE EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 > 30 AND status = 'completed';

[User] Now include the origin and destination location IDs for these trips, and filter to only show trips with more than 10 passengers.

[Assistant] SELECT t.trip_id, t.vehicle_id, t.driver_id, EXTRACT(EPOCH FROM (t.actual_departure - t.scheduled_departure))/60 AS delay_minutes, t.origin_location_id, t.destination_location_id FROM transportation.trips t WHERE EXTRACT(EPOCH FROM (t.actual_departure - t.scheduled_departure))/60 > 30 AND t.status = 'completed' AND t.passenger_count > 10;

[User] Can you join this with the fuel_logs table to show the total fuel cost for each of these delayed trips?

[Assistant] SELECT t.trip_id, t.vehicle_id, t.driver_id, EXTRACT(EPOCH FROM (t.actual_departure - t.scheduled_departure))/60 AS delay_minutes, t.origin_location_id, t.destination_location_id, SUM(f.total_cost) AS total_fuel_cost FROM transportation.trips t LEFT JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id WHERE EXTRACT(EPOCH FROM (t.actual_departure - t.scheduled_departure))/60 > 30 AND t.status = 'completed' AND t.passenger_count > 10 GROUP BY t.trip_id, t.vehicle_id, t.driver_id, delay_minutes, t.origin_location_id, t.destination_location_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.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.fuel_logs ( fuel_log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, trip_id character varying(64), log_timestamp timestamp with time zone NOT NULL, fuel_type character varying(32) NOT NULL, quantity numeric(10, 3) NOT NULL, unit character varying(16) NOT NULL, cost_per_unit numeric(8, 4), total_cost numeric(10, 2) NOT NULL, odometer_reading integer, location_id character varying(64), PRIMARY KEY (fuel_log_id) )


[User] List all vehicles and their last maintenance service date along with the odometer reading, including only those that have not had a fuel refill in the past 30 days.

[Assistant]
SELECT m.vehicle_id,
       m.last_service_date,
       m.last_odometer
FROM (
  SELECT l.vehicle_id,
         MAX(l.service_date) AS last_service_date,
         (SELECT odometer_reading
          FROM transportation.maintenance_logs
          WHERE vehicle_id = l.vehicle_id
          ORDER BY service_date DESC
          LIMIT 1) AS last_odometer
  FROM transportation.maintenance_logs l
  GROUP BY l.vehicle_id
) AS m
LEFT JOIN (
  SELECT fl.vehicle_id,
         MAX(fl.log_timestamp) AS last_fuel_date
  FROM transportation.fuel_logs fl
  GROUP BY fl.vehicle_id
) AS f ON m.vehicle_id = f.vehicle_id
WHERE COALESCE(f.last_fuel_date, '1900-01-01'::timestamp) < NOW() - 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 transportation.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.fuel_logs ( fuel_log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, trip_id character varying(64), log_timestamp timestamp with time zone NOT NULL, fuel_type character varying(32) NOT NULL, quantity numeric(10, 3) NOT NULL, unit character varying(16) NOT NULL, cost_per_unit numeric(8, 4), total_cost numeric(10, 2) NOT NULL, odometer_reading integer, location_id character varying(64), PRIMARY KEY (fuel_log_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )


[User] Show me the record_id, patient_id, prescription_id, medication_id, start_date, and the systolic blood pressure from the associated medical record for all prescriptions.

[Assistant]
SELECT p.prescription_id,
       p.medication_id,
       p.start_date,
       m.record_id,
       m.patient_id,
       (m.vitals->'blood_pressure'->>'systolic')::int AS systolic_bp
FROM healthcare.prescriptions p
JOIN healthcare.medical_records m
  ON p.record_id = m.record_id;

[User] Actually, only include those where the systolic blood pressure is greater than 140.

[Assistant]
SELECT p.prescription_id,
       p.medication_id,
       p.start_date,
       m.record_id,
       m.patient_id,
       (m.vitals->'blood_pressure'->>'systolic')::int AS systolic_bp
FROM healthcare.prescriptions p
JOIN healthcare.medical_records m
  ON p.record_id = m.record_id
WHERE (m.vitals->'blood_pressure'->>'systolic')::int > 140;

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.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )


[User] Find all metadata entries where the key is 'token_name' and display the asset_id along with its value.

[Assistant]
SELECT asset_id, value
FROM trading_platform.metadata
WHERE key = 'token_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 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 text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- 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.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- 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)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)


[User] List all cases opened in the 'State Court' jurisdiction in the year 2023, including their name, number, and client ID.

[Assistant] SELECT case_name, case_number, client_id FROM legal_services.cases WHERE court_jurisdiction = 'State Court' AND date_opened >= '2023-01-01' AND date_opened < '2024-01-01';

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.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )


[User] Show me all documents uploaded by lawyers from the 'Smith Legal Group' firm, including document_name, upload_timestamp, and the lawyer's first and last name.

[Assistant]
SELECT d.document_name, d.upload_timestamp, l.first_name, l.last_name
FROM legal_services.documents d
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
JOIN legal_services.law_firms f ON l.firm_id = f.firm_id
WHERE f.firm_name = 'Smith Legal Group';

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)
)
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)


[User] Show me all contracts deployed on the 'ethereum' network along with their deployer addresses and the length of their ABI in characters, sorted by ABI length in descending order.

[Assistant] SELECT address, deployer_address, LENGTH(abi) AS abi_length FROM web3.contracts WHERE network_id = 'ethereum' ORDER BY abi_length 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 web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )


[User] Get all beneficiaries added in the last 30 days. Include beneficiary_id, policy_id, first_name, last_name, and added_at, ordered by added_at descending.

[Assistant]
SELECT beneficiary_id,
       policy_id,
       first_name,
       last_name,
       added_at
FROM insurance.policy_beneficiaries
WHERE added_at >= NOW() - INTERVAL '30 days'
ORDER BY added_at 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.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


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

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

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

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

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

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

System:
You are an 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] List all games along with the count of in-game items they have. Only include games with more than 10 items and sort by the item count in descending order.

[Assistant]
SELECT g.game_id, g.title, COUNT(i.item_id) AS item_count
FROM gaming_technology.games g
LEFT JOIN gaming_technology.in_game_items i ON g.game_id = i.game_id
GROUP BY g.game_id, g.title
HAVING COUNT(i.item_id) > 10
ORDER BY item_count DESC;

[User] Also include the average cost_amount of the items for each game, labeled as avg_cost.

[Assistant]
SELECT g.game_id, g.title, COUNT(i.item_id) AS item_count, AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.games g
LEFT JOIN gaming_technology.in_game_items i ON g.game_id = i.game_id
GROUP BY g.game_id, g.title
HAVING COUNT(i.item_id) > 10
ORDER BY item_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 gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )


[User] List the usernames and the IDs of conversations they have joined.

[Assistant] SELECT T1.username, T2.conversation_id FROM social_media.users AS T1 JOIN social_media.conversation_participants AS T2 ON T1.user_id = T2.user_id;

[User] Can you filter this to only show users who joined after '2024-06-15'?

[Assistant] SELECT T1.username, T2.conversation_id FROM social_media.users AS T1 JOIN social_media.conversation_participants AS T2 ON T1.user_id = T2.user_id WHERE T2.joined_at > '2024-06-15';

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 social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )


[User] List the distinct cities where service locations are present.

[Assistant] SELECT DISTINCT city FROM government_services.service_locations;

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.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )


[User] List all pairs of tokens that are deployed on the same contract address and have the same number of decimals. Show both token IDs, the shared contract_address, and the decimals value.

[Assistant]
SELECT t1.token_id AS token_id_1, t2.token_id AS token_id_2, t1.contract_address, t1.decimals
FROM web3.tokens t1
JOIN web3.tokens t2
  ON t1.contract_address = t2.contract_address
  AND t1.decimals = t2.decimals
  AND t1.token_id < t2.token_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 web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)


[User] List all active SUI coins with status 'exists' in metadata, showing coin_type, symbol, name, balance, and description.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sc.balance, sm.description
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists';

[User] Limit to coins where balance > 1000000 and order by balance descending.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sc.balance, sm.description
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists'
  AND CAST(sc.balance AS numeric) > 1000000
ORDER BY CAST(sc.balance AS numeric) DESC;

[User] Also include the number of distinct owners per coin_type.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sm.description,
       SUM(CAST(sc.balance AS numeric)) AS total_balance,
       COUNT(DISTINCT sc.owner) AS owner_count
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists'
  AND CAST(sc.balance AS numeric) > 1000000
GROUP BY sc.coin_type, sm.symbol, sm.name, sm.description
ORDER BY total_balance DESC;

[User] Only show the top 3 coins by total_balance.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sm.description,
       SUM(CAST(sc.balance AS numeric)) AS total_balance,
       COUNT(DISTINCT sc.owner) AS owner_count
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists'
  AND CAST(sc.balance AS numeric) > 1000000
GROUP BY sc.coin_type, sm.symbol, sm.name, sm.description
ORDER BY total_balance DESC
LIMIT 3;

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 erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_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_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


[User] Find the average transaction value for successful transactions grouped by block number, showing only blocks with more than 10 transactions.

[Assistant] SELECT block_number, AVG(value) as avg_value, COUNT(*) as transaction_count FROM web3.transactions WHERE status = 'success' GROUP BY block_number HAVING COUNT(*) > 10 ORDER BY block_number;

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.transactions ( transaction_id text PRIMARY KEY, from_address text, to_address text, value numeric, gas_used int, gas_price numeric, block_number int, timestamp timestamp, input_data text, status text, nonce int )


[User] List all cryptocurrency assets that have been traded more than 50 times but have never been traded in quantities greater than 100.

[Assistant]
SELECT a.asset_id, a.name, a.symbol, COUNT(t.trade_id) AS trade_count
FROM trading_platform.assets a
JOIN trading_platform.trades t ON a.asset_id = t.asset_id
WHERE a.type = 'cryptocurrency'
GROUP BY a.asset_id, a.name, a.symbol
HAVING COUNT(t.trade_id) > 50 AND MAX(t.quantity) <= 100;

[User] I notice the query has a syntax error with the MAX function. Also, can you modify it to include the average trade price for these assets?

[Assistant]
SELECT a.asset_id, a.name, a.symbol, COUNT(t.trade_id) AS trade_count, AVG(t.price) AS avg_trade_price
FROM trading_platform.assets a
JOIN trading_platform.trades t ON a.asset_id = t.asset_id
WHERE a.type = 'cryptocurrency'
GROUP BY a.asset_id, a.name, a.symbol
HAVING COUNT(t.trade_id) > 50 AND MAX(t.quantity) <= 100;

[User] Now show me only assets from this list that have metadata entries about their blockchain network.

[Assistant]
SELECT a.asset_id, a.name, a.symbol, COUNT(t.trade_id) AS trade_count, AVG(t.price) AS avg_trade_price
FROM trading_platform.assets a
JOIN trading_platform.trades t ON a.asset_id = t.asset_id
JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
WHERE a.type = 'cryptocurrency' AND m.key = 'blockchain_network'
GROUP BY a.asset_id, a.name, a.symbol
HAVING COUNT(t.trade_id) > 50 AND MAX(t.quantity) <= 100;

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 text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
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, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_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.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
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)
)
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id 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.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )