System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp.timestamp, 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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
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 erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_balances (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar NOT NULL, -- Token tick
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, 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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, 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_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)

[User] List all ERC20 tokens (from token_metas) that have 'Governance' in their name.

[Assistant] SELECT contract_address, symbol, name FROM token_metas WHERE is_erc20 = 1 AND name ILIKE '%Governance%';

[User] For these tokens, show their total_supply and decimals as well.

[Assistant] SELECT contract_address, symbol, name, total_supply, decimals FROM token_metas WHERE is_erc20 = 1 AND name ILIKE '%Governance%';

[User] Now, join with token_prices_latest to add the latest price for each token.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, tm.decimals, tpl.price FROM token_metas tm LEFT JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tm.name ILIKE '%Governance%';

[User] Restrict results to only tokens with a latest price above 5.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, tm.decimals, tpl.price FROM token_metas tm LEFT JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tm.name ILIKE '%Governance%' AND tpl.price > 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.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] Retrieve the service names, location names, and cities for active services offered at accessible locations in California.

[Assistant]
SELECT s.service_name,
       sl.location_name,
       sl.city
FROM government_services.services AS s
JOIN government_services.service_locations AS sl
  ON s.agency_id = sl.agency_id
WHERE s.is_active = TRUE
  AND sl.is_accessible = TRUE
  AND sl.state = 'California';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )

[User] Show the latest version number of each document_name for every case.

[Assistant]
SELECT case_id,
       document_name,
       MAX(version) AS latest_version
FROM legal_services.documents
GROUP BY case_id, document_name;

[User] Actually, I also need the upload_timestamp of that latest version.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id,
         document_name,
         MAX(version) AS latest_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) sub
  ON d.case_id = sub.case_id
 AND d.document_name = sub.document_name
 AND d.version = sub.latest_version;

[User] Also include the uploaded_by_lawyer_id for each latest version.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version AS latest_version,
       d.upload_timestamp,
       d.uploaded_by_lawyer_id
FROM legal_services.documents d
JOIN (
  SELECT case_id,
         document_name,
         MAX(version) AS latest_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) sub
  ON d.case_id = sub.case_id
 AND d.document_name = sub.document_name
 AND d.version = sub.latest_version;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )

[User] Show the count of invoices for each case ID.

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id ORDER BY invoice_count DESC

[User] Only include case IDs with more than 2 invoices.

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id HAVING COUNT(invoice_id) > 2 ORDER BY invoice_count DESC

[User] For these cases, what is the average total amount across all invoices?

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count, AVG(total_amount) AS average_total_amount FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id HAVING COUNT(invoice_id) > 2 ORDER BY average_total_amount DESC

[User] Order the results by average total amount ascending.

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count, AVG(total_amount) AS average_total_amount FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id HAVING COUNT(invoice_id) > 2 ORDER BY average_total_amount ASC


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )

[User] Provide a list of all unique genders present in the citizens table.

[Assistant] SELECT DISTINCT gender FROM government_services.citizens;

[User] How many citizens belong to each gender?

[Assistant] SELECT gender, COUNT(*) AS citizen_count FROM government_services.citizens GROUP BY gender;

[User] Only show genders with more than 100 citizens.

[Assistant] SELECT gender, COUNT(*) AS citizen_count FROM government_services.citizens GROUP BY gender HAVING COUNT(*) > 100;

[User] Actually, sort the results by citizen_count in ascending order.

[Assistant] SELECT gender, COUNT(*) AS citizen_count FROM government_services.citizens GROUP BY gender HAVING COUNT(*) > 100 ORDER BY citizen_count ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )

[User] Find pairs of servers in the same region where one server's last heartbeat was recorded within the last hour, and the other server's last heartbeat was recorded between 1 and 2 hours ago. Show the server names, regions, and last heartbeat timestamps for both servers in each pair.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.last_heartbeat AS server1_heartbeat, s2.last_heartbeat AS server2_heartbeat FROM gaming_technology.servers AS s1 JOIN gaming_technology.servers AS s2 ON s1.region = s2.region AND s1.server_id != s2.server_id WHERE s1.last_heartbeat IS NOT NULL AND s2.last_heartbeat IS NOT NULL AND s1.last_heartbeat > NOW() - INTERVAL '1 hour' AND s2.last_heartbeat <= NOW() - INTERVAL '1 hour' AND s2.last_heartbeat > NOW() - INTERVAL '2 hours';

[User] Only include pairs where both servers are currently online.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.last_heartbeat AS server1_heartbeat, s2.last_heartbeat AS server2_heartbeat FROM gaming_technology.servers AS s1 JOIN gaming_technology.servers AS s2 ON s1.region = s2.region AND s1.server_id != s2.server_id WHERE s1.last_heartbeat IS NOT NULL AND s2.last_heartbeat IS NOT NULL AND s1.last_heartbeat > NOW() - INTERVAL '1 hour' AND s2.last_heartbeat <= NOW() - INTERVAL '1 hour' AND s2.last_heartbeat > NOW() - INTERVAL '2 hours' AND s1.status = 'online' AND s2.status = 'online';

