[User] Show me the top 5 ERC20 tokens with the highest total supply, along with their names and contract addresses, but only include tokens where the price is greater than $0.1.

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

[User] I think there's an error in your query - it should be 'tpl.symbol' not 'tm.symbol'. Also, can you add the decimals to the results?

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

[User] Now filter these results to only show tokens with decimals equal to 18.

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE 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 varchar, wallet_address varchar, amount varchar, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info ( 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 )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )


[User] Show the name, description, and URL for all DApps.

[Assistant] SELECT name, description, url FROM trading_platform.dapps;

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.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)


[User] Find pairs of insurance plans that are offered by the same insurance provider. Show the provider name, and the names of the two plans.

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

[User] Only show pairs where the provider name starts with 'B'.

[Assistant] SELECT p1.insurance_provider, p1.plan_name, p2.plan_name FROM healthcare.insurance_plans p1 JOIN healthcare.insurance_plans p2 ON p1.insurance_provider = p2.insurance_provider AND p1.plan_id < p2.plan_id WHERE p1.insurance_provider LIKE 'B%' ORDER BY p1.insurance_provider, p1.plan_name;

[User] Further filter to include only pairs where both plans have a website listed.

[Assistant] SELECT p1.insurance_provider, p1.plan_name, p2.plan_name FROM healthcare.insurance_plans p1 JOIN healthcare.insurance_plans p2 ON p1.insurance_provider = p2.insurance_provider AND p1.plan_id < p2.plan_id WHERE p1.insurance_provider LIKE 'B%' AND p1.website IS NOT NULL AND p2.website IS NOT NULL ORDER BY p1.insurance_provider, p1.plan_name;

[User] Also, include the plan type for both plans in the result.

[Assistant] SELECT p1.insurance_provider, p1.plan_name, p1.plan_type, p2.plan_name, p2.plan_type FROM healthcare.insurance_plans p1 JOIN healthcare.insurance_plans p2 ON p1.insurance_provider = p2.insurance_provider AND p1.plan_id < p2.plan_id WHERE p1.insurance_provider LIKE 'B%' AND p1.website IS NOT NULL AND p2.website IS NOT NULL ORDER BY p1.insurance_provider, p1.plan_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 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) )


[User] How many distinct posts does each hashtag appear in?

[Assistant] SELECT hashtag_id, COUNT(DISTINCT post_id) AS post_count FROM social_media.post_hashtags GROUP BY hashtag_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 social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )


[User] How many lawyers are there in each specialization?

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

[User] Only include specializations with more than 5 lawyers.

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

[User] Also display the average years since hire for each specialization.

[Assistant]
SELECT specialization,
       COUNT(*) AS lawyer_count,
       AVG(EXTRACT(YEAR FROM AGE(CURRENT_DATE, hire_date)))::numeric(5,2) AS avg_years_since_hire
FROM legal_services.lawyers
GROUP BY specialization
HAVING COUNT(*) > 5;

[User] Sort the results by lawyer_count descending and limit to the top 3 specializations.

[Assistant]
SELECT specialization,
       COUNT(*) AS lawyer_count,
       AVG(EXTRACT(YEAR FROM AGE(CURRENT_DATE, hire_date)))::numeric(5,2) AS avg_years_since_hire
FROM legal_services.lawyers
GROUP BY specialization
HAVING COUNT(*) > 5
ORDER BY lawyer_count 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 legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )


[User] Please list all doctors and their specialties, along with the phone numbers of any other doctors who share the same specialty.

[Assistant]
SELECT d1.doctor_id, d1.first_name, d1.last_name, d1.specialty, d2.phone_number AS colleague_phone_number
FROM healthcare.doctors d1
JOIN healthcare.doctors d2 ON d1.specialty = d2.specialty AND d1.doctor_id <> d2.doctor_id
ORDER BY d1.specialty, d1.doctor_id;

[User] Can you update the query to only include specialties where there are more than 2 doctors sharing the same specialty?

[Assistant]
WITH specialty_counts AS (
    SELECT specialty, COUNT(*) AS cnt FROM healthcare.doctors GROUP BY specialty HAVING COUNT(*) > 2
)
SELECT d1.doctor_id, d1.first_name, d1.last_name, d1.specialty, d2.phone_number AS colleague_phone_number
FROM healthcare.doctors d1
JOIN healthcare.doctors d2 ON d1.specialty = d2.specialty AND d1.doctor_id <> d2.doctor_id
JOIN specialty_counts sc ON d1.specialty = sc.specialty
ORDER BY d1.specialty, d1.doctor_id;

[User] Sorry, I got too many duplicate pairs. Can you adjust it to only show each unique pair of doctors per specialty once (doctor_id1 < doctor_id2)?

