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.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
##Table Structure
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
##Table Structure
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"
##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.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
##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 )
##Table Structure
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )

[User] List each account number and the total quantity of shares traded through it.

[Assistant] SELECT T2.account_number, SUM(T1.quantity) FROM financial_services.trades AS T1 JOIN financial_services.accounts AS T2 ON T1.account_id = T2.account_id GROUP BY 1

[User] Only include accounts with total quantity traded greater than 1000, and order the results by total quantity descending.

[Assistant] SELECT T2.account_number, SUM(T1.quantity) AS total_traded_quantity FROM financial_services.trades AS T1 JOIN financial_services.accounts AS T2 ON T1.account_id = T2.account_id GROUP BY 1 HAVING SUM(T1.quantity) > 1000 ORDER BY total_traded_quantity DESC

[User] Show me all assets whose symbol starts with 'BTC' or 'ETH', along with their full names and types.

[Assistant] SELECT asset_id, name, symbol, type FROM trading_platform.assets WHERE symbol LIKE 'BTC%' OR symbol LIKE 'ETH%';

[User] Find all tokens on the 'BSC' chain in the latest snapshot where the individual holding `usd_value` is greater than $1,000,000. Show their symbol, exchange, balance, and USD value.

[Assistant]
WITH latest_snapshot AS (
  SELECT max(snapshot_time) as max_time
  FROM cex_token_balance
)
SELECT token_symbol, exchange, balance, usd_value
FROM cex_token_balance ctb
JOIN latest_snapshot ls ON ctb.snapshot_time = ls.max_time
WHERE chain = 'BSC' AND usd_value > 1000000.0;

[User] Retrieve all notifications with status 'failed' along with the citizen's full name and contact_phone for those notifications that occurred in the past 30 days.

[Assistant]
SELECT n.notification_id,
       n.sent_at,
       n.status,
       c.first_name || ' ' || c.last_name AS full_name,
       c.contact_phone
FROM government_services.notifications n
JOIN government_services.citizens c
  ON n.citizen_id = c.citizen_id
WHERE n.status = 'failed'
  AND n.sent_at >= NOW() - INTERVAL '30 days';

[User] List each insurance provider along with the number of distinct plan types they offer.

[Assistant]
SELECT insurance_provider, COUNT(DISTINCT plan_type) AS type_count
FROM healthcare.insurance_plans
GROUP BY insurance_provider;

[User] How many clients registered in each month of 2024? Provide the month (YYYY-MM) and the number of registrations.

[Assistant] SELECT TO_CHAR(date_registered, 'YYYY-MM') AS month, COUNT(*) AS registration_count FROM legal_services.clients WHERE date_registered BETWEEN '2024-01-01' AND '2024-12-31' GROUP BY month ORDER BY month;

[User] List the sender_user_id and the total number of messages they have sent that include media attachments, along with the conversation_id.

[Assistant]
SELECT sender_user_id, conversation_id, COUNT(*) AS media_message_count
FROM social_media.messages
WHERE media_url IS NOT NULL AND media_url <> ''
GROUP BY sender_user_id, conversation_id;

[User] Only include media attachments where media_type is 'video'.

[Assistant]
SELECT sender_user_id, conversation_id, COUNT(*) AS video_media_message_count
FROM social_media.messages
WHERE media_url IS NOT NULL AND media_url <> '' AND media_type = 'video'
GROUP BY sender_user_id, conversation_id;

[User] How many users registered in 2024?

[Assistant] SELECT COUNT(*) FROM trading_platform.users WHERE DATE_PART('year', created_at) = 2024;

[User] Count the total number of hashtags.

[Assistant] SELECT COUNT(*) FROM social_media.hashtags;


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, national_id_number.text, first_name.text, last_name.text, date_of_birth.date, gender.text, primary_address.text, contact_email.text, contact_phone.text, registration_date.timestamp, is_verified.boolean )
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.payments ( payment_id.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.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 )
##Table Structure
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )
##Table Structure
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
##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 )
##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)
)
##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] Count the total number of employees who have a direct manager assigned.

[Assistant] SELECT COUNT(employee_id) FROM government_services.employees WHERE manager_employee_id IS NOT NULL;

[User] List the document ID, document type, and the full name of the citizen who submitted the document, but only for documents submitted for applications with a status of 'Approved'.

[Assistant] SELECT T1.document_id, T1.document_type, T3.first_name, T3.last_name FROM government_services.documents AS T1 JOIN government_services.applications AS T2 ON T1.application_id = T2.application_id JOIN government_services.citizens AS T3 ON T1.citizen_id = T3.citizen_id WHERE T2.status = 'Approved';

[User] List all token symbols related to the 'Gaming' narrative that had a net positive token inflow.

[Assistant] SELECT token_symbol FROM smart_money_token_inflow WHERE narrative = 'Gaming' AND usd_value > 0 GROUP BY token_symbol;