[User] Could you also filter the list to only show pairs from regions starting with 'us-'?

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.last_heartbeat AS server1_heartbeat, s2.last_heartbeat AS server2_heartbeat FROM gaming_technology.servers AS s1 JOIN gaming_technology.servers AS s2 ON s1.region = s2.region AND s1.server_id != s2.server_id WHERE s1.last_heartbeat IS NOT NULL AND s2.last_heartbeat IS NOT NULL AND s1.last_heartbeat > NOW() - INTERVAL '1 hour' AND s2.last_heartbeat <= NOW() - INTERVAL '1 hour' AND s2.last_heartbeat > NOW() - INTERVAL '2 hours' AND s1.status = 'online' AND s2.status = 'online' AND s1.region LIKE 'us-%';

[User] Order the results by the region ascending, then by the earlier heartbeat timestamp ascending.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.last_heartbeat AS server1_heartbeat, s2.last_heartbeat AS server2_heartbeat FROM gaming_technology.servers AS s1 JOIN gaming_technology.servers AS s2 ON s1.region = s2.region AND s1.server_id != s2.server_id WHERE s1.last_heartbeat IS NOT NULL AND s2.last_heartbeat IS NOT NULL AND s1.last_heartbeat > NOW() - INTERVAL '1 hour' AND s2.last_heartbeat <= NOW() - INTERVAL '1 hour' AND s2.last_heartbeat > NOW() - INTERVAL '2 hours' AND s1.status = 'online' AND s2.status = 'online' AND s1.region LIKE 'us-%' ORDER BY s1.region ASC, s2.last_heartbeat ASC;


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

[User] Show me product_id, product_name, and base_premium for products created after '2023-01-01'.

[Assistant]
SELECT product_id,
       product_name,
       base_premium
FROM insurance.insurance_products
WHERE created_at > '2023-01-01';

[User] Actually, only include those with a base_premium greater than 1000.

[Assistant]
SELECT product_id,
       product_name,
       base_premium
FROM insurance.insurance_products
WHERE created_at > '2023-01-01'
  AND base_premium > 1000;

[User] Can you also order the results by base_premium descending and limit to the top 5?

[Assistant]
SELECT product_id,
       product_name,
       base_premium
FROM insurance.insurance_products
WHERE created_at > '2023-01-01'
  AND base_premium > 1000
ORDER BY base_premium DESC
LIMIT 5;

[User] Now, I need the total number of such products per product_type.

[Assistant]
SELECT product_type,
       COUNT(*) AS product_count
FROM insurance.insurance_products
WHERE created_at > '2023-01-01'
  AND base_premium > 1000
GROUP BY product_type;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)

[User] List all rooms, showing their room number, type name, and the name of the property they are in.

[Assistant] SELECT T1.room_number, T2.type_name, T3.property_name FROM hospitality_technology.rooms AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.room_type_id = T2.room_type_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.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] Show me reviews from 'Expedia' that have an overall rating of 1 or 2.

[Assistant] SELECT review_id, property_id, guest_id, rating_overall, review_date, comment FROM hospitality_technology.reviews WHERE review_source = 'Expedia' AND rating_overall <= 2;

[User] Actually, only include those submitted in the second half of 2023.

[Assistant] SELECT review_id, property_id, guest_id, rating_overall, review_date, comment FROM hospitality_technology.reviews WHERE review_source = 'Expedia' AND rating_overall <= 2 AND review_date >= '2023-07-01' AND review_date < '2024-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )

[User] I need the average close_price per sector for the last month.

[Assistant]
SELECT s.sector, AVG(m.close_price) AS avg_close_price
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
GROUP BY s.sector;

[User] Can you also include the maximum volume per sector?

[Assistant]
SELECT s.sector,
       AVG(m.close_price)    AS avg_close_price,
       MAX(m.volume)         AS max_volume
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
GROUP BY s.sector;

[User] Now I only want data from source 'Reuters'.

[Assistant]
SELECT s.sector,
       AVG(m.close_price)    AS avg_close_price,
       MAX(m.volume)         AS max_volume
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
  AND m.source = 'Reuters'
GROUP BY s.sector;

[User] Finally, only include sectors with total volume over 1000000 and order by avg_close_price descending.

[Assistant]
SELECT s.sector,
       AVG(m.close_price)    AS avg_close_price,
       MAX(m.volume)         AS max_volume
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
  AND m.source = 'Reuters'
GROUP BY s.sector
HAVING SUM(m.volume) > 1000000
ORDER BY avg_close_price DESC;


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

[User] List all pairs of users who share the same email domain, showing each pair’s user_id, username, and the common domain.

[Assistant]
SELECT u1.user_id AS user1_id,
       u1.username AS user1_name,
       u2.user_id AS user2_id,
       u2.username AS user2_name,
       split_part(u1.email, '@', 2) AS domain
FROM web3.users u1
JOIN web3.users u2
  ON split_part(u1.email, '@', 2) = split_part(u2.email, '@', 2)
 AND u1.user_id < u2.user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )

[User] List all replacement policies where a customer received a new policy starting the day after their previous policy was cancelled. Return customer_id, original_policy_id, original_cancellation_date, new_policy_id, new_start_date.

[Assistant]
SELECT orig.customer_id,
       orig.policy_id      AS original_policy_id,
       orig.cancellation_date AS original_cancellation_date,
       nw.policy_id        AS new_policy_id,
       nw.start_date       AS new_start_date
FROM insurance.policies orig
JOIN insurance.policies nw
  ON orig.customer_id = nw.customer_id
 AND orig.cancellation_date IS NOT NULL
 AND nw.start_date = orig.cancellation_date + INTERVAL '1 day';

[User] Now include the premium_amount difference as premium_diff and only show cases where the new policy's premium is higher.

[Assistant]
SELECT orig.customer_id,
       orig.policy_id      AS original_policy_id,
       orig.cancellation_date AS original_cancellation_date,
       nw.policy_id        AS new_policy_id,
       nw.start_date       AS new_start_date,
       (nw.premium_amount - orig.premium_amount) AS premium_diff
FROM insurance.policies orig
JOIN insurance.policies nw
  ON orig.customer_id = nw.customer_id
 AND orig.cancellation_date IS NOT NULL
 AND nw.start_date = orig.cancellation_date + INTERVAL '1 day'
WHERE nw.premium_amount > orig.premium_amount;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )

[User] Could you list all pairs of active accounts for the same customer, showing customer_id, account_a, and account_b?

[Assistant] SELECT a.customer_id, a.account_number AS account_a, b.account_number AS account_b FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.status = 'Active' AND b.status = 'Active';

[User] Please only include account pairs where both balances exceed 1000.

[Assistant] SELECT a.customer_id, a.account_number AS account_a, b.account_number AS account_b FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.status = 'Active' AND b.status = 'Active' AND a.balance > 1000 AND b.balance > 1000;

[User] Also, filter to accounts opened after 2022-01-01.

[Assistant] SELECT a.customer_id, a.account_number AS account_a, b.account_number AS account_b FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.status = 'Active' AND b.status = 'Active' AND a.balance > 1000 AND b.balance > 1000 AND a.opened_date > '2022-01-01' AND b.opened_date > '2022-01-01';

[User] Finally, order the output by customer_id and account_a.

[Assistant] SELECT a.customer_id, a.account_number AS account_a, b.account_number AS account_b FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.status = 'Active' AND b.status = 'Active' AND a.balance > 1000 AND b.balance > 1000 AND a.opened_date > '2022-01-01' AND b.opened_date > '2022-01-01' ORDER BY a.customer_id, a.account_number;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] 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 expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )

[User] Show me all posts created between '2024-06-01' and '2024-06-30', showing post_id, content, and media_type.

[Assistant] SELECT post_id, content, media_type FROM social_media.posts WHERE created_at >= '2024-06-01' AND created_at < '2024-07-01';

[User] Add the visibility status and filter to only show posts where content is NOT NULL.

[Assistant] SELECT post_id, content, media_type, visibility FROM social_media.posts WHERE created_at >= '2024-06-01' AND created_at < '2024-07-01' AND content IS NOT NULL;

[User] Order the results by creation time descending and limit to the top 10.

[Assistant] SELECT post_id, content, media_type, visibility FROM social_media.posts WHERE created_at >= '2024-06-01' AND created_at < '2024-07-01' AND content IS NOT NULL ORDER BY created_at DESC LIMIT 10;


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

[User] Show the count of posts for each distinct media type.

[Assistant] SELECT media_type, COUNT(*) FROM social_media.posts GROUP BY media_type;

[User] Only include posts created after June 1, 2024.

[Assistant] SELECT media_type, COUNT(*) FROM social_media.posts WHERE created_at >= '2024-06-01' GROUP BY media_type;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.comments ( comment_id text PRIMARY KEY, 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 character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
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 PRIMARY KEY, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
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 PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] Get the count of unread messages for each participant in each group chat, showing conversation_id, group_name, user_id, and unread_count.

[Assistant]
SELECT cp.conversation_id, conv.group_name, cp.user_id, COUNT(m.message_id) AS unread_count
FROM social_media.conversation_participants cp
JOIN social_media.conversations conv ON cp.conversation_id = conv.conversation_id
LEFT JOIN social_media.messages m ON m.conversation_id = cp.conversation_id
  AND m.read_at IS NULL
  AND (cp.last_read_at IS NULL OR m.sent_at > cp.last_read_at)
WHERE conv.is_group_chat = TRUE
GROUP BY cp.conversation_id, conv.group_name, cp.user_id;

[User] Filter to only include counts greater than 5 and order by unread_count descending.

[Assistant]
SELECT cp.conversation_id, conv.group_name, cp.user_id, COUNT(m.message_id) AS unread_count
FROM social_media.conversation_participants cp
JOIN social_media.conversations conv ON cp.conversation_id = conv.conversation_id
LEFT JOIN social_media.messages m ON m.conversation_id = cp.conversation_id
  AND m.read_at IS NULL
  AND (cp.last_read_at IS NULL OR m.sent_at > cp.last_read_at)