[Assistant]
WITH specialty_counts AS (
    SELECT specialty, COUNT(*) AS cnt FROM healthcare.doctors GROUP BY specialty HAVING COUNT(*) > 2
)
SELECT d1.specialty, d1.doctor_id AS doctor_id1, d1.first_name AS first_name1, d1.last_name AS last_name1, d1.phone_number AS phone1,
       d2.doctor_id AS doctor_id2, d2.first_name AS first_name2, d2.last_name AS last_name2, d2.phone_number AS phone2
FROM healthcare.doctors d1
JOIN healthcare.doctors d2 ON d1.specialty = d2.specialty AND d1.doctor_id < d2.doctor_id
JOIN specialty_counts sc ON d1.specialty = sc.specialty
ORDER BY d1.specialty, d1.doctor_id1, d2.doctor_id2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id.text, first_name.text, last_name.text, specialty.text, license_number.text, phone_number.text, email.text, hospital_affiliation_id.text, created_at.timestamp, updated_at.timestamp )


[User] List pairs of maintenance logs for the same vehicle where the service date is the same, showing the log IDs and service types.

[Assistant] SELECT T1.log_id AS log_id_1, T1.service_type AS service_type_1, T2.log_id AS log_id_2, T2.service_type AS service_type_2, T1.vehicle_id, T1.service_date FROM transportation.maintenance_logs AS T1 JOIN transportation.maintenance_logs AS T2 ON T1.vehicle_id = T2.vehicle_id AND T1.service_date = T2.service_date AND T1.log_id < T2.log_id;

[User] Filter this list to only include pairs where at least one of the logs has a cost greater than 500.

[Assistant] SELECT T1.log_id AS log_id_1, T1.service_type AS service_type_1, T2.log_id AS log_id_2, T2.service_type AS service_type_2, T1.vehicle_id, T1.service_date FROM transportation.maintenance_logs AS T1 JOIN transportation.maintenance_logs AS T2 ON T1.vehicle_id = T2.vehicle_id AND T1.service_date = T2.service_date AND T1.log_id < T2.log_id WHERE T1.cost > 500 OR T2.cost > 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 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) )


[User] Which projects raised funds in January 2022?

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-02-01';

[User] Please also show their introductions.

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date, introduction FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-02-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 project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )


[User] Show me the number of service orders placed for each service category.

[Assistant]
SELECT s.category, COUNT(so.order_id) AS order_count
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
GROUP BY s.category;

[User] Only include categories with more than 10 orders and order by order_count descending.

[Assistant]
SELECT s.category, COUNT(so.order_id) AS order_count
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
GROUP BY s.category
HAVING COUNT(so.order_id) > 10
ORDER BY order_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.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, 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 int, num_children int, 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 PRIMARY KEY, 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 int, 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.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


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

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

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


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

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

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

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

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


[User] List all policies where the premium_amount exceeds the base_premium of its insurance product. Display the policy_number, premium_amount, product_name, and base_premium. Sort the results by premium_amount descending.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
ORDER BY p.premium_amount DESC;

[User] Actually, I only want policies that are active and whose insurance products are also active.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'active'
  AND ip.is_active = TRUE
ORDER BY p.premium_amount DESC;

[User] Also, limit the output to policies with a coverage_limit greater than 1000000.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'active'
  AND ip.is_active = TRUE
  AND p.coverage_limit > 1000000
ORDER BY p.premium_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.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, 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 )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


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

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

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

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

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


[User] What is the total investment_value per fundraising round for the year 2023? Order by total investment descending.

[Assistant]
SELECT
  substr(investment_date,1,7) AS month,
  rounds_name,
  SUM(investment_value) AS total_investment
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%'
GROUP BY substr(investment_date,1,7), rounds_name
ORDER BY total_investment DESC;


[User] List all achievements (name and ID) that have not been unlocked by any player.

[Assistant] SELECT a.achievement_id, a.name FROM gaming_technology.achievements a LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id WHERE pa.player_achievement_id IS NULL;

[User] Also include the points for these achievements.

[Assistant] SELECT a.achievement_id, a.name, a.points FROM gaming_technology.achievements a LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id WHERE pa.player_achievement_id IS NULL;

[User] Order the results by points in descending order.

[Assistant] SELECT a.achievement_id, a.name, a.points FROM gaming_technology.achievements a LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id WHERE pa.player_achievement_id IS NULL ORDER BY a.points DESC;

[User] Only show achievements with points greater than 0.

[Assistant] SELECT a.achievement_id, a.name, a.points FROM gaming_technology.achievements a LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id WHERE pa.player_achievement_id IS NULL AND a.points > 0 ORDER BY a.points 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.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )


[User] Show me the top 5 NFT collections with the highest number of unique owners, along with their names and contract addresses.