[User] List all CEX addresses on the BSC chain that hold more than $1 million USD value in total.

[Assistant] SELECT address, SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE chain = 'BSC' GROUP BY address HAVING SUM(usd_value) > 1000000;

[User] Provide every combination of medication name and insurance plan name.

[Assistant]
SELECT m.medication_name, p.plan_name
FROM healthcare.medications AS m
CROSS JOIN healthcare.insurance_plans AS p;

[User] List all smart money addresses that have a negative PNL but a positive Realized Ratio. Show the address, chain, PNL, and Realized Ratio.

[Assistant] SELECT token_address, chain, pnl, realized_ratio FROM smart_money_token_performance WHERE pnl < 0 AND realized_ratio > 0

[User] Can you refine the results to only include addresses where the absolute value of PNL is greater than 1000?

[Assistant] SELECT token_address, chain, pnl, realized_ratio FROM smart_money_token_performance WHERE pnl < -1000 AND realized_ratio > 0

[User] List all pairs of token transfers where the sender is the same but the recipients differ. Show both transfer IDs and the common sender address.

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

[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 government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE blockchain.blocks ( block_id character varying(64) NOT NULL, previous_block_id character varying(64), timestamp timestamp NOT NULL, nonce integer NOT NULL, merkle_root character varying(128) NOT NULL, difficulty integer NOT NULL, PRIMARY KEY (block_id) )
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )
##Table Structure
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 )
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
##Table Structure
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
##Table Structure
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )

[User] Which services have the longest average processing times? List the top 5 services by average processing time.

[Assistant]
SELECT
  service_name,
  average_processing_time_days
FROM
  government_services.services
ORDER BY
  average_processing_time_days DESC
LIMIT 5;

[User] Find all pairs of distinct block IDs that were mined at the exact same timestamp. Show both block IDs and the shared timestamp.

[Assistant] SELECT t1.block_id AS block_id_1, t2.block_id AS block_id_2, t1.timestamp FROM blockchain.blocks AS t1 JOIN blockchain.blocks AS t2 ON t1.timestamp = t2.timestamp WHERE t1.block_id < t2.block_id;

[User] Show me all appointments where the lawyer_id matches the client_id, and display the appointment_id, start_time, and status.

[Assistant] SELECT appointment_id, start_time, status FROM legal_services.appointments WHERE lawyer_id = client_id;

[User] Find the average commission rate among all agents whose hire date is after '2020-01-01'.

[Assistant] SELECT AVG(commission_rate) FROM insurance.agents WHERE hire_date > '2020-01-01';

[User] Show each user ID with the date of their first created wallet.

[Assistant]
SELECT user_id, MIN(created_at) AS first_wallet_date
FROM trading_platform.wallets
GROUP BY user_id;

[User] Get all non-smoking rooms with status 'Available'.

[Assistant]
SELECT room_id, property_id, room_number, floor
FROM hospitality_technology.rooms
WHERE is_smoking = FALSE
  AND status = 'Available';

[User] Now include the property_name for each room.

[Assistant]
SELECT r.room_id, r.room_number, p.property_name, r.floor
FROM hospitality_technology.rooms r
JOIN hospitality_technology.properties p
  ON r.property_id = p.property_id
WHERE r.is_smoking = FALSE
  AND r.status = 'Available';

[User] List the first name and last name of each employee, along with the first and last name of their manager.

[Assistant] SELECT e.first_name AS employee_first_name, e.last_name AS employee_last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM government_services.employees AS e LEFT JOIN government_services.employees AS m ON e.manager_employee_id = m.employee_id;

[User] Can you show me a list of all active services along with their agency IDs and categories?

[Assistant] SELECT service_id, agency_id, service_name, category FROM government_services.services WHERE is_active = TRUE;

[User] Actually, only include services where the standard fee is less than 50.

[Assistant] SELECT service_id, agency_id, service_name, category FROM government_services.services WHERE is_active = TRUE AND standard_fee < 50;

[User] Can you show me a list of all agencies along with their parent agency names?

[Assistant]
SELECT a.agency_id, a.agency_name, pa.agency_name AS parent_agency_name
FROM government_services.agencies a
LEFT JOIN government_services.agencies pa ON a.parent_agency_id = pa.agency_id;

[User] Only show agencies that actually have a parent agency.

[Assistant]
SELECT a.agency_id, a.agency_name, pa.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies pa ON a.parent_agency_id = pa.agency_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.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 )
##Table Structure
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)
##Table Structure
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text PRIMARY KEY, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults int, num_children int, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )

[User] For each claim, retrieve the document_id, file_name, and uploaded_at of the earliest and the latest uploaded document.

