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 character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
##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.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 social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.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 )
##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 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 )
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )
##Table Structure
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 )

[User] List all services with an average processing time greater than the overall average processing time for all services. Show the service name, average processing time, and the overall average processing time.

[Assistant] SELECT service_name, average_processing_time_days, (SELECT AVG(average_processing_time_days) FROM government_services.services WHERE average_processing_time_days IS NOT NULL) as overall_avg_processing_time FROM government_services.services WHERE average_processing_time_days IS NOT NULL AND average_processing_time_days > (SELECT AVG(average_processing_time_days) FROM government_services.services WHERE average_processing_time_days IS NOT NULL);

[User] Find all pairs of events that occurred in the same transaction but at different log indices, showing both event_ids, their event_names, the transaction_id, and each log_index.

[Assistant]
SELECT a.event_id AS event_id1,
       a.event_name AS event_name1,
       b.event_id AS event_id2,
       b.event_name AS event_name2,
       a.transaction_id,
       a.log_index AS log_index1,
       b.log_index AS log_index2
FROM web3.events a
JOIN web3.events b
  ON a.transaction_id = b.transaction_id
 AND a.log_index < b.log_index;

[User] Show me all game sessions that do not have a score recorded. List the session_id, player_id, game_id, and start_time.

[Assistant] SELECT session_id, player_id, game_id, start_time FROM gaming_technology.game_sessions WHERE score IS NULL;

[User] For each game, how many of its sessions have a missing score? Show game_id and the count.

[Assistant] SELECT game_id, COUNT(session_id) AS sessions_with_no_score FROM gaming_technology.game_sessions WHERE score IS NULL GROUP BY game_id;

[User] Which posts have been mentioned with at least one hashtag and also have users who joined the conversation corresponding to the post? Please show the post_id and the user_id of participants.

[Assistant]
SELECT ph.post_id, cp.user_id
FROM social_media.post_hashtags ph
INNER JOIN social_media.conversation_participants cp
  ON ph.post_id = cp.conversation_id;

[User] Can you also include the joined_at time for each user in the result?

[Assistant]
SELECT ph.post_id, cp.user_id, cp.joined_at
FROM social_media.post_hashtags ph
INNER JOIN social_media.conversation_participants cp
  ON ph.post_id = cp.conversation_id;

[User] Find all applications whose last update occurred on a weekend. Show application_id, citizen full name, last_updated_at, and status.

[Assistant]
SELECT
a.application_id,
(c.first_name || ' ' || c.last_name) AS full_name,
a.last_updated_at,
a.status
FROM government_services.applications a
JOIN government_services.citizens c
  ON a.citizen_id = c.citizen_id
WHERE EXTRACT(DOW FROM a.last_updated_at) IN (0, 6);

[User] Find the deployer address that has deployed the highest number of contracts and report the address and the total count of contracts for that deployer.

[Assistant] SELECT deployer_address, COUNT(*) AS contract_count FROM web3.contracts GROUP BY deployer_address ORDER BY contract_count DESC LIMIT 1;

[User] List all failed payments with their details.

[Assistant] SELECT payment_id, application_id, citizen_id, service_id, amount, currency, payment_method, payment_provider_reference, payment_timestamp, status, notes FROM government_services.payments WHERE status = 'Failed';

[User] Show me all documents uploaded in 2024 that do not have a description.

[Assistant]
SELECT document_id, file_name, uploaded_at
FROM insurance.claim_documents
WHERE uploaded_at >= '2024-01-01'
  AND uploaded_at < '2025-01-01'
  AND (description IS NULL OR description = '');

[User] For each claim, retrieve the earliest uploaded document and the latest uploaded document filenames. Return claim_id, earliest_file_name, latest_file_name.

[Assistant]
SELECT e.claim_id,
       e.file_name AS earliest_file_name,
       l.file_name AS latest_file_name
FROM insurance.claim_documents e
JOIN insurance.claim_documents l
  ON e.claim_id = l.claim_id
WHERE e.uploaded_at = (
        SELECT MIN(uploaded_at)
        FROM insurance.claim_documents
        WHERE claim_id = e.claim_id
      )
  AND l.uploaded_at = (
        SELECT MAX(uploaded_at)
        FROM insurance.claim_documents
        WHERE claim_id = l.claim_id
      );

[User] How many employees have a manager assigned to them?

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )
##Table Structure
CREATE TABLE blockchain.transactions ( transaction_id.text, block_id.text, sender_address.text, receiver_address.text, amount.numeric, timestamp.timestamp, signature.text )
CREATE TABLE blockchain.addresses ( address_id.text, public_key.text, balance.numeric )
CREATE TABLE blockchain.nodes (
    node_id character varying(64) NOT NULL,  -- unique identifier for the node
    ip_address character varying(15) NOT NULL, -- IP address of the node
    port integer NOT NULL, -- port number of the node
    last_seen timestamp NOT NULL, -- last time the node was active
    PRIMARY KEY (node_id)
)
##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 smart_money_token_performance ( token_address character varying(100) NOT NULL, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
##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 blockchain.transactions ( transaction_id text, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.addresses ( address_id text, public_key text, balance numeric )
CREATE TABLE blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )
CREATE TABLE blockchain.users ( user_id text, username text, email text, password_hash 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 )

[User] Find all addresses that have both sent and received tokens. For each, show the address, the total value sent, and the total value received.