[Assistant] SELECT nc.name, nc.contract_address, COUNT(DISTINCT nh.wallet_address) AS unique_owners FROM nft_collections nc JOIN nft_holders nh ON nc.contract_address = nh.contract_address GROUP BY nc.name, nc.contract_address ORDER BY unique_owners DESC LIMIT 5;

[User] Can you modify the query to also include the floor price and filter to only show collections with more than 1000 unique owners?

[Assistant] SELECT nc.name, nc.contract_address, nc.floor_price, COUNT(DISTINCT nh.wallet_address) AS unique_owners FROM nft_collections nc JOIN nft_holders nh ON nc.contract_address = nh.contract_address GROUP BY nc.name, nc.contract_address, nc.floor_price HAVING COUNT(DISTINCT nh.wallet_address) > 1000 ORDER BY unique_owners DESC LIMIT 5;

[User] Now join this with the nft_metadata table to include the average rarity score for these collections.

[Assistant] SELECT nc.name, nc.contract_address, nc.floor_price, COUNT(DISTINCT nh.wallet_address) AS unique_owners, AVG(nm.rarity_score) AS avg_rarity_score FROM nft_collections nc JOIN nft_holders nh ON nc.contract_address = nh.contract_address JOIN nft_metadata nm ON nc.contract_address = nm.contract_address GROUP BY nc.name, nc.contract_address, nc.floor_price HAVING COUNT(DISTINCT nh.wallet_address) > 1000 ORDER BY unique_owners 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 erc20_balances_historical ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk integer )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain varchar, contract_address varchar, name varchar, symbol varchar, deploy_block_number bigint, deploy_block_time bigint, erc_type varchar, owner varchar, traits varchar, description varchar, slug varchar, media_info varchar, image_url varchar, banner_image_url varchar, updated_at bigint, banner varchar, token_count bigint, floor_price varchar, floor_price_symbol varchar, floor_price_contract varchar, pk integer )
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_info ( 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 )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
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] For each user, show their username and the total number of completed orders they have placed, along with the name of the asset for each order.

[Assistant]
SELECT u.username, a.name AS asset_name, COUNT(o.order_id) AS completed_order_count
FROM trading_platform.users u
JOIN trading_platform.orders o ON u.user_id = o.user_id
JOIN trading_platform.assets a ON o.asset_id = a.asset_id
WHERE o.status = 'completed'
GROUP BY u.username, a.name;

[User] Actually, only show users who have completed orders for more than one different asset. Please also include their email in the results.