[Assistant]
SELECT
    c1.claim_id,
    c1.document_id AS earliest_document_id,
    c1.file_name AS earliest_file_name,
    c1.uploaded_at AS earliest_uploaded_at,
    c2.document_id AS latest_document_id,
    c2.file_name AS latest_file_name,
    c2.uploaded_at AS latest_uploaded_at
FROM insurance.claim_documents c1
JOIN insurance.claim_documents c2
  ON c1.claim_id = c2.claim_id
  AND c1.uploaded_at = (
    SELECT MIN(cd.uploaded_at)
    FROM insurance.claim_documents cd
    WHERE cd.claim_id = c1.claim_id
  )
  AND c2.uploaded_at = (
    SELECT MAX(cd.uploaded_at)
    FROM insurance.claim_documents cd
    WHERE cd.claim_id = c2.claim_id
  );

[User] Which achievements have been unlocked by more than 100 unique players? Show the achievement ID and the count.

[Assistant] SELECT achievement_id, COUNT(DISTINCT player_id) AS player_count FROM gaming_technology.player_achievements GROUP BY achievement_id HAVING COUNT(DISTINCT player_id) > 100 ORDER BY player_count DESC;

[User] List all trades that occurred on July 10, 2024, showing the trade ID, asset symbol, quantity, and trade price.

[Assistant]
SELECT t.trade_id, a.symbol AS asset_symbol, t.quantity, t.price
FROM trading_platform.trades t
JOIN trading_platform.assets a ON t.asset_id = a.asset_id
WHERE DATE(t.traded_at) = '2024-07-10';

[User] How many users have disabled push notifications?

[Assistant]
SELECT COUNT(*) AS disabled_push_count
FROM social_media.user_settings
WHERE push_notifications_enabled = false;

[User] List all accounts with a balance below 1000, showing the account_id, account_number, and currency.

[Assistant]
SELECT account_id, account_number, currency
FROM financial_services.accounts
WHERE balance < 1000;

[User] Now, also include accounts with a negative balance and order the result by balance ascending.

[Assistant]
SELECT account_id, account_number, currency, balance
FROM financial_services.accounts
WHERE balance < 1000 OR balance < 0
ORDER BY balance ASC;

[User] I only want to see the accounts where status is not 'Closed'.

[Assistant]
SELECT account_id, account_number, currency, balance
FROM financial_services.accounts
WHERE (balance < 1000 OR balance < 0) AND status <> 'Closed'
ORDER BY balance ASC;

[User] List each reservation along with the next reservation for the same guest. Show the original reservation_id, its check_out_date, the next_reservation_id, and the next reservation's check_in_date.

[Assistant]
SELECT r1.reservation_id,
       r1.check_out_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM hospitality_technology.reservations r1
LEFT JOIN hospitality_technology.reservations r2
  ON r2.guest_id = r1.guest_id
  AND r2.check_in_date = (
    SELECT MIN(r3.check_in_date)
    FROM hospitality_technology.reservations r3
    WHERE r3.guest_id = r1.guest_id
      AND r3.check_in_date > r1.check_out_date
  );

[User] Count the number of events for each hour of the day based on the emitted_at timestamp.

[Assistant] SELECT EXTRACT(HOUR FROM emitted_at) AS event_hour, COUNT(*) AS event_count FROM web3.events GROUP BY event_hour ORDER BY event_hour;

[User] Actually, only show hours with more than 100 events.

[Assistant] SELECT EXTRACT(HOUR FROM emitted_at) AS event_hour, COUNT(*) AS event_count FROM web3.events GROUP BY event_hour HAVING COUNT(*) > 100 ORDER BY event_hour;

[User] List the usernames and registration dates for all players from Germany ('DE') who are currently 'online'.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE country_code = 'DE' AND status = 'online';

[User] Now, for players in Germany ('DE'), show me the count of players for each different status recorded in the table.

[Assistant] SELECT status, COUNT(player_id) FROM gaming_technology.players WHERE country_code = 'DE' GROUP BY status;


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 character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.notifications (
    notification_id character varying(64) NOT NULL,  -- unique identifier for the notification
    user_id character varying(64) NOT NULL, -- identifier of the user receiving the notification
    message text NOT NULL, -- message of the notification
    sent_at timestamp NOT NULL, -- time when the notification was sent
    read_at timestamp, -- time when the notification was read
    PRIMARY KEY (notification_id)
)
##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 )
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##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 )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )
##Table Structure
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )

[User] Show all wallet addresses that have ever received a UTXO.

[Assistant]
SELECT DISTINCT address
FROM trading_platform.utxos;

[User] Show me all invoice numbers and due dates where the amount paid is exactly zero.

[Assistant] SELECT invoice_number, due_date FROM legal_services.invoices WHERE amount_paid = 0;

[User] Find all patients who have more than two primary active insurance policies, showing their patient ID and the count of such policies. Also, list the plan names for these policies.