WHERE conv.is_group_chat = TRUE
GROUP BY cp.conversation_id, conv.group_name, cp.user_id
HAVING COUNT(m.message_id) > 5
ORDER BY unread_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
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.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )

[User] List the notification ID, message subject, and sent time for all notifications sent through the 'SMS' channel.

[Assistant] SELECT notification_id, message_subject, sent_at FROM government_services.notifications WHERE channel = 'SMS';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] How many appointments are scheduled at each location?

[Assistant] SELECT location_id, COUNT(*) AS scheduled_count FROM healthcare.appointments WHERE status = 'scheduled' GROUP BY location_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.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] Count the number of unique users who are being followed.

[Assistant] SELECT COUNT(DISTINCT following_user_id) FROM social_media.follows


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, 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.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] Provide each developer_id, the number of games they have released, and the total items acquired across all their games.

[Assistant]
SELECT g.developer_id,
       COUNT(g.game_id) AS game_count,
       SUM(pi.quantity) AS total_items_acquired
FROM gaming_technology.games g
JOIN gaming_technology.player_inventory pi
  ON (pi.instance_data->>'game_id')::uuid = g.game_id
GROUP BY g.developer_id;

[User] Only include developers who have released more than 2 games.

[Assistant]
SELECT g.developer_id,
       COUNT(g.game_id) AS game_count,
       SUM(pi.quantity) AS total_items_acquired
FROM gaming_technology.games g
JOIN gaming_technology.player_inventory pi
  ON (pi.instance_data->>'game_id')::uuid = g.game_id
GROUP BY g.developer_id
HAVING COUNT(g.game_id) > 2;

[User] Also require total_items_acquired to exceed 500 and sort by that value descending.

[Assistant]
SELECT g.developer_id,
       COUNT(g.game_id) AS game_count,
       SUM(pi.quantity) AS total_items_acquired
FROM gaming_technology.games g
JOIN gaming_technology.player_inventory pi
  ON (pi.instance_data->>'game_id')::uuid = g.game_id
GROUP BY g.developer_id
HAVING COUNT(g.game_id) > 2
   AND SUM(pi.quantity) > 500
ORDER BY total_items_acquired DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )

[User] List the token IDs and names of all NFTs minted by the wallet '0x1234...' on Ethereum.

[Assistant] SELECT token_id, name FROM nft_metadata WHERE minter = '0x1234...' AND blockchain = 'Ethereum';

[User] Now, for each of those NFTs, show also the collection name by joining to nft_collections.

[Assistant] SELECT nm.token_id, nm.name, nc.name AS collection_name FROM nft_metadata nm LEFT JOIN nft_collections nc ON nm.contract_address = nc.contract_address AND nc.blockchain = 'Ethereum' WHERE nm.minter = '0x1234...' AND nm.blockchain = 'Ethereum';

[User] Only include NFTs where the rarity rank is below 100.

[Assistant] SELECT nm.token_id, nm.name, nc.name AS collection_name FROM nft_metadata nm LEFT JOIN nft_collections nc ON nm.contract_address = nc.contract_address AND nc.blockchain = 'Ethereum' WHERE nm.minter = '0x1234...' AND nm.blockchain = 'Ethereum' AND nm.rarity_rank < 100;


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

[User] Find all pairs of payments for the same policy where the payment_periods overlap. Show payment_id1, payment_id2, policy_id, overlap_start, and overlap_end.

[Assistant]
SELECT p1.payment_id AS payment_id1,
       p2.payment_id AS payment_id2,
       p1.policy_id,
       GREATEST(p1.payment_period_start, p2.payment_period_start) AS overlap_start,
       LEAST(p1.payment_period_end, p2.payment_period_end) AS overlap_end
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.policy_id = p2.policy_id
 AND p1.payment_id < p2.payment_id
WHERE p1.payment_period_start <= p2.payment_period_end
  AND p2.payment_period_start <= p1.payment_period_end;

[User] Only include pairs where both payment statuses are 'completed'.

[Assistant]
SELECT p1.payment_id AS payment_id1,
       p2.payment_id AS payment_id2,
       p1.policy_id,
       GREATEST(p1.payment_period_start, p2.payment_period_start) AS overlap_start,
       LEAST(p1.payment_period_end, p2.payment_period_end) AS overlap_end
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.policy_id = p2.policy_id
 AND p1.payment_id < p2.payment_id
WHERE p1.payment_period_start <= p2.payment_period_end
  AND p2.payment_period_start <= p1.payment_period_end
  AND p1.status = 'completed'
  AND p2.status = 'completed';

[User] Also include the customer_id for each payment in the output.

[Assistant]
SELECT p1.payment_id AS payment_id1,
       p2.payment_id AS payment_id2,
       p1.customer_id AS customer_id1,
       p2.customer_id AS customer_id2,
       p1.policy_id,
       GREATEST(p1.payment_period_start, p2.payment_period_start) AS overlap_start,
       LEAST(p1.payment_period_end, p2.payment_period_end) AS overlap_end
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.policy_id = p2.policy_id
 AND p1.payment_id < p2.payment_id