[Assistant]
SELECT u.username, u.email, COUNT(DISTINCT o.asset_id) AS asset_count
FROM trading_platform.users u
JOIN trading_platform.orders o ON u.user_id = o.user_id
WHERE o.status = 'completed'
GROUP BY u.username, u.email
HAVING COUNT(DISTINCT o.asset_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 trading_platform.users ( user_id.text, username.text, email.text, password_hash.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.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, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.logs ( log_id 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] Show me all active customers from California who were born before 1980, along with their contact information.

[Assistant] SELECT first_name, last_name, phone_number, email, address_line1, city, zip_code FROM insurance.customers WHERE state = 'California' AND date_of_birth < '1980-01-01' AND status = 'Active';

[User] Now filter these results to only show customers who have provided both a phone number and an email address.

[Assistant] SELECT first_name, last_name, phone_number, email, address_line1, city, zip_code FROM insurance.customers WHERE state = 'California' AND date_of_birth < '1980-01-01' AND status = 'Active' AND phone_number IS NOT NULL AND email IS NOT NULL;

[User] I also want to see how long these customers have been in our system (difference between current date and created_at in years).

[Assistant] SELECT first_name, last_name, phone_number, email, address_line1, city, zip_code, EXTRACT(YEAR FROM AGE(CURRENT_DATE, created_at)) AS years_in_system FROM insurance.customers WHERE state = 'California' AND date_of_birth < '1980-01-01' AND status = 'Active' AND phone_number IS NOT NULL AND email IS NOT NULL;

[User] Finally, order the results by the longest tenure in our system first, then by last name alphabetically.

[Assistant] SELECT first_name, last_name, phone_number, email, address_line1, city, zip_code, EXTRACT(YEAR FROM AGE(CURRENT_DATE, created_at)) AS years_in_system FROM insurance.customers WHERE state = 'California' AND date_of_birth < '1980-01-01' AND status = 'Active' AND phone_number IS NOT NULL AND email IS NOT NULL ORDER BY years_in_system DESC, last_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)


[User] Find pairs of insurance policies where the plan_id is the same, but they belong to different patients. Show the plan_id, and the patient_id and policy_number for both policies in the pair.

[Assistant] SELECT T1.plan_id, T1.patient_id AS patient_id_1, T1.policy_number AS policy_number_1, T2.patient_id AS patient_id_2, T2.policy_number AS policy_number_2 FROM healthcare.patient_insurance AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.plan_id = T2.plan_id WHERE T1.patient_id <> T2.patient_id AND T1.patient_insurance_id < T2.patient_insurance_id;

[User] Refine this to only include policies that are currently active (expiration_date IS NULL or > CURRENT_DATE) for both policies in the pair.

[Assistant] SELECT T1.plan_id, T1.patient_id AS patient_id_1, T1.policy_number AS policy_number_1, T2.patient_id AS patient_id_2, T2.policy_number AS policy_number_2 FROM healthcare.patient_insurance AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.plan_id = T2.plan_id WHERE T1.patient_id <> T2.patient_id AND T1.patient_insurance_id < T2.patient_insurance_id AND (T1.expiration_date IS NULL OR T1.expiration_date > CURRENT_DATE) AND (T2.expiration_date IS NULL OR T2.expiration_date > CURRENT_DATE);

[User] Also, only show pairs where one policy is primary and the other is not primary (is_primary = TRUE for one, is_primary = FALSE for the other).

[Assistant] SELECT T1.plan_id, T1.patient_id AS patient_id_1, T1.policy_number AS policy_number_1, T2.patient_id AS patient_id_2, T2.policy_number AS policy_number_2 FROM healthcare.patient_insurance AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.plan_id = T2.plan_id WHERE T1.patient_id <> T2.patient_id AND T1.patient_insurance_id < T2.patient_insurance_id AND (T1.expiration_date IS NULL OR T1.expiration_date > CURRENT_DATE) AND (T2.expiration_date IS NULL OR T2.expiration_date > CURRENT_DATE) AND ((T1.is_primary = TRUE AND T2.is_primary = FALSE) OR (T1.is_primary = FALSE AND T2.is_primary = TRUE));

[User] Filter further to only show pairs where the shared plan_id starts with 'HMO'.

[Assistant] SELECT T1.plan_id, T1.patient_id AS patient_id_1, T1.policy_number AS policy_number_1, T2.patient_id AS patient_id_2, T2.policy_number AS policy_number_2 FROM healthcare.patient_insurance AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.plan_id = T2.plan_id WHERE T1.patient_id <> T2.patient_id AND T1.patient_insurance_id < T2.patient_insurance_id AND (T1.expiration_date IS NULL OR T1.expiration_date > CURRENT_DATE) AND (T2.expiration_date IS NULL OR T2.expiration_date > CURRENT_DATE) AND ((T1.is_primary = TRUE AND T2.is_primary = FALSE) OR (T1.is_primary = FALSE AND T2.is_primary = TRUE)) AND T1.plan_id LIKE 'HMO%';

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.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )


[User] List all DApps along with the number of metadata entries linked to each, even if the DApp has no linked metadata.

[Assistant]
SELECT d.name, d.url, COUNT(m.metadata_id) AS metadata_count
FROM trading_platform.dapps d
LEFT JOIN trading_platform.metadata m ON d.dapp_id = m.asset_id
GROUP BY d.dapp_id, d.name, d.url;


[User] Show me the total transaction amount sent by each sender address, along with their current balance from the addresses table.

[Assistant] SELECT t.sender_address, SUM(t.amount) AS total_sent, a.balance FROM blockchain.transactions t JOIN blockchain.addresses a ON t.sender_address = a.address_id GROUP BY t.sender_address, a.balance;

[User] Now filter this to only show sender addresses that have sent more than 1000 in total and have a balance greater than 500.

[Assistant] SELECT t.sender_address, SUM(t.amount) AS total_sent, a.balance FROM blockchain.transactions t JOIN blockchain.addresses a ON t.sender_address = a.address_id GROUP BY t.sender_address, a.balance HAVING SUM(t.amount) > 1000 AND a.balance > 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.blocks ( block_id text PRIMARY KEY, previous_block_id text, timestamp timestamp, nonce int, merkle_root text, difficulty int )
CREATE TABLE blockchain.transactions ( transaction_id text PRIMARY KEY, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.addresses ( address_id text PRIMARY KEY, public_key text, balance numeric )
CREATE TABLE blockchain.nodes ( node_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE blockchain.users ( user_id text PRIMARY KEY, username text, email text, password_hash text )
CREATE TABLE blockchain.smart_contracts ( contract_id text PRIMARY KEY, creator_address text, code text, timestamp timestamp )


[User] Show all claims and the full name of the customer who filed each claim.

[Assistant] SELECT T1.claim_id, T1.incident_date, T1.description, T2.first_name, T2.last_name FROM insurance.claims AS T1 JOIN insurance.customers AS T2 ON T1.customer_id = T2.customer_id

[User] Can you also include the ID of the claim handler for each claim?

[Assistant] SELECT T1.claim_id, T1.incident_date, T1.description, T2.first_name, T2.last_name, T1.claim_handler_id FROM insurance.claims AS T1 JOIN insurance.customers AS T2 ON T1.customer_id = T2.customer_id

[User] Actually, only show claims with status 'Open' and an estimated loss greater than $10,000.

[Assistant] SELECT T1.claim_id, T1.incident_date, T1.description, T2.first_name, T2.last_name, T1.claim_handler_id FROM insurance.claims AS T1 JOIN insurance.customers AS T2 ON T1.customer_id = T2.customer_id WHERE T1.status = 'Open' AND T1.estimated_loss > 10000

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.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.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 )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)