[Assistant]
SELECT s.address, s.total_sent, r.total_received
FROM (
  SELECT from_address AS address, SUM(value) AS total_sent
  FROM web3.token_transfers
  GROUP BY from_address
) s
JOIN (
  SELECT to_address   AS address, SUM(value) AS total_received
  FROM web3.token_transfers
  GROUP BY to_address
) r
  ON s.address = r.address;

[User] Show me all rooms along with their current overall review rating for each room, including the room number and property id.

[Assistant]
SELECT r.room_number, r.property_id, AVG(rv.rating_overall) AS average_overall_rating
FROM hospitality_technology.rooms r
LEFT JOIN hospitality_technology.reviews rv
  ON r.property_id = rv.property_id
GROUP BY r.room_number, r.property_id;

[User] Show me each transaction ID along with the sender's public key, the receiver's balance, and the transaction amount.

[Assistant]
SELECT t.transaction_id, a_sender.public_key AS sender_public_key, a_receiver.balance AS receiver_balance, t.amount
FROM blockchain.transactions t
JOIN blockchain.addresses a_sender ON t.sender_address = a_sender.address_id
JOIN blockchain.addresses a_receiver ON t.receiver_address = a_receiver.address_id;

[User] For each transaction, show the transaction id and the total number of unique addresses involved in token transfers for that transaction (both as sender and receiver).

[Assistant]
SELECT transaction_id, COUNT(DISTINCT addr) AS unique_address_count
FROM (
    SELECT transaction_id, from_address AS addr FROM web3.token_transfers
    UNION ALL
    SELECT transaction_id, to_address AS addr FROM web3.token_transfers
) a
GROUP BY transaction_id;

[User] Show the tokens with a negative net flow this month on all chains.

[Assistant] SELECT token_symbol, chain, net_flow FROM smart_money_token_performance WHERE net_flow < 0 AND date_trunc('month', CURRENT_DATE) = date_trunc('month', now());

[User] Order them by net flow ascending and only show the bottom 5.

[Assistant] SELECT token_symbol, chain, net_flow FROM smart_money_token_performance WHERE net_flow < 0 AND date_trunc('month', CURRENT_DATE) = date_trunc('month', now()) ORDER BY net_flow ASC LIMIT 5;

[User] List all partners who were hired in the same year. Show their first name, last name, hire year, and firm ID.

[Assistant] SELECT l1.first_name, l1.last_name, EXTRACT(YEAR FROM l1.hire_date) AS hire_year, l1.firm_id FROM legal_services.lawyers AS l1 JOIN legal_services.lawyers AS l2 ON EXTRACT(YEAR FROM l1.hire_date) = EXTRACT(YEAR FROM l2.hire_date) AND l1.lawyer_id != l2.lawyer_id WHERE l1.is_partner = TRUE AND l2.is_partner = TRUE GROUP BY l1.lawyer_id, hire_year, l1.firm_id ORDER BY hire_year, l1.last_name;

[User] How many contracts are deployed each month for each status?

[Assistant]
SELECT TO_CHAR(deployed_at, 'YYYY-MM') AS deploy_month,
       status,
       COUNT(*) AS contract_count
FROM web3.contracts
GROUP BY TO_CHAR(deployed_at, 'YYYY-MM'), status
ORDER BY deploy_month, status;

[User] Actually, I only want to see yearly totals instead of monthly.

[Assistant]
SELECT EXTRACT(YEAR FROM deployed_at) AS deploy_year,
       status,
       COUNT(*) AS contract_count
FROM web3.contracts
GROUP BY EXTRACT(YEAR FROM deployed_at), status
ORDER BY deploy_year, status;

[User] Show me each transaction with its ID, amount, timestamp, and the usernames of both sender and receiver.

[Assistant]
SELECT t.transaction_id, t.amount, t.timestamp, us.username AS sender_username, ur.username AS receiver_username
FROM blockchain.transactions t
LEFT JOIN blockchain.wallets ws ON t.sender_address = ws.address_id
LEFT JOIN blockchain.users us ON ws.user_id = us.user_id
LEFT JOIN blockchain.wallets wr ON t.receiver_address = wr.address_id
LEFT JOIN blockchain.users ur ON wr.user_id = ur.user_id;

[User] List the application ID and citizen ID for all documents of type 'Proof of Address'.

[Assistant] SELECT application_id, citizen_id FROM government_services.documents WHERE document_type = 'Proof of Address';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
##Table Structure
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.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 PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )
##Table Structure
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
##Table Structure
CREATE TABLE web3.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )

[User] How many addresses on the Ethereum chain have an ROI between 2 and 4?

[Assistant] SELECT COUNT(*) AS address_count FROM smart_money_profit WHERE chain = 'Ethereum' AND roi >= 2 AND roi <= 4;

[User] Could you also show their average profit?

[Assistant] SELECT AVG(profit) AS avg_profit FROM smart_money_profit WHERE chain = 'Ethereum' AND roi >= 2 AND roi <= 4;

[User] For each event recorded, list its ID, name, and the status and value of the transaction in which it occurred.

[Assistant] SELECT E.event_id, E.event_name, E.transaction_id, T.status, T.value FROM web3.events AS E JOIN web3.transactions AS T ON E.transaction_id = T.transaction_id;

[User] List all pairs of lawyers from the same firm who were hired in the same month and year. Include each lawyer's first_name, last_name, firm_id, and the shared hire_month_year.