WHERE p1.payment_period_start <= p2.payment_period_end
  AND p2.payment_period_start <= p1.payment_period_end
  AND p1.status = 'completed'
  AND p2.status = 'completed';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)

[User] Can you show me the number of items per rarity and item type combination, along with the minimum and maximum cost for each group?

[Assistant] SELECT item_type, rarity, COUNT(*) AS num_items, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost FROM gaming_technology.in_game_items GROUP BY item_type, rarity;

[User] Could you only show the combinations where there are more than 2 items in that group?

[Assistant] SELECT item_type, rarity, COUNT(*) AS num_items, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost FROM gaming_technology.in_game_items GROUP BY item_type, rarity HAVING COUNT(*) > 2;

[User] Additionally, can you add the average cost for each group to the results?

[Assistant] SELECT item_type, rarity, COUNT(*) AS num_items, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost, AVG(cost_amount) AS avg_cost FROM gaming_technology.in_game_items GROUP BY item_type, rarity HAVING COUNT(*) > 2;

[User] Now, please only include groups where rarity is not null and order the output by avg_cost descending.

[Assistant] SELECT item_type, rarity, COUNT(*) AS num_items, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost, AVG(cost_amount) AS avg_cost FROM gaming_technology.in_game_items WHERE rarity IS NOT NULL GROUP BY item_type, rarity HAVING COUNT(*) > 2 ORDER BY avg_cost DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )

[User] Show the first name, last name, and license number of all drivers whose license expiry date is after January 1, 2026, along with their status.

[Assistant] SELECT first_name, last_name, license_number, status FROM transportation.drivers WHERE license_expiry_date > '2026-01-01';

[User] Could you also show their hire date and order the results by hire date descending?

[Assistant] SELECT first_name, last_name, license_number, status, hire_date FROM transportation.drivers WHERE license_expiry_date > '2026-01-01' ORDER BY hire_date DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
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.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)

[User] Show the details of all UTXOs with an amount greater than 5, ordered by amount descending.

[Assistant]
SELECT utxo_id, transaction_id, output_index, address, amount, spent
FROM trading_platform.utxos
WHERE amount > 5
ORDER BY amount DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id.text, first_name.text, last_name.text, company_name.text, email.text, phone.text, address.text, date_registered.timestamp, status.text )
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
CREATE TABLE legal_services.cases ( case_id.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 )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )

[User] Get me a list of law firms with the firm_name, founded_date, the managing partner's full name, and the total number of partners at that firm.

[Assistant]
SELECT f.firm_name, f.founded_date, mp.first_name || ' ' || mp.last_name AS managing_partner_full_name, COUNT(l.lawyer_id) FILTER (WHERE l.is_partner) AS partner_count
FROM legal_services.law_firms f
LEFT JOIN legal_services.lawyers mp ON f.managing_partner_id = mp.lawyer_id
LEFT JOIN legal_services.lawyers l ON f.firm_id = l.firm_id
GROUP BY f.firm_id, f.firm_name, f.founded_date, mp.first_name, mp.last_name;

[User] Now restrict the list to firms founded after 2010 that have at least 2 partners, and order by partner_count descending.

[Assistant]
SELECT f.firm_name, f.founded_date, mp.first_name || ' ' || mp.last_name AS managing_partner_full_name, COUNT(l.lawyer_id) FILTER (WHERE l.is_partner) AS partner_count
FROM legal_services.law_firms f
LEFT JOIN legal_services.lawyers mp ON f.managing_partner_id = mp.lawyer_id
LEFT JOIN legal_services.lawyers l ON f.firm_id = l.firm_id
GROUP BY f.firm_id, f.firm_name, f.founded_date, mp.first_name, mp.last_name
HAVING COUNT(l.lawyer_id) FILTER (WHERE l.is_partner) >= 2
  AND f.founded_date > '2010-01-01'
ORDER BY partner_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )

[User] How many notifications are there for each distinct notification type?

[Assistant] SELECT notification_type, COUNT(*) FROM social_media.notifications GROUP BY notification_type;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )

[User] List all prescriptions where the dosage text contains the word 'unit'. Show the prescription ID, medication ID, and dosage.

[Assistant] SELECT prescription_id, medication_id, dosage FROM healthcare.prescriptions WHERE dosage LIKE '%unit%';

[User] From that list, also filter to only show prescriptions where the number of refills allowed is greater than 0.

[Assistant] SELECT prescription_id, medication_id, dosage FROM healthcare.prescriptions WHERE dosage LIKE '%unit%' AND refills_allowed > 0;


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.stations ( station_id text PRIMARY KEY, station_name text, city text, state_province text, country_code text, address text, timezone text, number_of_platforms int, created_at timestamp, last_updated_at timestamp )

[User] What is the maintenance schedule for the platforms at the station with ID 'ST234' for the next month?