[User] Find all pairs of distinct medications manufactured by the same company, showing med1.medication_id, med1.medication_name, med2.medication_id, med2.medication_name, and the manufacturer.

[Assistant]
SELECT m1.medication_id AS med1_id, m1.medication_name AS med1_name, m2.medication_id AS med2_id, m2.medication_name AS med2_name, m1.manufacturer
FROM healthcare.medications m1
JOIN healthcare.medications m2
  ON m1.manufacturer = m2.manufacturer
 AND m1.medication_id <> m2.medication_id;

[User] Actually, exclude duplicate pairs by ensuring med1_id is less than med2_id.

[Assistant]
SELECT m1.medication_id AS med1_id, m1.medication_name AS med1_name, m2.medication_id AS med2_id, m2.medication_name AS med2_name, m1.manufacturer
FROM healthcare.medications m1
JOIN healthcare.medications m2
  ON m1.manufacturer = m2.manufacturer
 AND m1.medication_id < m2.medication_id;

[User] Also, sort the results by manufacturer ascending and then med1_id ascending.

[Assistant]
SELECT m1.medication_id AS med1_id, m1.medication_name AS med1_name, m2.medication_id AS med2_id, m2.medication_name AS med2_name, m1.manufacturer
FROM healthcare.medications m1
JOIN healthcare.medications m2
  ON m1.manufacturer = m2.manufacturer
 AND m1.medication_id < m2.medication_id
ORDER BY m1.manufacturer ASC, m1.medication_id ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.medications ( medication_id.text, medication_name.text, generic_name.text, manufacturer.text, ndc_code.text, description.text )


[User] List the first and last names, email, and loyalty program ID of all passengers who joined after January 1, 2024.

[Assistant]
SELECT first_name, last_name, email, loyalty_program_id
FROM transportation.passengers
WHERE created_at > '2024-01-01';

[User] Include only those passengers who are enrolled in any loyalty program (loyalty_program_id is not null), and order the results by last name.

[Assistant]
SELECT first_name, last_name, email, loyalty_program_id
FROM transportation.passengers
WHERE created_at > '2024-01-01' AND loyalty_program_id IS NOT NULL
ORDER BY last_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 transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )


[User] Find all pairs of bookings on the same trip, showing both booking IDs, passenger IDs, and booking times.

[Assistant]
SELECT b1.booking_id AS booking_id1,
       b1.passenger_id AS passenger1,
       b1.booking_time AS time1,
       b2.booking_id AS booking_id2,
       b2.passenger_id AS passenger2,
       b2.booking_time AS time2
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.trip_id = b2.trip_id
 AND b1.booking_id < b2.booking_id;

[User] Now limit to only those pairs where both fares exceed 100.

[Assistant]
SELECT b1.booking_id AS booking_id1,
       b1.passenger_id AS passenger1,
       b1.booking_time AS time1,
       b2.booking_id AS booking_id2,
       b2.passenger_id AS passenger2,
       b2.booking_time AS time2
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.trip_id = b2.trip_id
 AND b1.booking_id < b2.booking_id
WHERE b1.fare > 100
  AND b2.fare > 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 transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )


[User] List all guests who have made at least one reservation. Show their first and last names and the number of reservations they have made.

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )


[User] Show me the top 5 NFT collections with the highest token count on Ethereum, along with their names, symbols, and floor prices.

[Assistant] SELECT n.name, n.symbol, n.floor_price, n.token_count FROM nft_collections n WHERE n.blockchain = 'ethereum' ORDER BY n.token_count DESC LIMIT 5;

[User] Now, join this with the nft_metadata table to include the average rarity score for each collection.

[Assistant] SELECT n.name, n.symbol, n.floor_price, n.token_count, AVG(m.rarity_score) as avg_rarity_score FROM nft_collections n JOIN nft_metadata m ON n.contract_address = m.contract_address WHERE n.blockchain = 'ethereum' GROUP BY n.name, n.symbol, n.floor_price, n.token_count ORDER BY n.token_count DESC LIMIT 5;

[User] Can you filter these results to only show collections with an average rarity score greater than 80?