[Assistant]
SELECT a.first_name AS lawyer1_first_name,
       a.last_name  AS lawyer1_last_name,
       b.first_name AS lawyer2_first_name,
       b.last_name  AS lawyer2_last_name,
       a.firm_id,
       TO_CHAR(a.hire_date, 'YYYY-MM') AS hire_month_year
FROM legal_services.lawyers a
JOIN legal_services.lawyers b
  ON a.firm_id = b.firm_id
 AND TO_CHAR(a.hire_date, 'YYYY-MM') = TO_CHAR(b.hire_date, 'YYYY-MM')
 AND a.lawyer_id < b.lawyer_id;

[User] Which law firms were founded in the same year and share the same managing partner? Show the firm names, founding year, and managing partner ID.

[Assistant]
SELECT f1.firm_name AS firm_name_1, f2.firm_name AS firm_name_2, EXTRACT(YEAR FROM f1.founded_date) AS founding_year, f1.managing_partner_id
FROM legal_services.law_firms f1
JOIN legal_services.law_firms f2
  ON f1.firm_id <> f2.firm_id
  AND EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date)
  AND f1.managing_partner_id = f2.managing_partner_id
ORDER BY founding_year, f1.firm_name, f2.firm_name;

[User] List all rooms that have a 'Jacuzzi' feature, including the room_number, property_id, type_name, and base_rate.

[Assistant]
SELECT r.room_number,
       r.property_id,
       rt.type_name,
       rt.base_rate
FROM hospitality_technology.rooms AS r
JOIN hospitality_technology.room_types AS rt
  ON r.room_type_id = rt.room_type_id
 AND r.property_id = rt.property_id
WHERE r.features ILIKE '%Jacuzzi%';

[User] Calculate the average and maximum payment amount grouped by payment status.

[Assistant]
SELECT status,
       AVG(amount_paid) AS avg_amount,
       MAX(amount_paid) AS max_amount
FROM insurance.premium_payments
GROUP BY status;

[User] How many users registered on each date?

[Assistant] SELECT DATE(created_at) AS registration_date, COUNT(*) AS user_count FROM web3.users GROUP BY DATE(created_at) ORDER BY registration_date;

[User] Actually, I only want to see dates with more than 5 registrations.

[Assistant] SELECT DATE(created_at) AS registration_date, COUNT(*) AS user_count FROM web3.users GROUP BY DATE(created_at) HAVING COUNT(*) > 5 ORDER BY registration_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 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.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.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE government_services.agencies (
    agency_id character varying(64) NOT NULL, -- unique identifier for the agency
    agency_name character varying(255) NOT NULL, -- full name of the government agency
    jurisdiction_level character varying(50) NOT NULL, -- e.g., Federal, State, County, City
    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), -- FK to self for hierarchical structure
    PRIMARY KEY (agency_id)
)
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
##Table Structure
CREATE TABLE web3.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
##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) )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.trades ( trade_id.text, order_id.text, buyer_id.text, seller_id.text, asset_id.text, quantity.numeric, price.numeric, traded_at.timestamp )
CREATE TABLE trading_platform.assets ( asset_id.text, name.text, symbol.text, type.text )
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.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id.text, asset_id.text, key.text, value.text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id uuid, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )

[User] For each contract that has received transactions, list its address and the total value of Ether received.

[Assistant] SELECT T1.address, SUM(T2.value) FROM web3.contracts AS T1 JOIN web3.transactions AS T2 ON T1.address = T2.to_address GROUP BY T1.address;

[User] Show me a list of all agencies and the number of distinct citizens who have submitted documents to each agency.

[Assistant]
SELECT a.agency_name, COUNT(DISTINCT d.citizen_id) AS citizen_count
FROM government_services.documents d
JOIN government_services.applications app ON d.application_id = app.application_id
JOIN government_services.services s ON app.service_id = s.service_id
JOIN government_services.agencies a ON s.agency_id = a.agency_id
GROUP BY a.agency_name;

[User] How many users registered in each month?

[Assistant]
SELECT date_trunc('month', created_at) AS month,
       COUNT(*) AS registrations
FROM web3.users
GROUP BY month
ORDER BY month;

[User] Actually, show only those months where registrations exceed 10.

[Assistant]
SELECT date_trunc('month', created_at) AS month,
       COUNT(*) AS registrations
FROM web3.users
GROUP BY month
HAVING COUNT(*) > 10
ORDER BY month;

[User] For each employee who has verified more than one document, list their employee ID, the first document they verified, and the next document they verified, along with both verification timestamps.

[Assistant]
SELECT
  d1.verified_by_employee_id AS employee_id,
  d1.document_id AS first_verified_document,
  d1.verification_timestamp AS first_verification_time,
  d2.document_id AS next_verified_document,
  d2.verification_timestamp AS next_verification_time
FROM government_services.documents d1
JOIN government_services.documents d2
  ON d1.verified_by_employee_id = d2.verified_by_employee_id
  AND d2.verification_timestamp > d1.verification_timestamp
WHERE d1.verification_status = 'Verified'
  AND d2.verification_status = 'Verified';

[User] Find the address that has the highest total amount across all its UTXOs.

[Assistant] SELECT address FROM utxos GROUP BY address ORDER BY SUM(amount) DESC LIMIT 1;

[User] For each driver, find the other driver whose license_expiry_date is the next one after theirs. Show both IDs, names and their expiry dates.