[Assistant] I'm sorry, but I don't have access to the maintenance schedule for the platforms at any station. The data I have only includes basic station information such as station ID, name, location, and number of platforms. For maintenance schedules, you may need to contact the station management or relevant authorities.


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )

[User] Find pairs of lawyers who work for the same firm AND share the same specialization, excluding pairs where the lawyer IDs are the same. Show their first names, last names, firm ID, and specialization. Order the results by firm ID and then specialization.

[Assistant] SELECT l1.first_name, l1.last_name, l2.first_name AS lawyer2_first_name, l2.last_name AS lawyer2_last_name, l1.firm_id, l1.specialization FROM legal_services.lawyers AS l1 JOIN legal_services.lawyers AS l2 ON l1.firm_id = l2.firm_id AND l1.specialization = l2.specialization AND l1.lawyer_id < l2.lawyer_id ORDER BY l1.firm_id, l1.specialization;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)

[User] Show me all maintenance logs for 'Oil Change' services performed in the last 6 months, including the vehicle ID, service date, and cost.

[Assistant] SELECT vehicle_id, service_date, cost FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '6 months';

[User] Can you also include the mechanic name and filter to only show services that cost more than $100?

[Assistant] SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '6 months' AND cost > 100;

[User] Now order these results by service date with the most recent first and limit to 10 records.

[Assistant] SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '6 months' AND cost > 100 ORDER BY service_date DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )

[User] Find tokens on the 'Polygon' chain with a market cap greater than $1,000,000,000 and a positive price change in the last 24 hours. List their symbol, name, market cap, and 24h price change.

[Assistant] SELECT token_symbol, token_name, market_cap, price_change_percentage_24h FROM token_basic_info WHERE chain = 'Polygon' AND market_cap > 1000000000 AND price_change_percentage_24h > 0;

[User] Also include their current price and 7-day price change percentage. Order the results by market cap descending.

[Assistant] SELECT token_symbol, token_name, market_cap, price_change_percentage_24h, price, price_change_percentage_7d FROM token_basic_info WHERE chain = 'Polygon' AND market_cap > 1000000000 AND price_change_percentage_24h > 0 ORDER BY market_cap DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )

[User] Find all pairs of lawyers who were hired on the exact same date but have different specializations. Return each lawyer's name, hire_date, and both specializations.

[Assistant]
SELECT a.lawyer_id   AS lawyer1_id,
       a.first_name  AS lawyer1_first_name,
       a.last_name   AS lawyer1_last_name,
       b.lawyer_id   AS lawyer2_id,
       b.first_name  AS lawyer2_first_name,
       b.last_name   AS lawyer2_last_name,
       a.hire_date,
       a.specialization AS specialization1,
       b.specialization AS specialization2
FROM legal_services.lawyers a
JOIN legal_services.lawyers b
  ON DATE(a.hire_date) = DATE(b.hire_date)
 AND a.lawyer_id < b.lawyer_id
 AND a.specialization <> b.specialization;

[User] Actually, only include pairs where at least one of the lawyers is a partner.

[Assistant]
SELECT a.lawyer_id   AS lawyer1_id,
       a.first_name  AS lawyer1_first_name,
       a.last_name   AS lawyer1_last_name,
       b.lawyer_id   AS lawyer2_id,
       b.first_name  AS lawyer2_first_name,
       b.last_name   AS lawyer2_last_name,
       a.hire_date,
       a.specialization AS specialization1,
       b.specialization AS specialization2
FROM legal_services.lawyers a
JOIN legal_services.lawyers b
  ON DATE(a.hire_date) = DATE(b.hire_date)
 AND a.lawyer_id < b.lawyer_id
 AND a.specialization <> b.specialization
WHERE a.is_partner OR b.is_partner;

[User] Also, sort the results by hire_date descending and then by the first lawyer's last_name ascending.

[Assistant]
SELECT a.lawyer_id   AS lawyer1_id,
       a.first_name  AS lawyer1_first_name,
       a.last_name   AS lawyer1_last_name,
       b.lawyer_id   AS lawyer2_id,
       b.first_name  AS lawyer2_first_name,
       b.last_name   AS lawyer2_last_name,
       a.hire_date,
       a.specialization AS specialization1,
       b.specialization AS specialization2
FROM legal_services.lawyers a
JOIN legal_services.lawyers b
  ON DATE(a.hire_date) = DATE(b.hire_date)
 AND a.lawyer_id < b.lawyer_id
 AND a.specialization <> b.specialization
WHERE a.is_partner OR b.is_partner
ORDER BY a.hire_date DESC,
         a.last_name ASC;


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

[User] List all pairs of insurance products that share the same product_type but have differing active statuses. Return both product_ids, the product_type, and each is_active flag.

[Assistant]
SELECT p1.product_id AS product_id_1, p2.product_id AS product_id_2, p1.product_type, p1.is_active AS is_active_1, p2.is_active AS is_active_2
FROM insurance.insurance_products p1
JOIN insurance.insurance_products p2
  ON p1.product_type = p2.product_type
  AND p1.is_active <> p2.is_active