[Assistant] SELECT n.name, n.symbol, n.floor_price, n.token_count, AVG(m.rarity_score) as avg_rarity_score FROM nft_collections n JOIN nft_metadata m ON n.contract_address = m.contract_address WHERE n.blockchain = 'ethereum' GROUP BY n.name, n.symbol, n.floor_price, n.token_count HAVING AVG(m.rarity_score) > 80 ORDER BY n.token_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 token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] Now, sort the results by the date opened, oldest first, and show only the top 10.

[Assistant] SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE lead_lawyer_id = 'lawyer_abc' AND status = 'Open' AND case_type = 'Criminal' ORDER BY date_opened ASC 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 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] For each country code, what is the earliest registration date of a player?

[Assistant] SELECT country_code, MIN(registration_date) AS earliest_reg_date FROM gaming_technology.players GROUP BY country_code;

[User] Only list countries where the earliest registration occurred before January 1st, 2020.

[Assistant] SELECT country_code, MIN(registration_date) AS earliest_reg_date FROM gaming_technology.players GROUP BY country_code HAVING MIN(registration_date) < '2020-01-01';

[User] Also include the total count of players for each of these countries.

[Assistant] SELECT country_code, MIN(registration_date) AS earliest_reg_date, COUNT(player_id) AS total_players FROM gaming_technology.players GROUP BY country_code HAVING MIN(registration_date) < '2020-01-01';

[User] Sort the results by the earliest registration date in ascending order.

[Assistant] SELECT country_code, MIN(registration_date) AS earliest_reg_date, COUNT(player_id) AS total_players FROM gaming_technology.players GROUP BY country_code HAVING MIN(registration_date) < '2020-01-01' ORDER BY earliest_reg_date ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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] Give me a breakdown of the number of reviews per day for the last 14 days, including the review_date and review count.

[Assistant]
SELECT DATE(review_date) AS review_day, COUNT(*) AS review_count
FROM hospitality_technology.reviews
WHERE review_date >= CURRENT_DATE - INTERVAL '14 days'
GROUP BY DATE(review_date)
ORDER BY review_day ASC;

[User] Add the number of public reviews for each day in a separate column named public_review_count.

[Assistant]
SELECT DATE(review_date) AS review_day,
       COUNT(*) AS review_count,
       SUM(CASE WHEN is_public THEN 1 ELSE 0 END) AS public_review_count
FROM hospitality_technology.reviews
WHERE review_date >= CURRENT_DATE - INTERVAL '14 days'
GROUP BY DATE(review_date)
ORDER BY review_day ASC;

[User] Now, also include the number of reviews per day with a rating_overall below 3 as a column called low_rating_count.

[Assistant]
SELECT DATE(review_date) AS review_day,
       COUNT(*) AS review_count,
       SUM(CASE WHEN is_public THEN 1 ELSE 0 END) AS public_review_count,
       SUM(CASE WHEN rating_overall < 3 THEN 1 ELSE 0 END) AS low_rating_count
FROM hospitality_technology.reviews
WHERE review_date >= CURRENT_DATE - INTERVAL '14 days'
GROUP BY DATE(review_date)
ORDER BY review_day ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


[User] Find pairs of citizens who share the same gender but registered in different years. Show each citizen's first and last name along with their registration year.

[Assistant]
SELECT c1.first_name AS first_name_1,
       c1.last_name  AS last_name_1,
       EXTRACT(YEAR FROM c1.registration_date) AS reg_year_1,
       c2.first_name AS first_name_2,
       c2.last_name  AS last_name_2,
       EXTRACT(YEAR FROM c2.registration_date) AS reg_year_2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.gender = c2.gender
 AND EXTRACT(YEAR FROM c1.registration_date) <> EXTRACT(YEAR FROM c2.registration_date)
 AND c1.citizen_id < c2.citizen_id;

[User] Exclude any pairs where either citizen is not verified.

[Assistant]
SELECT c1.first_name AS first_name_1,
       c1.last_name  AS last_name_1,
       EXTRACT(YEAR FROM c1.registration_date) AS reg_year_1,
       c2.first_name AS first_name_2,
       c2.last_name  AS last_name_2,
       EXTRACT(YEAR FROM c2.registration_date) AS reg_year_2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.gender = c2.gender
 AND EXTRACT(YEAR FROM c1.registration_date) <> EXTRACT(YEAR FROM c2.registration_date)
 AND c1.citizen_id < c2.citizen_id
WHERE c1.is_verified = TRUE
  AND c2.is_verified = TRUE;

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 )


[User] List all patients who have non-primary insurance plans from providers containing 'Care' in their name, including the policy number and expiration date.

[Assistant] SELECT pi.patient_id, pi.policy_number, pi.expiration_date FROM healthcare.patient_insurance pi JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE pi.is_primary = false AND ip.insurance_provider LIKE '%Care%';