[Assistant]
SELECT
  d1.driver_id            AS driver_id,
  d1.first_name || ' ' || d1.last_name     AS driver_name,
  d1.license_expiry_date  AS expiry_date,
  d2.driver_id            AS next_driver_id,
  d2.first_name || ' ' || d2.last_name     AS next_driver_name,
  d2.license_expiry_date  AS next_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date = (
    SELECT MIN(d3.license_expiry_date)
    FROM transportation.drivers d3
    WHERE d3.license_expiry_date > d1.license_expiry_date
  );

[User] How can I calculate how many years each developer has been in business based on their founded_year?

[Assistant]
SELECT name,
       EXTRACT(year FROM age(CURRENT_DATE, make_date(founded_year, 1, 1))) AS years_in_business
FROM gaming_technology.developers;

[User] Actually, I'd like to include only developers founded before 2000 and order the result by years_in_business descending.

[Assistant]
SELECT name,
       EXTRACT(year FROM age(CURRENT_DATE, make_date(founded_year, 1, 1))) AS years_in_business
FROM gaming_technology.developers
WHERE founded_year < 2000
ORDER BY years_in_business 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 insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )
##Table Structure
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
##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 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.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 )
##Table Structure
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
##Table Structure
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 )
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id.uuid, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, session_data.jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
CREATE TABLE gaming_technology.in_game_items ( item_id.uuid, game_id.uuid, item_name.text, item_type.text, description.text, rarity.text, cost_currency.text, cost_amount.numeric, attributes.jsonb )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )
##Table Structure
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) )
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )

[User] Find the claim ID and the total number of documents associated with each claim ID that has more than 10 documents.

[Assistant] SELECT claim_id, COUNT(*) FROM insurance.claim_documents GROUP BY claim_id HAVING COUNT(*) > 10;

[User] Find the total quantity dispensed and the number of refills allowed for each dosage type.

[Assistant] SELECT dosage, SUM(quantity_dispensed) AS total_quantity_dispensed, SUM(refills_allowed) AS total_refills_allowed FROM healthcare.prescriptions GROUP BY dosage;

[User] List the claim_id and the total number of documents uploaded for each claim, but only include claims with between 3 and 7 documents.

[Assistant] SELECT claim_id, COUNT(*) AS document_count FROM insurance.claim_documents GROUP BY claim_id HAVING COUNT(*) BETWEEN 3 AND 7;

[User] Can you also show the upload time of the most recent document for each claim in this list?

[Assistant] SELECT cd.claim_id, COUNT(*) AS document_count, MAX(cd.uploaded_at) AS latest_uploaded_at FROM insurance.claim_documents cd GROUP BY cd.claim_id HAVING COUNT(*) BETWEEN 3 AND 7;

[User] List the contract ID, address, and deployer address for all contracts deployed on the 'mainnet' network.

[Assistant] SELECT contract_id, address, deployer_address FROM web3.contracts WHERE network_id = 'mainnet';

[User] Find all pairs of routes where one starts where the other ends and vice versa. List their route numbers, origin and destination IDs for each.

[Assistant]
SELECT r1.route_number AS route_number_1, r1.origin_location_id AS origin_1, r1.destination_location_id AS destination_1,
       r2.route_number AS route_number_2, r2.origin_location_id AS origin_2, r2.destination_location_id AS destination_2
FROM transportation.routes r1
JOIN transportation.routes r2
  ON r1.origin_location_id = r2.destination_location_id
  AND r1.destination_location_id = r2.origin_location_id
  AND r1.route_id < r2.route_id;

[User] List the first name, last name, email, and the name of the law firm for all lawyers.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T1.email ,  T2.firm_name FROM legal_services.lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id  =  T2.firm_id

[User] Show me pairs of patients who have had a medical record created on the same day. For each pair, include the first patient's ID, the second patient's ID, the shared record_date, and their respective record_ids.

[Assistant]
SELECT a.patient_id AS patient1_id, b.patient_id AS patient2_id, a.record_date::date AS shared_record_date, a.record_id AS record1_id, b.record_id AS record2_id
FROM healthcare.medical_records a
JOIN healthcare.medical_records b ON a.record_date::date = b.record_date::date AND a.patient_id < b.patient_id;

[User] List the names of servers and their regions, and the names of achievements available in the games hosted on those servers.

[Assistant] SELECT s.server_name, s.region, a.name AS achievement_name FROM gaming_technology.servers AS s JOIN gaming_technology.achievements AS a ON s.game_id = a.game_id;

[User] Find the top 5 transactions with the highest gas prices that were successful, including the from_address, to_address, and block_number.

[Assistant] SELECT from_address, to_address, block_number, gas_price FROM web3.transactions WHERE status = 'success' ORDER BY gas_price DESC LIMIT 5;

[User] List the first and last names of all doctors whose email address ends with '@hospital.org'.

[Assistant] SELECT first_name, last_name FROM healthcare.doctors WHERE email LIKE '%@hospital.org';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.users ( user_id 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.comments ( comment_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, parent_comment_id character varying(64), content text NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (comment_id) )
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
CREATE TABLE social_media.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) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address.text, token_name.text, token_symbol.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_6h.numeric, price_change_percentage_24h.numeric, makers_24h.numeric, volume_24h.numeric, liquidity.numeric, market_cap.numeric, trend_rank.numeric )
##Table Structure
CREATE TABLE blockchain.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, PRIMARY KEY (user_id) )
##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 hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
##Table Structure
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Find all users who have set their bio to a non-empty value, showing their username and email.

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

[User] List all tokens on the BSC chain with a price below $1.

[Assistant] SELECT token_symbol, token_name, price FROM token_dexpool_info WHERE chain = 'BSC' AND price < 1;