WHERE p1.product_id < p2.product_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.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 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.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
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] For each claim, show the claim ID, incident date, the customer's first and last name, and the policy number under which it was filed.

[Assistant] SELECT cl.claim_id, cl.incident_date, c.first_name AS customer_first_name, c.last_name AS customer_last_name, p.policy_number FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id JOIN insurance.policies AS p ON cl.policy_id = p.policy_id;

[User] Filter these results to only include claims reported in the year 2024.

[Assistant] SELECT cl.claim_id, cl.incident_date, c.first_name AS customer_first_name, c.last_name AS customer_last_name, p.policy_number FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id JOIN insurance.policies AS p ON cl.policy_id = p.policy_id WHERE cl.reported_date >= '2024-01-01' AND cl.reported_date < '2025-01-01';

[User] Now, only show claims where the status is 'Settled' or 'Approved', and include the settlement amount.

[Assistant] SELECT cl.claim_id, cl.incident_date, c.first_name AS customer_first_name, c.last_name AS customer_last_name, p.policy_number, cl.settlement_amount FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id JOIN insurance.policies AS p ON cl.policy_id = p.policy_id WHERE cl.reported_date >= '2024-01-01' AND cl.reported_date < '2025-01-01' AND cl.status IN ('Settled', 'Approved');

[User] For *these* settled or approved claims reported in 2024, find the count of associated claim documents and the total size of those documents. Show the claim ID, customer full name, and the document count and total size.

[Assistant] SELECT cl.claim_id, c.first_name AS customer_first_name, c.last_name AS customer_last_name, COUNT(cd.document_id) AS document_count, SUM(cd.file_size_bytes) AS total_document_size_bytes FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id LEFT JOIN insurance.claim_documents AS cd ON cl.claim_id = cd.claim_id WHERE cl.reported_date >= '2024-01-01' AND cl.reported_date < '2025-01-01' AND cl.status IN ('Settled', 'Approved') GROUP BY cl.claim_id, c.first_name, c.last_name ORDER BY cl.claim_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 )
CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, 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.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
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.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] Could you get the total spend on rare items for each player along with the player's username?

[Assistant]
SELECT p.player_id,
       p.username,
       SUM(pi.quantity * i.cost_amount) AS total_spend
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.players p ON pi.player_id = p.player_id
WHERE i.rarity = 'rare'
GROUP BY p.player_id, p.username;

[User] Actually, limit to players who registered after 2022-01-01 and include their country_code.

[Assistant]
SELECT p.player_id,
       p.username,
       p.country_code,
       SUM(pi.quantity * i.cost_amount) AS total_spend
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.players p ON pi.player_id = p.player_id
WHERE i.rarity = 'rare'
  AND p.registration_date > '2022-01-01'
GROUP BY p.player_id, p.username, p.country_code;

[User] Also, only consider items from games on the 'PC' platform and order the results by total_spend descending.

[Assistant]
SELECT p.player_id,
       p.username,
       p.country_code,
       SUM(pi.quantity * i.cost_amount) AS total_spend
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.players p ON pi.player_id = p.player_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE i.rarity = 'rare'
  AND p.registration_date > '2022-01-01'
  AND g.platform = 'PC'
GROUP BY p.player_id, p.username, p.country_code
ORDER BY total_spend DESC;

[User] Great, but show only the top 10 players.

[Assistant]
SELECT p.player_id,
       p.username,
       p.country_code,
       SUM(pi.quantity * i.cost_amount) AS total_spend
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.players p ON pi.player_id = p.player_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE i.rarity = 'rare'
  AND p.registration_date > '2022-01-01'
  AND g.platform = 'PC'
GROUP BY p.player_id, p.username, p.country_code
ORDER BY total_spend DESC
LIMIT 10;


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

[User] Find pairs of distinct token transfers that occurred in the same transaction and were initiated by the same sender address. List the transaction ID, the common sender address, and both transfer IDs.

[Assistant]
SELECT
  t1.transaction_id,
  t1.from_address,
  t1.transfer_id AS transfer_id_1,
  t2.transfer_id AS transfer_id_2
FROM web3.token_transfers AS t1
JOIN web3.token_transfers AS t2
  ON t1.transaction_id = t2.transaction_id
  AND t1.from_address = t2.from_address
WHERE
  t1.transfer_id < t2.transfer_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id uuid, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid, player_id uuid, item_id uuid, quantity integer, acquired_at timestamp with time zone, instance_data jsonb )

[User] I’d like to see how many achievements each player has unlocked and the date of their first unlock.

[Assistant]
SELECT pa.player_id, COUNT(pa.achievement_id) AS achievement_count, MIN(pa.unlocked_at) AS first_unlocked
FROM gaming_technology.player_achievements pa
GROUP BY pa.player_id;

[User] Actually, exclude players with fewer than 3 achievements and only consider achievements worth at least 10 points.