[User] Actually, I need to see only those plans that will expire within the next 90 days.

[Assistant] SELECT pi.patient_id, pi.policy_number, pi.expiration_date FROM healthcare.patient_insurance pi JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE pi.is_primary = false AND ip.insurance_provider LIKE '%Care%' AND pi.expiration_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '90 days');

[User] Can you also include the insurance provider name in the results?

[Assistant] SELECT pi.patient_id, ip.insurance_provider, pi.policy_number, pi.expiration_date FROM healthcare.patient_insurance pi JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE pi.is_primary = false AND ip.insurance_provider LIKE '%Care%' AND pi.expiration_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '90 days');

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    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.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.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List all premium payments made by Bank Transfer where the amount_paid is greater than 5000. Show payment_id, policy_id, customer_id, amount_paid, and payment_date, ordered by amount_paid descending.

[Assistant]
SELECT payment_id,
       policy_id,
       customer_id,
       amount_paid,
       payment_date
FROM insurance.premium_payments
WHERE payment_method = 'Bank Transfer'
  AND amount_paid > 5000
ORDER BY amount_paid 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.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.agents (
    agent_id character varying(64) NOT NULL, -- unique identifier for the agent
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    agency_name character varying(150),
    license_number character varying(100) NOT NULL UNIQUE, -- state insurance license number
    license_state character varying(50) NOT NULL,
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(30),
    hire_date date,
    termination_date date,
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Terminated, On Leave
    commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, -- percentage commission
    manager_id character varying(64), -- identifier for the agent's manager (FK to agents or employees)
    PRIMARY KEY (agent_id)
)
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
CREATE TABLE insurance.claim_documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document
    claim_id character varying(64) NOT NULL, -- identifier of the claim this document relates to (FK to claims)
    document_type character varying(50) NOT NULL, -- e.g., Police Report, Photo, Invoice, Medical Bill
    file_name character varying(255) NOT NULL, -- original name of the uploaded file
    file_path character varying(512) NOT NULL, -- storage path (e.g., S3 URL, network path)
    file_size_bytes integer, -- size of the file in bytes
    mime_type character varying(100), -- MIME type of the file (e.g., 'image/jpeg', 'application/pdf')
    uploaded_by character varying(64), -- identifier of the user/system who uploaded (FK to users/customers)
    uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- time of upload
    description text, -- optional description of the document
    PRIMARY KEY (document_id)
)
CREATE TABLE insurance.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)


[User] Can you list each developer's name along with the number of games they have published by joining developers and games?

[Assistant]
SELECT d.name AS developer_name,
       COUNT(g.game_id) AS games_published
FROM gaming_technology.developers d
LEFT JOIN gaming_technology.games g
  ON d.developer_id = g.developer_id
GROUP BY d.name;

[User] Also, only include developers who have published more than 3 games and show the latest release_date of their games.

[Assistant]
SELECT d.name AS developer_name,
       COUNT(g.game_id) AS games_published,
       MAX(g.release_date) AS latest_release
FROM gaming_technology.developers d
JOIN gaming_technology.games g
  ON d.developer_id = g.developer_id
GROUP BY d.name
HAVING COUNT(g.game_id) > 3
ORDER BY latest_release 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.players ( player_id uuid, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id uuid, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )


[User] List the names of employees and the names of the cities where their agency operates service locations.

[Assistant]
SELECT e.first_name, e.last_name, sl.city
FROM government_services.employees e
JOIN government_services.service_locations sl ON e.agency_id = sl.agency_id;

[User] Only show employees who work in locations that are accessible.

[Assistant]
SELECT e.first_name, e.last_name, sl.city
FROM government_services.employees e
JOIN government_services.service_locations sl ON e.agency_id = sl.agency_id
WHERE sl.is_accessible = true;

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] I want to find total PNL and average ROI of smart money token performance for each narrative category. Only include narratives with average ROI greater than 0.5.

[Assistant]
SELECT bi.narrative,
       SUM(smtp.pnl)       AS total_pnl,
       AVG(smtp.roi)       AS avg_roi
FROM smart_money_token_performance AS smtp
JOIN token_basic_info AS bi
  ON smtp.token_symbol = bi.token_symbol
GROUP BY bi.narrative
HAVING AVG(smtp.roi) > 0.5;

[User] Exclude narratives with total net_flow below zero and show only the top 3 narratives by total PNL.

[Assistant]
SELECT bi.narrative,
       SUM(smtp.pnl)       AS total_pnl,
       AVG(smtp.roi)       AS avg_roi,
       SUM(smtp.net_flow)  AS total_net_flow
FROM smart_money_token_performance AS smtp
JOIN token_basic_info AS bi
  ON smtp.token_symbol = bi.token_symbol
GROUP BY bi.narrative
HAVING AVG(smtp.roi) > 0.5
   AND SUM(smtp.net_flow) >= 0