[User] Only show tokens where the 24-hour trading volume is above $200,000 and order the results by price ascending.

[Assistant] SELECT token_symbol, token_name, price FROM token_dexpool_info WHERE chain = 'BSC' AND price < 1 AND volume_24h > 200000 ORDER BY price ASC;

[User] Find all email addresses that are used by more than one user, and list the email address along with the count of users sharing it.

[Assistant] SELECT email, COUNT(user_id) FROM blockchain.users GROUP BY email HAVING COUNT(user_id) > 1;

[User] Retrieve each game_id alongside the achievement with the highest points, showing its name and points.

[Assistant]
SELECT a.game_id,
       a.name,
       a.points
FROM achievements a
JOIN (
  SELECT game_id,
         MAX(points) AS max_points
  FROM achievements
  GROUP BY game_id
) m ON a.game_id = m.game_id
   AND a.points = m.max_points;

[User] Exclude hidden achievements and only include games where that top achievement has at least 80 points.

[Assistant]
SELECT a.game_id,
       a.name,
       a.points
FROM achievements a
JOIN (
  SELECT game_id,
         MAX(points) AS max_points
  FROM achievements
  WHERE hidden = false
  GROUP BY game_id
) m ON a.game_id = m.game_id
   AND a.points = m.max_points
WHERE a.hidden = false
  AND a.points >= 80
ORDER BY a.points DESC;

[User] Could you provide a count of services available within each department?

[Assistant] SELECT department, COUNT(*) FROM hospitality_technology.services GROUP BY department;

[User] Now, only list the departments that have more than 5 available services and sort them by the service count in descending order.

[Assistant] SELECT department, COUNT(*) FROM hospitality_technology.services WHERE is_available = TRUE GROUP BY department HAVING COUNT(*) > 5 ORDER BY COUNT(*) DESC;

[User] List all plan names and their contact numbers for plans of type 'HMO' offered by 'Sunrise Insurance'.

[Assistant] SELECT plan_name, contact_phone FROM healthcare.insurance_plans WHERE plan_type = 'HMO' AND insurance_provider = 'Sunrise Insurance';

[User] Find all pairs of lawyers who work for the same firm, showing each lawyer's first_name, last_name, email, and firm_id.

[Assistant]
SELECT l1.first_name AS lawyer1_first_name,
       l1.last_name AS lawyer1_last_name,
       l1.email AS lawyer1_email,
       l2.first_name AS lawyer2_first_name,
       l2.last_name AS lawyer2_last_name,
       l2.email AS lawyer2_email,
       l1.firm_id
FROM legal_services.lawyers l1
JOIN legal_services.lawyers l2
  ON l1.firm_id = l2.firm_id
  AND l1.lawyer_id < l2.lawyer_id;

[User] Show the document type, verification status, and the full name of the citizen who uploaded each document.

[Assistant] SELECT d.document_type, d.verification_status, CONCAT(c.first_name, ' ', c.last_name) AS citizen_full_name FROM government_services.documents d JOIN government_services.citizens c ON d.citizen_id = c.citizen_id;

[User] List all beneficiaries who do not have any contact information provided. Show beneficiary_id, first_name, and last_name.

[Assistant] SELECT beneficiary_id, first_name, last_name FROM insurance.policy_beneficiaries WHERE contact_info IS NULL OR contact_info = ''


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
// Use Hashes for platform details. Key format: platform:<platform_id>
// HSET platform:plat_123 platform_id "plat_123" station_id "station_xyz" platform_number "1A" track_number "T1" status "Operational" length_meters 250.50 accessible 1

// To link platforms to stations (optional):
// SADD station:station_xyz:platforms platform:plat_123 platform:plat_456
// Use Hashes for train details. Key format: train:<train_id>
// HSET train:train_789 train_id "train_789" train_number "Acela 2151" model "Siemens Velaro" ... status "Active" ...

// To find train by train_number (optional index):
// SET train_number:"Acela 2151" train:train_789
// Use Hashes for car details. Key format: car:<car_id>
// HSET car:car_abc car_id "car_abc" train_id "train_789" car_number "C3" car_type "Passenger" class "Business" capacity 60 features "WiFi,Power Outlet"

// To link cars to trains (optional):
// SADD train:train_789:cars car:car_abc car:car_def
// Use Hashes for details. Key format: route_station:<route_station_id>
// HSET route_station:rs_ne_1 route_station_id "rs_ne_1" route_id "route_ne_corr" station_id "station_bos" sequence_order 1 ...

// To find stops for a route, use a Sorted Set (score by sequence_order):
// ZADD route:route_ne_corr:stops 1 route_station:rs_ne_1
// ZADD route:route_ne_corr:stops 2 route_station:rs_ne_2
// Use Hashes for schedule details. Key format: schedule:<schedule_id>
// HSET schedule:sched_1122 schedule_id "sched_1122" train_id "train_789" route_id "route_ne_corr" departure_datetime "2024-05-10T08:00:00-04:00" ... status "Scheduled"
// Use Hashes for details. Key format: schedule_stop:<stop_id>
// HSET schedule_stop:stop_sched1122_1 stop_id "stop_sched1122_1" schedule_id "sched_1122" station_id "station_bos" ...