[Assistant]
SELECT pi.patient_id, COUNT(*) AS active_primary_policy_count, STRING_AGG(ip.plan_name, ', ') AS plan_names
FROM healthcare.patient_insurance pi
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE pi.is_primary = TRUE AND (pi.expiration_date IS NULL OR pi.expiration_date > CURRENT_DATE)
GROUP BY pi.patient_id
HAVING COUNT(*) > 2;

[User] Find all pairs of citizens who share the same last name but have different dates of birth. Display both full names, the shared last name, and each date of birth.

[Assistant]
SELECT
  c1.first_name || ' ' || c1.last_name AS citizen1_name,
  c2.first_name || ' ' || c2.last_name AS citizen2_name,
  c1.last_name AS shared_last_name,
  c1.date_of_birth AS dob1,
  c2.date_of_birth AS dob2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.last_name = c2.last_name
     AND c1.citizen_id < c2.citizen_id
     AND c1.date_of_birth <> c2.date_of_birth;

[User] List all combinations of manufacturers and generic names. For each combination, display the manufacturer, generic_name, and the number of medications.

[Assistant] SELECT manufacturer, generic_name, COUNT(*) AS medication_count FROM healthcare.medications GROUP BY manufacturer, generic_name;

[User] Only show combinations where there are at least 3 medications and exclude rows where generic_name is missing.

[Assistant] SELECT manufacturer, generic_name, COUNT(*) AS medication_count FROM healthcare.medications WHERE generic_name IS NOT NULL AND generic_name <> '' GROUP BY manufacturer, generic_name HAVING COUNT(*) >= 3;

[User] Show me all participants who joined any conversation before January 1st, 2024. Return participant_id, user_id, conversation_id and the joined_at timestamp.

[Assistant] SELECT participant_id, user_id, conversation_id, joined_at FROM social_media.conversation_participants WHERE joined_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 healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    application_id character varying(64), -- FK to applications table (optional)
    message_subject character varying(255),
    message_body text NOT NULL,
    channel character varying(30) NOT NULL, -- e.g., Email, SMS, Portal Message, Mail
    sent_at timestamp NOT NULL,
    status character varying(30) NOT NULL, -- e.g., Queued, Sent, Delivered, Failed, Read
    related_entity_type character varying(50), -- e.g., Application, Appointment, Document Request
    related_entity_id character varying(64), -- ID of the related entity
    PRIMARY KEY (notification_id)
)
##Table Structure
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_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 )
##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.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
##Table Structure
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )

[User] List all appointments that are currently scheduled and show their appointment time.

[Assistant] SELECT appointment_id, patient_id, doctor_id, appointment_time FROM healthcare.appointments WHERE status = 'Scheduled';

[User] Retrieve the agency name and the most recent notification sent date for each agency, considering only notifications related to agencies.

[Assistant]
SELECT a.agency_name, MAX(n.sent_at) AS last_notification_date
FROM government_services.agencies a
JOIN government_services.notifications n
  ON n.related_entity_type = 'Agency'
  AND n.related_entity_id = a.agency_id
GROUP BY a.agency_name;

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

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

[User] List the usernames and emails of users who have set a location in their profile.

[Assistant]
SELECT username, email
FROM social_media.users
WHERE location IS NOT NULL AND location != '';

[User] Which service locations do not have a contact phone specified? Show the location_id and location_name.

[Assistant]
SELECT location_id, location_name
FROM government_services.service_locations
WHERE contact_phone IS NULL OR contact_phone = '';

[User] Calculate the total quantity and average cost_per_unit for each fuel_type in the fuel_logs table.

[Assistant]
SELECT fuel_type,
       SUM(quantity)         AS total_quantity,
       AVG(cost_per_unit)    AS avg_cost_per_unit
FROM transportation.fuel_logs
GROUP BY fuel_type;

[User] Actually, only include fuel types where the total quantity exceeds 1000 and order the results by avg_cost_per_unit descending.

[Assistant]
SELECT fuel_type,
       SUM(quantity)         AS total_quantity,
       AVG(cost_per_unit)    AS avg_cost_per_unit
FROM transportation.fuel_logs
GROUP BY fuel_type
HAVING SUM(quantity) > 1000
ORDER BY avg_cost_per_unit 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.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )
##Table Structure
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 )
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##Table Structure
CREATE TABLE social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
##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 )
##Table Structure
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
##Table Structure
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 )
##Table Structure
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)

[User] List every booking together with the route number and description for the trip being booked.

[Assistant]
SELECT b.booking_id, b.passenger_id, b.trip_id, r.route_number, r.description
FROM transportation.bookings b
JOIN transportation.routes r ON b.trip_id = r.route_id;

[User] How many agents were hired in the year 2023?

[Assistant] SELECT COUNT(*) AS agents_hired_2023 FROM insurance.agents WHERE hire_date BETWEEN '2023-01-01' AND '2023-12-31';