ORDER BY total_pnl 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 project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )
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.text, chain.text, address.text, exchange.text, token_address.text, token_symbol.text, balance.numeric, usd_value.numeric, price.numeric )
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )


[User] Show me all trades (trade_id, security_id, total_amount) executed by employees in the 'Investment' department, along with their employee_id and first_name.

[Assistant] SELECT t.trade_id, t.security_id, t.total_amount, e.employee_id, e.first_name FROM financial_services.trades t JOIN financial_services.employees e ON t.account_id = e.employee_id WHERE e.department = 'Investment';

[User] Now modify the query to only include trades with a total_amount greater than $10,000 and sort them by trade_timestamp in descending order.

[Assistant] SELECT t.trade_id, t.security_id, t.total_amount, e.employee_id, e.first_name FROM financial_services.trades t JOIN financial_services.employees e ON t.account_id = e.employee_id WHERE e.department = 'Investment' AND t.total_amount > 10000 ORDER BY t.trade_timestamp 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 financial_services.trades ( trade_id.text, account_id.text, security_id.text, order_id.text, trade_type.text, quantity.numeric, price_per_unit.numeric, total_amount.numeric, commission.numeric, trade_timestamp.timestamp, settlement_date.date, status.text, execution_venue.text )
CREATE TABLE financial_services.employees ( employee_id.text, first_name.text, last_name.text, job_title.text, department.text, branch_id.text, email.text, phone_extension.text, hire_date.date, termination_date.date, manager_id.text, status.text )


[User] Which hashtags appear on the most posts? Return hashtag_id, tag_name, and the number of posts each hashtag is used in, sorted descending, limited to the top 3.

[Assistant]
SELECT
  h.hashtag_id,
  h.tag_name,
  COUNT(ph.post_id) AS post_count
FROM social_media.hashtags h
JOIN social_media.post_hashtags ph
  ON h.hashtag_id = ph.hashtag_id
GROUP BY h.hashtag_id, h.tag_name
ORDER BY post_count 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 social_media.users ( user_id.text, username.text, email.text, password_hash.text, full_name.text, profile_picture_url.text, bio.text, location.text, created_at.timestamp, updated_at.timestamp, is_verified.boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.messages ( message_id.text, conversation_id.text, sender_user_id.text, content.text, media_url.text, media_type.text, sent_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )


[User] List each citizen's first and last name along with the first and last name of another citizen who shares the same last name. Show each pair only once.

[Assistant]
SELECT c1.first_name || ' ' || c1.last_name AS citizen_name,
       c2.first_name || ' ' || c2.last_name AS other_citizen_name
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.last_name = c2.last_name
 AND c1.citizen_id < c2.citizen_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)


[User] How many service locations do we have in each state?

[Assistant] SELECT state, COUNT(*) AS location_count FROM government_services.service_locations GROUP BY state;

[User] Only show states where there are at least 3 locations.

[Assistant] SELECT state, COUNT(*) AS location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) >= 3;

[User] Can you also show the number of accessible locations in each of those states?

[Assistant] SELECT state, COUNT(*) AS location_count, SUM(CASE WHEN is_accessible = TRUE THEN 1 ELSE 0 END) AS accessible_location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) >= 3;

[User] Order the results by accessible location count in descending order.

[Assistant] SELECT state, COUNT(*) AS location_count, SUM(CASE WHEN is_accessible = TRUE THEN 1 ELSE 0 END) AS accessible_location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) >= 3 ORDER BY accessible_location_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 government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)


[User] List claims along with the name of the insurance product associated with the policy under which the claim was filed. Show claim_id, incident_date, and product_name.

[Assistant] SELECT T1.claim_id, T1.incident_date, T3.product_name FROM insurance.claims AS T1 JOIN policies AS T2 ON T1.policy_id = T2.policy_id JOIN insurance.insurance_products AS T3 ON T2.product_id = T3.product_id;

[User] Only show claims related to 'auto' insurance products.

[Assistant] SELECT T1.claim_id, T1.incident_date, T3.product_name FROM insurance.claims AS T1 JOIN policies AS T2 ON T1.policy_id = T2.policy_id JOIN insurance.insurance_products AS T3 ON T2.product_id = T3.product_id WHERE T3.product_type = 'Auto';

[User] Further filter the results to only include claims with status 'Settled' or 'Closed'.

[Assistant] SELECT T1.claim_id, T1.incident_date, T3.product_name FROM insurance.claims AS T1 JOIN policies AS T2 ON T1.policy_id = T2.policy_id JOIN insurance.insurance_products AS T3 ON T2.product_id = T3.product_id WHERE T3.product_type = 'Auto' AND T1.status IN ('Settled', 'Closed');

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, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
CREATE TABLE insurance.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)