[Assistant]
SELECT pa.player_id, COUNT(pa.achievement_id) AS achievement_count, MIN(pa.unlocked_at) AS first_unlocked
FROM gaming_technology.player_achievements pa
JOIN gaming_technology.achievements a ON pa.achievement_id = a.achievement_id
WHERE a.points >= 10
GROUP BY pa.player_id
HAVING COUNT(pa.achievement_id) >= 3;

[User] Also include the title of the game for the earliest unlocked achievement.

[Assistant]
SELECT x.player_id, x.achievement_count, x.first_unlocked, g.title AS game_title
FROM (
  SELECT pa.player_id,
         COUNT(pa.achievement_id) AS achievement_count,
         MIN(pa.unlocked_at) AS first_unlocked
  FROM gaming_technology.player_achievements pa
  JOIN gaming_technology.achievements a ON pa.achievement_id = a.achievement_id
  WHERE a.points >= 10
  GROUP BY pa.player_id
  HAVING COUNT(pa.achievement_id) >= 3
) x
JOIN gaming_technology.player_achievements pa2
  ON x.player_id = pa2.player_id AND x.first_unlocked = pa2.unlocked_at
JOIN gaming_technology.achievements a2
  ON pa2.achievement_id = a2.achievement_id
JOIN gaming_technology.games g
  ON a2.game_id = g.game_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.time_entries ( entry_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, date_worked date NOT NULL, hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), billing_rate numeric(10, 2) NOT NULL, description text NOT NULL, is_billable boolean DEFAULT true, is_billed boolean DEFAULT false, invoice_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (entry_id) )
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )

[User] Show all appointments, including subject, start time, and the billing rate for the lawyer who handled the appointment.

[Assistant]
SELECT a.subject, a.start_time, te.billing_rate
FROM legal_services.appointments a
JOIN legal_services.time_entries te ON a.case_id = te.case_id AND a.lawyer_id = te.lawyer_id;

[User] Actually, I only want appointments that have status 'Scheduled' and where the hours spent in the associated time entries is greater than 2.

[Assistant]
SELECT a.subject, a.start_time, te.billing_rate
FROM legal_services.appointments a
JOIN legal_services.time_entries te ON a.case_id = te.case_id AND a.lawyer_id = te.lawyer_id
WHERE a.status = 'Scheduled' AND te.hours_spent > 2;

[User] Also, sort the results by start time ascending.

[Assistant]
SELECT a.subject, a.start_time, te.billing_rate
FROM legal_services.appointments a
JOIN legal_services.time_entries te ON a.case_id = te.case_id AND a.lawyer_id = te.lawyer_id
WHERE a.status = 'Scheduled' AND te.hours_spent > 2
ORDER BY a.start_time ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )

[User] List the number of bookings made by each passenger, including passenger_id, first_name, last_name, and booking_count.

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

[User] Actually, only include passengers who have made at least 2 bookings.

[Assistant]
SELECT p.passenger_id,
       p.first_name,
       p.last_name,
       COUNT(b.booking_id) AS booking_count
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id,
         p.first_name,
         p.last_name
HAVING COUNT(b.booking_id) >= 2;

[User] Also include the average fare per passenger.

[Assistant]
SELECT p.passenger_id,
       p.first_name,
       p.last_name,
       COUNT(b.booking_id)     AS booking_count,
       AVG(b.fare)             AS average_fare
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id,
         p.first_name,
         p.last_name
HAVING COUNT(b.booking_id) >= 2;

[User] Sort the results by average_fare descending and limit to the top 5.

[Assistant]
SELECT p.passenger_id,
       p.first_name,
       p.last_name,
       COUNT(b.booking_id)     AS booking_count,
       AVG(b.fare)             AS average_fare
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id,
         p.first_name,
         p.last_name
HAVING COUNT(b.booking_id) >= 2
ORDER BY average_fare DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )

[User] How many conversations are there where the last message was sent before January 1, 2024?

[Assistant] SELECT COUNT(*) FROM social_media.conversations WHERE last_message_at < '2024-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] What is the average ROI and average realized_ratio for each chain?

[Assistant]
SELECT chain,
       AVG(roi) AS avg_roi,
       AVG(realized_ratio) AS avg_realized_ratio
FROM smart_money_token_performance
GROUP BY chain;

[User] Now filter to only include chains where average ROI is above 0.5.

[Assistant]
WITH stats AS (
  SELECT chain,
         AVG(roi) AS avg_roi,
         AVG(realized_ratio) AS avg_realized_ratio
  FROM smart_money_token_performance
  GROUP BY chain
)
SELECT chain, avg_roi, avg_realized_ratio
FROM stats
WHERE avg_roi > 0.5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )

[User] List all policies that expired in the last 30 days, along with their product IDs and premium amounts.

[Assistant] SELECT policy_id, product_id, premium_amount FROM insurance.policies WHERE end_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND CURRENT_DATE AND status = 'expired';

[User] Now include only policies that had a deductible of $1000 or more.

[Assistant] SELECT policy_id, product_id, premium_amount, deductible FROM insurance.policies WHERE end_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND CURRENT_DATE AND status = 'expired' AND deductible >= 1000;