[User] Retrieve all unique chief complaints from medical_records.

[Assistant]
SELECT DISTINCT chief_complaint
FROM healthcare.medical_records;

[User] Now show chief complaints that occur more than 3 times along with their occurrence count.

[Assistant]
SELECT chief_complaint,
       COUNT(*) AS complaint_count
FROM healthcare.medical_records
GROUP BY chief_complaint
HAVING COUNT(*) > 3;

[User] I need a list of all group chat names with every username.

[Assistant]
SELECT u.username, c.group_name
FROM social_media.users u
JOIN social_media.conversations c ON 1=1
WHERE c.is_group_chat = true;

[User] Actually, only include users who are verified.

[Assistant]
SELECT u.username, c.group_name
FROM social_media.users u
JOIN social_media.conversations c ON 1=1
WHERE c.is_group_chat = true
  AND u.is_verified = true;

[User] List all pairs of clients who registered on the same day, showing each client's first_name, last_name, and the registration date.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, DATE(c1.date_registered) AS registration_date FROM legal_services.clients c1 JOIN legal_services.clients c2 ON DATE(c1.date_registered) = DATE(c2.date_registered) AND c1.client_id < c2.client_id;

[User] Calculate the total value of unspent UTXOs for each user whose KYC status has been 'approved'.

[Assistant] SELECT kyc.user_id, SUM(u.amount) FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status = 'approved' AND u.spent = false GROUP BY kyc.user_id;

[User] Refine that to only show users where this total value exceeds 1000.

[Assistant] SELECT kyc.user_id, SUM(u.amount) FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status = 'approved' AND u.spent = false GROUP BY kyc.user_id HAVING SUM(u.amount) > 1000;

[User] How many game sessions started on each calendar day?

[Assistant] SELECT DATE(start_time), COUNT(*) FROM gaming_technology.game_sessions GROUP BY DATE(start_time) ORDER BY DATE(start_time);

[User] Only display days that had more than 100 sessions.

[Assistant] SELECT DATE(start_time), COUNT(*) FROM gaming_technology.game_sessions GROUP BY DATE(start_time) HAVING COUNT(*) > 100 ORDER BY DATE(start_time);

[User] Find all service locations whose postal code starts with '75' and display their names, cities, and operating hours, including the agency ID.

[Assistant] SELECT location_name, city, operating_hours, agency_id FROM government_services.service_locations WHERE postal_code LIKE '75%';


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.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.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 )
##Table Structure
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, 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 )
##Table Structure
CREATE TABLE web3.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_id)
)
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
##Table Structure
CREATE TABLE web3.contracts ( contract_id text, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text )
##Table Structure
CREATE TABLE legal_services.time_entries ( entry_id.text, case_id.text, lawyer_id.text, date_worked.date, hours_spent.numeric, billing_rate.numeric, description.text, is_billable.boolean, is_billed.boolean, invoice_id.text, created_at.timestamp )
##Table Structure
CREATE TABLE web3.events ( event_id text, contract_id text, event_name text, data text, emitted_at timestamp, transaction_id text, log_index integer )
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )
CREATE TABLE web3.tokens ( token_id text, contract_address text, token_name text, token_symbol text, decimals integer, total_supply numeric )
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )

[User] Show the wallet address, token symbol, and the total value received by each wallet for each token. Only include wallets that have received tokens.

[Assistant]
SELECT w.address AS wallet_address, t.token_symbol, SUM(tt.value) AS total_received_value
FROM web3.wallets w
JOIN web3.token_transfers tt ON w.address = tt.to_address
JOIN web3.tokens t ON tt.token_id = t.token_id
GROUP BY w.address, t.token_symbol
ORDER BY w.address, t.token_symbol;

[User] Show me a list of all bus routes, including their route numbers, type, and the names of both the origin and destination locations.

[Assistant]
SELECT r.route_number, r.type, lo.name AS origin_name, ld.name AS destination_name
FROM transportation.routes r
JOIN transportation.locations lo ON r.origin_location_id = lo.location_id
JOIN transportation.locations ld ON r.destination_location_id = ld.location_id;

[User] List all premium payments with a due date in March 2024.

[Assistant] SELECT * FROM insurance.premium_payments WHERE due_date >= '2024-03-01' AND due_date <= '2024-03-31';

[User] Find the top 5 transactions with the highest gas prices, including the from_address, to_address, and block_number, sorted by gas_price in descending order.

[Assistant] SELECT transaction_id, from_address, to_address, block_number, gas_price FROM web3.transactions ORDER BY gas_price DESC LIMIT 5;

[User] Find pairs of guests living in the same city, returning each pair’s full names and the city.

[Assistant]
SELECT g1.first_name || ' ' || g1.last_name AS guest1,
       g2.first_name || ' ' || g2.last_name AS guest2,
       g1.city