// To find stops for a schedule, use a Sorted Set (score by sequence_order):
// ZADD schedule:sched_1122:stops 1 schedule_stop:stop_sched1122_1
// ZADD schedule:sched_1122:stops 2 schedule_stop:stop_sched1122_2
// Use Hashes for passenger details. Key format: passenger:<passenger_id>
// HSET passenger:pass_pqr passenger_id "pass_pqr" first_name "Alice" last_name "Smith" email "alice.smith@example.com" ...

// To find passenger by email (optional index):
// SET passenger_email:"alice.smith@example.com" passenger:pass_pqr
// Use Hashes for booking details. Key format: booking:<booking_id>
// HSET booking:book_zyx booking_id "book_zyx" passenger_id "pass_pqr" schedule_id "sched_1122" ... status "Confirmed" ...

// To link bookings to passengers/schedules (optional):
// SADD passenger:pass_pqr:bookings booking:book_zyx
// SADD schedule:sched_1122:bookings booking:book_zyx
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...

// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b
// Use Hashes for staff details. Key format: staff:<staff_id>
// HSET staff:staff_mno staff_id "staff_mno" first_name "Bob" ... employee_number "E12345" ... is_active 1

// To find staff by employee number (optional index):
// SET staff_employee_number:"E12345" staff:staff_mno
// Use Hashes for maintenance record details. Key format: maintenance_record:<record_id>
// HSET maintenance_record:maint_rec_001 record_id "maint_rec_001" asset_id "train_789" asset_type "Train" ... status "Completed"

// To link records to assets (optional):
// SADD train:train_789:maintenance maintenance_record:maint_rec_001
// SADD platform:plat_123:maintenance maintenance_record:maint_rec_002
##Table Structure
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )
##Table Structure
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )

[User] Can you provide the total number of cars associated with a specific train with train_id 'train_789'?

[Assistant] SCARD train:train_789:cars

[User] Report the number of employees for each department, broken down by their employment status.

[Assistant] SELECT department, status, COUNT(*) AS employee_count FROM financial_services.employees GROUP BY department, status

[User] List all staff members along with their direct manager's first and last names.

[Assistant]
SELECT s.staff_id,
       s.first_name AS staff_first_name,
       s.last_name AS staff_last_name,
       m.first_name AS manager_first_name,
       m.last_name AS manager_last_name
FROM hospitality_technology.staff s
LEFT JOIN hospitality_technology.staff m
  ON s.manager_id = m.staff_id;

[User] Could you retrieve pairs of accessible service locations in the same city but with different postal codes?

[Assistant]
SELECT sl1.location_id AS location1_id,
       sl2.location_id AS location2_id,
       sl1.city
FROM government_services.service_locations sl1
JOIN government_services.service_locations sl2
  ON sl1.city = sl2.city
 AND sl1.location_id < sl2.location_id
WHERE sl1.is_accessible = TRUE
  AND sl2.is_accessible = TRUE;

[User] Now restrict these pairs to those in the state of 'California'.

[Assistant]
SELECT sl1.location_id AS location1_id,
       sl2.location_id AS location2_id,
       sl1.city
FROM government_services.service_locations sl1
JOIN government_services.service_locations sl2
  ON sl1.city = sl2.city
 AND sl1.location_id < sl2.location_id
WHERE sl1.is_accessible = TRUE
  AND sl2.is_accessible = TRUE
  AND sl1.state = 'California'
  AND sl2.state = 'California';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
##Table Structure
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
##Table Structure
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
##Table Structure
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
##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) )
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
##Table Structure
Use Hashes. Key pattern: 'component:<component_id>'. Example: HSET component:LGSTRUT01 part_number "PN-5521-A" component_name "Landing Gear Strut" material_id "mat:TI64" supplier_id "sup:ACME_AERO" ... Consider Sets for reverse lookups (e.g., 'material_components:<material_id>' -> Set<component_id>).
##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] Could you list each game_id along with the count of hidden achievements and the count of visible achievements?

[Assistant]
SELECT game_id,
       SUM(CASE WHEN hidden THEN 1 ELSE 0 END) AS hidden_count,
       SUM(CASE WHEN NOT hidden THEN 1 ELSE 0 END) AS visible_count
FROM gaming_technology.achievements
GROUP BY game_id;

[User] Actually, please provide pairs of one hidden and one visible achievement name for each game where both types exist.

[Assistant]
SELECT h.game_id,
       h.name AS hidden_name,
       v.name AS visible_name
FROM gaming_technology.achievements h
JOIN gaming_technology.achievements v
  ON h.game_id = v.game_id
 AND h.hidden = TRUE
 AND v.hidden = FALSE
WHERE EXISTS (
  SELECT 1 FROM gaming_technology.achievements x
   WHERE x.game_id = h.game_id
     AND x.hidden = FALSE
)
AND EXISTS (
  SELECT 1 FROM gaming_technology.achievements y
   WHERE y.game_id = h.game_id
     AND y.hidden = TRUE
);

[User] Show me the names of law firms founded after 2010, along with the full name of their managing partner.

[Assistant] SELECT f.firm_name, l.first_name, l.last_name FROM legal_services.law_firms AS f JOIN legal_services.lawyers AS l ON f.managing_partner_id = l.lawyer_id WHERE f.founded_date > '2010-12-31';

[User] List all claim documents where the file name contains 'invoice' (case insensitive), showing the document ID, claim ID, file name, and uploaded_at.

[Assistant]
SELECT document_id, claim_id, file_name, uploaded_at
FROM insurance.claim_documents
WHERE LOWER(file_name) LIKE '%invoice%';

[User] Show me all cancelled trips along with their scheduled departure times and route IDs.