FROM hospitality_technology.guests g1
JOIN hospitality_technology.guests g2
  ON g1.city = g2.city
 AND g1.guest_id < g2.guest_id;

[User] Show the total number of contracts grouped by their status.

[Assistant] SELECT status, COUNT(*) AS contract_count FROM web3.contracts GROUP BY status;

[User] Can you also filter to only include statuses with more than 10 contracts?

[Assistant] SELECT status, COUNT(*) AS contract_count FROM web3.contracts GROUP BY status HAVING COUNT(*) > 10;

[User] Find pairs of time entries for the same invoice where one entry is billed and the other is not.

[Assistant]
SELECT a.invoice_id,
       a.entry_id AS billed_entry,
       b.entry_id AS unbilled_entry
FROM legal_services.time_entries a
JOIN legal_services.time_entries b
  ON a.invoice_id = b.invoice_id
 AND a.entry_id <> b.entry_id
WHERE a.is_billed = TRUE
  AND b.is_billed = FALSE;

[User] Also show the number of days between the billed and unbilled entry dates.

[Assistant]
SELECT a.invoice_id,
       a.entry_id AS billed_entry,
       b.entry_id AS unbilled_entry,
       ABS(DATE_PART('day', a.date_worked - b.date_worked)) AS days_between
FROM legal_services.time_entries a
JOIN legal_services.time_entries b
  ON a.invoice_id = b.invoice_id
 AND a.entry_id <> b.entry_id
WHERE a.is_billed = TRUE
  AND b.is_billed = FALSE;

[User] List all token transfers showing the transfer id, the symbol of the transferred token, and the contract address where the token was created.

[Assistant]
SELECT tt.transfer_id, t.token_symbol, t.contract_address
FROM web3.token_transfers tt
JOIN web3.tokens t ON tt.token_id = t.token_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 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.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
##Table Structure
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE web3.transactions ( transaction_id text PRIMARY KEY, from_address text, to_address text, value numeric, gas_used int, gas_price numeric, block_number int, timestamp timestamp, input_data text, status text, nonce int )
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
##Table Structure
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )

[User] For each route, show the route number and the total number of trips associated with it.

[Assistant] SELECT T2.route_number, count(T1.trip_id) FROM transportation.trips AS T1 JOIN transportation.routes AS T2 ON T1.route_id = T2.route_id GROUP BY T2.route_number

[User] I want to list all insurance plans along with the number of medical records that have a record_date in 2024. Display plan_id, plan_name, and the total medical records.

[Assistant]
SELECT ip.plan_id, ip.plan_name, COUNT(mr.record_id) AS total_medical_records
FROM healthcare.insurance_plans ip
LEFT JOIN healthcare.medical_records mr ON 1=0 -- there is no direct relationship in schema, so no records will be counted
WHERE mr.record_date >= '2024-01-01' AND mr.record_date < '2025-01-01'
GROUP BY ip.plan_id, ip.plan_name;

[User] Since there's no direct relationship, can you adjust it to just show all insurance plans of type 'EPO' with their plan_id and plan_name?

[Assistant]
SELECT plan_id, plan_name
FROM healthcare.insurance_plans
WHERE plan_type = 'EPO';

[User] List all pairs of active services in the same category where one service’s standard fee is higher than the other’s. Display the category, the higher-fee service name with its fee, and the lower-fee service name with its fee.

[Assistant]
SELECT
  s1.category,
  s1.service_name AS higher_service,
  s1.standard_fee AS higher_fee,
  s2.service_name AS lower_service,
  s2.standard_fee AS lower_fee
FROM government_services.services s1
JOIN government_services.services s2
  ON s1.category = s2.category
  AND s1.standard_fee > s2.standard_fee
WHERE s1.is_active = TRUE
  AND s2.is_active = TRUE;

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

[Assistant]
SELECT user_id, action, logged_at
FROM trading_platform.logs
ORDER BY logged_at DESC;

[User] For each block, compute the total number of transactions and the average gas_price.

[Assistant] SELECT block_number, COUNT(*) AS total_txs, AVG(gas_price) AS avg_gas_price FROM web3.transactions GROUP BY block_number;

[User] Actually, only include blocks with more than 100 transactions.

[Assistant] SELECT block_number, COUNT(*) AS total_txs, AVG(gas_price) AS avg_gas_price FROM web3.transactions GROUP BY block_number HAVING COUNT(*) > 100;

[User] How many events were emitted on each date? List the date and the count of events.

[Assistant]
SELECT DATE(emitted_at) AS emit_date,
       COUNT(*) AS event_count
FROM web3.events
GROUP BY DATE(emitted_at);

[User] Actually, only include dates where more than 10 events were emitted.

[Assistant]
SELECT DATE(emitted_at) AS emit_date,
       COUNT(*) AS event_count
FROM web3.events
GROUP BY DATE(emitted_at)
HAVING COUNT(*) > 10;