[Assistant] SELECT trip_id, route_id, scheduled_departure FROM transportation.trips WHERE status = 'cancelled';

[User] Can you include the vehicle ID and driver ID for these trips, and filter to only show cancellations that were supposed to depart in the morning (between 6 AM and 12 PM)?

[Assistant] SELECT trip_id, route_id, vehicle_id, driver_id, scheduled_departure FROM transportation.trips WHERE status = 'cancelled' AND EXTRACT(HOUR FROM scheduled_departure) BETWEEN 6 AND 11;

[User] Now group these results by driver_id and show the count of morning cancellations per driver.

[Assistant] SELECT driver_id, COUNT(*) AS cancellation_count FROM transportation.trips WHERE status = 'cancelled' AND EXTRACT(HOUR FROM scheduled_departure) BETWEEN 6 AND 11 GROUP BY driver_id ORDER BY cancellation_count DESC;

[User] Could you list all agencies along with the name of their parent agency?

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

[User] Please only show the agencies that have a parent agency.

[Assistant] SELECT child.agency_name AS agency_name, parent.agency_name AS parent_agency_name FROM government_services.agencies AS child INNER JOIN government_services.agencies AS parent ON child.parent_agency_id = parent.agency_id;

[User] Which cities have more than 10 active customers in the state of Texas? Provide the city name and the customer count.

[Assistant]
SELECT city, COUNT(*) AS customer_count
FROM insurance.customers
WHERE state = 'TX' AND status = 'Active'
GROUP BY city
HAVING COUNT(*) > 10;

[User] Can you help me retrieve the list of components made of a specific material along with their supplier details?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id

[User] Can you also include the part number for each component in the result?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
HGET component:<component_id> part_number

[User] If I want to filter out components from a specific supplier, how can I modify the query?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
HGET component:<component_id> part_number
IF HGET component:<component_id> supplier_id != 'sup:ACME_AERO' THEN INCLUDE

[User] Can you also sort the results based on the part number?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
HGET component:<component_id> part_number
IF HGET component:<component_id> supplier_id != 'sup:ACME_AERO' THEN INCLUDE
SORT BY part_number ASC

[User] Please list the contact phone number and website for each insurance plan.

[Assistant] SELECT plan_id, plan_name, contact_phone, website FROM healthcare.insurance_plans;

[User] Show only the plans where the website contains '.gov'.

[Assistant] SELECT plan_id, plan_name, contact_phone, website FROM healthcare.insurance_plans WHERE website LIKE '%.gov%';


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.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 healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
##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 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.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.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 PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
##Table Structure
CREATE TABLE financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)

[User] Which department has the highest number of employees currently employed?

[Assistant] SELECT department FROM government_services.employees WHERE termination_date IS NULL GROUP BY department ORDER BY COUNT(*) DESC LIMIT 1;

[User] List each patient and the total number of chronic diagnoses they have received, as well as the number of distinct doctors who have made those diagnoses.

[Assistant] SELECT patient_id, COUNT(*) AS chronic_diagnoses_count, COUNT(DISTINCT doctor_id) AS distinct_doctors FROM healthcare.diagnoses WHERE is_chronic = TRUE GROUP BY patient_id;

[User] Only include patients who have received diagnoses recorded as 'Active' status.

[Assistant] SELECT patient_id, COUNT(*) AS chronic_diagnoses_count, COUNT(DISTINCT doctor_id) AS distinct_doctors FROM healthcare.diagnoses WHERE is_chronic = TRUE AND status = 'Active' GROUP BY patient_id;

[User] List each doctor and how many prescriptions they have written, sorted by the highest count first.

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

[User] Calculate the average quantity for orders based on their status.

[Assistant] SELECT status, AVG(quantity) FROM trading_platform.orders GROUP BY status;

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

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

[User] Show me the total principal amount for each loan type, along with the count of loans and average monthly payment, but only for loans originated in the last 5 years.

[Assistant] SELECT loan_type, SUM(principal_amount) AS total_principal, COUNT(loan_id) AS loan_count, AVG(monthly_payment) AS avg_monthly_payment FROM financial_services.loans WHERE origination_date >= CURRENT_DATE - INTERVAL '5 years' GROUP BY loan_type;

[User] Find all policies that were cancelled due to 'Non-payment'. Show the policy number, cancellation date, and premium amount for these policies.

[Assistant] SELECT policy_number ,  cancellation_date ,  premium_amount FROM insurance.policies WHERE status = 'Cancelled' AND cancellation_reason = 'Non-payment'


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.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, 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 bool )
CREATE TABLE social_media.hashtags ( hashtag_id text PRIMARY KEY, tag_name text, created_at timestamp )
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 )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )
##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 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 web3.tokens ( token_id character varying(64) NOT NULL, contract_address character varying(128) NOT NULL, token_name character varying(128) NOT NULL, token_symbol character varying(32) NOT NULL, decimals integer NOT NULL, total_supply numeric(38,14) NOT NULL, PRIMARY KEY (token_id) )
##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 character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
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.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.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 transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )

[User] List all agents and their managers' full names.

[Assistant] SELECT a.first_name, a.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM insurance.agents a LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id;

[User] Show the usernames of all users who were created in 2024.

[Assistant]
SELECT username
FROM social_media.users
WHERE EXTRACT(YEAR FROM created_at) = 2024;

[User] List all document IDs and their corresponding location names for documents that are associated with applications assigned to a service location in the city of 'Los Angeles'.