[User] How many agents were hired in the current year and what is their average commission rate?

[Assistant] SELECT COUNT(*) AS hired_this_year, AVG(commission_rate) AS average_commission_rate FROM insurance.agents WHERE EXTRACT(YEAR FROM hire_date) = EXTRACT(YEAR FROM CURRENT_DATE);


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text PRIMARY KEY, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean )
##Table Structure
CREATE TABLE healthcare.prescriptions ( prescription_id text PRIMARY KEY, 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 int, prescription_date timestamp )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
##Table Structure
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
##Table Structure
CREATE TABLE web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
CREATE TABLE web3.transactions ( transaction_id text PRIMARY KEY, from_address text, to_address text, value numeric, gas_used int, gas_price numeric, block_number int, timestamp timestamp, input_data text, status text, nonce int )
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] Find all doctors who have a hospital affiliation and include their full names (concatenated), specialties, and affiliation IDs.

[Assistant] SELECT CONCAT(first_name, ' ', last_name) AS full_name, specialty, hospital_affiliation_id FROM healthcare.doctors WHERE hospital_affiliation_id IS NOT NULL;

[User] Count how many non-primary insurance policies have a group number specified.

[Assistant] SELECT COUNT(*) FROM healthcare.patient_insurance WHERE is_primary = FALSE AND group_number IS NOT NULL;

[User] List all events and any token transfers that occurred in the same transaction, showing event_id, event_name, transfer_id, and token_symbol.

[Assistant]
SELECT
  e.event_id,
  e.event_name,
  tt.transfer_id,
  tk.token_symbol
FROM web3.events e
LEFT JOIN web3.token_transfers tt
  ON e.transaction_id = tt.transaction_id
LEFT JOIN web3.tokens tk
  ON tt.token_id = tk.token_id
ORDER BY e.transaction_id, e.log_index;

[User] List all achievements with their name, points, and the title of the game they belong to.

[Assistant] SELECT a.name AS achievement_name, a.points, g.title AS game_title FROM gaming_technology.achievements a JOIN games g ON a.game_id = g.game_id;

[User] Filter this list to only show achievements with more than 50 points.

[Assistant] SELECT a.name AS achievement_name, a.points, g.title AS game_title FROM gaming_technology.achievements a JOIN games g ON a.game_id = g.game_id WHERE a.points > 50;

[User] List all distinct medication IDs that have been prescribed with more than 5 refills allowed.

[Assistant] SELECT DISTINCT medication_id FROM healthcare.prescriptions WHERE refills_allowed > 5;

[User] Find all users who have at least two wallets with different private keys. Show user_id and the count of distinct private keys for those users.

[Assistant]
SELECT user_id, COUNT(DISTINCT private_key) AS distinct_private_key_count
FROM web3.wallets
GROUP BY user_id
HAVING COUNT(DISTINCT private_key) >= 2;

[User] List the transaction IDs which have had more than one unique event emitted inside them.

[Assistant] SELECT transaction_id FROM web3.events GROUP BY transaction_id HAVING COUNT(DISTINCT event_name) > 1;

[User] Actually, can you also list the names of these unique events for each transaction ID?

[Assistant] SELECT transaction_id, STRING_AGG(DISTINCT event_name, ', ') AS unique_event_names FROM web3.events GROUP BY transaction_id HAVING COUNT(DISTINCT event_name) > 1;

[User] Count how many diagnoses entries are currently marked as 'Resolved'.

[Assistant] SELECT COUNT(*) FROM healthcare.diagnoses WHERE status = 'Resolved';

[User] Show me all contracts deployed on the 'ethereum' network along with their deployer addresses and the count of transactions they've been involved in, sorted by transaction count in descending order.

[Assistant] SELECT c.address, c.deployer_address, COUNT(t.transaction_id) AS transaction_count FROM web3.contracts c LEFT JOIN web3.transactions t ON c.address = t.to_address WHERE c.network_id = 'ethereum' GROUP BY c.address, c.deployer_address ORDER BY transaction_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 gaming_technology.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
##Table Structure
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
##Table Structure
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
##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 )
##Table Structure
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )

[User] For each game, which server has hosted the most sessions?

[Assistant] SELECT game_id, server_id, COUNT(*) AS session_count FROM gaming_technology.game_sessions GROUP BY game_id, server_id;

[User] I want the server with the highest session count per game, not all servers.

[Assistant] SELECT t.game_id, t.server_id, t.session_count FROM (SELECT game_id, server_id, COUNT(*) AS session_count, RANK() OVER (PARTITION BY game_id ORDER BY COUNT(*) DESC) AS rnk FROM gaming_technology.game_sessions GROUP BY game_id, server_id) t WHERE t.rnk = 1;

[User] If two servers have the same highest count for a game, will both be shown?

[Assistant] Yes, the RANK() function ensures all servers tied for the highest session count per game are shown. The SQL will return all such tied servers for each game where they share the top session count.

[User] Can you also show the total duration of all sessions for the top server(s) per game?

[Assistant] WITH top_servers AS (SELECT game_id, server_id, COUNT(*) AS session_count, RANK() OVER (PARTITION BY game_id ORDER BY COUNT(*) DESC) AS rnk FROM gaming_technology.game_sessions GROUP BY game_id, server_id) SELECT ts.game_id, ts.server_id, ts.session_count, SUM(gs.duration_seconds) AS total_duration FROM top_servers ts JOIN gaming_technology.game_sessions gs ON ts.game_id = gs.game_id AND ts.server_id = gs.server_id WHERE ts.rnk = 1 GROUP BY ts.game_id, ts.server_id, ts.session_count;

[User] Provide a count of contracts for each unique combination of network ID and status.

[Assistant] SELECT network_id, status, COUNT(*) FROM web3.contracts GROUP BY network_id, status;

[User] Now, only show the network IDs from the previous result that have contracts in more than one distinct status.

[Assistant] SELECT network_id FROM web3.contracts GROUP BY network_id HAVING COUNT(DISTINCT status) > 1;

[User] For each vehicle, list the vehicle_id and the total number of trips it has performed.

[Assistant] SELECT vehicle_id, COUNT(*) AS trip_count FROM transportation.trips GROUP BY vehicle_id;

[User] Can you limit this to only vehicles that have more than 10 trips?

[Assistant] SELECT vehicle_id, COUNT(*) AS trip_count FROM transportation.trips GROUP BY vehicle_id HAVING COUNT(*) > 10;

[User] In addition, for these vehicles, can you show the driver_id who has driven the highest number of trips for each vehicle?

[Assistant] SELECT vehicle_id, driver_id, trip_driver_count FROM (SELECT vehicle_id, driver_id, COUNT(*) AS trip_driver_count, ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY COUNT(*) DESC) as rn FROM transportation.trips GROUP BY vehicle_id, driver_id) t WHERE rn = 1 AND vehicle_id IN (SELECT vehicle_id FROM transportation.trips GROUP BY vehicle_id HAVING COUNT(*) > 10);

[User] Find patients who had more than one appointment on the same day. Show patient ID and the date of the appointments.

[Assistant] SELECT patient_id, DATE(appointment_time) AS appointment_date FROM healthcare.appointments GROUP BY patient_id, DATE(appointment_time) HAVING COUNT(*) > 1;

[User] Also include the total number of appointments on that day for that patient.

[Assistant] SELECT patient_id, DATE(appointment_time) AS appointment_date, COUNT(*) AS daily_appointment_count FROM healthcare.appointments GROUP BY patient_id, DATE(appointment_time) HAVING COUNT(*) > 1;

[User] Show all active agents along with their respective managers' full names.

[Assistant] SELECT a.agent_id, a.first_name || ' ' || a.last_name AS agent_name, m.first_name || ' ' || m.last_name AS manager_name FROM insurance.agents a LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id WHERE a.status = 'Active';

[User] Can you show me the email addresses of all drivers whose status is 'Inactive'?

[Assistant] SELECT driver_id, first_name, last_name, email FROM transportation.drivers WHERE status = 'Inactive';

[User] I see there are some missing emails. Only include drivers who actually have an email address.

[Assistant] SELECT driver_id, first_name, last_name, email FROM transportation.drivers WHERE status = 'Inactive' AND email IS NOT NULL AND email <> '';

[User] Also add their hire date to the results and order by hire date ascending.

[Assistant] SELECT driver_id, first_name, last_name, email, hire_date FROM transportation.drivers WHERE status = 'Inactive' AND email IS NOT NULL AND email <> '' ORDER BY hire_date ASC;

[User] Show each order with its previous order timestamp for the same user.

[Assistant]
SELECT o.order_id, o.user_id, o.created_at AS current_time, MAX(prev.created_at) AS previous_time
FROM trading_platform.orders o
LEFT JOIN trading_platform.orders prev
  ON o.user_id = prev.user_id
  AND prev.created_at < o.created_at
GROUP BY o.order_id, o.user_id, o.created_at
ORDER BY o.user_id, o.created_at;

[User] Filter to include only those orders where the gap between current_time and previous_time exceeds one day.

[Assistant]
SELECT *
FROM (
  SELECT o.order_id,
         o.user_id,
         o.created_at AS current_time,
         MAX(prev.created_at) AS previous_time
  FROM trading_platform.orders o
  LEFT JOIN trading_platform.orders prev
    ON o.user_id = prev.user_id
    AND prev.created_at < o.created_at
  GROUP BY o.order_id, o.user_id, o.created_at
) t
WHERE t.current_time - t.previous_time > INTERVAL '1 day'
ORDER BY t.user_id, t.current_time;