[Assistant]
SELECT d.document_id, sl.location_name
FROM government_services.documents d
JOIN government_services.service_locations sl
  ON d.application_id = sl.location_id
WHERE sl.city = 'Los Angeles';

[User] Find all pairs of appointments that are scheduled for the same case and overlap in time. Show the IDs of the two overlapping appointments and the shared case ID.

[Assistant] SELECT t1.appointment_id AS appointment1_id, t2.appointment_id AS appointment2_id, t1.case_id FROM legal_services.appointments AS t1 JOIN legal_services.appointments AS t2 ON t1.case_id = t2.case_id AND t1.appointment_id != t2.appointment_id WHERE t1.start_time < t2.end_time AND t2.start_time < t1.end_time;

[User] List all pairs of tokens (show token_id for both) that share the same contract address, excluding pairs where the token_id is the same.

[Assistant] SELECT t1.token_id AS token_id1, t2.token_id AS token_id2, t1.contract_address FROM web3.tokens AS t1 JOIN web3.tokens AS t2 ON t1.contract_address = t2.contract_address WHERE t1.token_id < t2.token_id;

[User] For each medication manufacturer, show the total number of distinct generic names they produce.

[Assistant] SELECT manufacturer, COUNT(DISTINCT generic_name) AS distinct_generic_name_count FROM healthcare.medications WHERE generic_name IS NOT NULL AND manufacturer IS NOT NULL GROUP BY manufacturer ORDER BY manufacturer;

[User] List pairs of drivers whose license expiry dates fall within 30 days of each other. Show both driver_ids, names, and the two expiry dates.

[Assistant] SELECT d1.driver_id AS driver1_id, d1.first_name AS driver1_first, d1.last_name AS driver1_last, d1.license_expiry_date AS expiry1, d2.driver_id AS driver2_id, d2.first_name AS driver2_first, d2.last_name AS driver2_last, d2.license_expiry_date AS expiry2 FROM transportation.drivers d1 JOIN transportation.drivers d2 ON d1.driver_id < d2.driver_id AND ABS((d1.license_expiry_date - d2.license_expiry_date)) <= INTERVAL '30 days';


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.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.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##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.insurance_plans ( plan_id text PRIMARY KEY, 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 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 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) )
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)
##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 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 )

[User] List the usernames and registration dates for users who registered before the earliest deployed contract.

[Assistant] SELECT T1.username, T1.created_at FROM web3.users AS T1 JOIN (SELECT MIN(deployed_at) AS earliest_deploy FROM web3.contracts) AS T2 ON T1.created_at < T2.earliest_deploy;

[User] List every diagnosis description paired with every insurance plan's website.

[Assistant] SELECT T1.description, T2.website FROM healthcare.diagnoses AS T1 CROSS JOIN healthcare.insurance_plans AS T2;

[User] Only include chronic diagnoses and plans whose website ends with '.org'.

[Assistant] SELECT T1.description, T2.website FROM healthcare.diagnoses AS T1 CROSS JOIN healthcare.insurance_plans AS T2 WHERE T1.is_chronic = true AND T2.website LIKE '%.org';

[User] What is the average ROI and average realized_ratio for each chain?

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

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

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

[User] Show me the total fuel quantity and cost for each route, grouped by route number, only for trips that have associated fuel logs.

[Assistant]
SELECT r.route_number, SUM(f.quantity) AS total_quantity, SUM(f.total_cost) AS total_cost
FROM transportation.fuel_logs f
JOIN transportation.routes r ON f.trip_id IS NOT NULL AND f.trip_id IN (
    SELECT DISTINCT trip_id FROM transportation.fuel_logs
)
JOIN transportation.bookings b ON f.trip_id = b.trip_id
WHERE r.route_id = b.trip_id
GROUP BY r.route_number;

[User] List all trades for asset 'BTC' where the trade quantity is greater than 5.

[Assistant] SELECT trade_id, order_id, buyer_id, seller_id, quantity, price, traded_at FROM trading_platform.trades WHERE asset_id = 'BTC' AND quantity > 5;

[User] List all post IDs that have more than one hashtag associated with them.

[Assistant] SELECT post_id FROM social_media.post_hashtags GROUP BY post_id HAVING COUNT(hashtag_id) > 1;

[User] For each of these posts that have multiple hashtags, show the post ID and all associated hashtag IDs.

[Assistant] SELECT DISTINCT t1.post_id, t1.hashtag_id FROM social_media.post_hashtags AS t1 JOIN social_media.post_hashtags AS t2 ON t1.post_id = t2.post_id WHERE t1.post_hashtag_id != t2.post_hashtag_id;

[User] List the names of law firms whose managing partner has uploaded at least one document, and show the managing partner ID along with the firm's phone number.

[Assistant] SELECT DISTINCT T1.firm_name, T1.managing_partner_id, T1.phone FROM legal_services.law_firms AS T1 JOIN legal_services.documents AS T2 ON T1.managing_partner_id = T2.uploaded_by_lawyer_id;

[User] How many medications does each manufacturer have?

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

[User] Only include manufacturers with more than 10 medications.

[Assistant]
SELECT manufacturer, COUNT(*) AS med_count
FROM healthcare.medications
GROUP BY manufacturer
HAVING COUNT(*) > 10;

[User] For each access level, count the number of employees. Return access_level and the corresponding employee_count.

[Assistant] SELECT access_level, COUNT(*) AS employee_count FROM government_services.employees GROUP BY access_level;