System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE financial_services.accounts ( account_id text PRIMARY KEY, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.transactions ( transaction_id text PRIMARY KEY, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.securities ( security_id text PRIMARY KEY, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )
CREATE TABLE financial_services.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id bigserial PRIMARY KEY, security_id text, data_timestamp timestamp, open_price numeric, high_price numeric, low_price numeric, close_price numeric, adjusted_close_price numeric, volume bigint, source text )
CREATE TABLE financial_services.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )
CREATE TABLE financial_services.loans ( loan_id text PRIMARY KEY, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months int, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )
##Table Structure
CREATE TABLE legal_services.clients (
    client_id character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_id)
)
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)
##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) )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
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.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, 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, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
##Table Structure
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )

[User] Summarize the trades by trade type, showing the total quantity and the total amount for each type.

[Assistant] SELECT trade_type, SUM(quantity) AS total_quantity, SUM(total_amount) AS total_amount FROM financial_services.trades GROUP BY trade_type;

[User] Calculate the total sum of hours spent across all time entries that are billable but have not yet been billed.

[Assistant] SELECT SUM(hours_spent) FROM legal_services.time_entries WHERE is_billable = TRUE AND is_billed = FALSE;

[User] Which employees have verified more than 5 documents in the last 30 days? Return the employee's full name, department, and the number of verifications.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS full_name, e.department, COUNT(d.document_id) AS verification_count
FROM government_services.documents d
JOIN government_services.employees e ON d.verified_by_employee_id = e.employee_id
WHERE d.verification_status = 'Verified'
  AND d.verification_timestamp >= now() - interval '30 days'
GROUP BY e.first_name, e.last_name, e.department
HAVING COUNT(d.document_id) > 5;

[User] How many securities are there for each security type?

[Assistant] SELECT security_type, COUNT(*) AS security_count FROM financial_services.securities GROUP BY security_type;

[User] Only show security types that have more than 50 securities.

[Assistant] SELECT security_type, COUNT(*) AS security_count FROM financial_services.securities GROUP BY security_type HAVING COUNT(*) > 50;

[User] Sort the result by the count in descending order.

[Assistant] SELECT security_type, COUNT(*) AS security_count FROM financial_services.securities GROUP BY security_type HAVING COUNT(*) > 50 ORDER BY security_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
##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 legal_services.appointments ( appointment_id text, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )
##Table Structure
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE legal_services.documents ( document_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, document_name character varying(255) NOT NULL, document_type character varying(100), storage_path text NOT NULL, uploaded_by_lawyer_id character varying(64), upload_timestamp timestamp NOT NULL, version integer DEFAULT 1, description text, PRIMARY KEY (document_id) )

[User] List the service name, category, and standard fee for all services offered by agencies that have at least one accessible service location in the state of 'California'.

[Assistant] SELECT DISTINCT T1.service_name, T1.category, T1.standard_fee FROM government_services.services AS T1 JOIN government_services.service_locations AS T2 ON T1.agency_id = T2.agency_id WHERE T2.is_accessible = TRUE AND T2.state = 'California';

[User] Which token on each chain has the highest ROI and what is its associated PNL and net_flow?

[Assistant]
SELECT a.chain,
       a.token_symbol,
       a.roi,
       a.pnl,
       a.net_flow
FROM smart_money_token_performance a
JOIN (
  SELECT chain, MAX(roi) AS max_roi
  FROM smart_money_token_performance
  GROUP BY chain
) b ON a.chain = b.chain AND a.roi = b.max_roi;

[User] Actually, I’d like to see the top 2 tokens with the highest ROI per chain instead of only the top one.

[Assistant]
WITH ranked AS (
  SELECT *,
         ROW_NUMBER() OVER (PARTITION BY chain ORDER BY roi DESC) AS rn
  FROM smart_money_token_performance
)
SELECT chain, token_symbol, roi, pnl, net_flow
FROM ranked
WHERE rn <= 2;

[User] I got an error about ties when two tokens share the same ROI. Please adjust the query to include ties for the highest ROI.

[Assistant]
WITH ranked AS (
  SELECT *,
         DENSE_RANK() OVER (PARTITION BY chain ORDER BY roi DESC) AS dr
  FROM smart_money_token_performance
)
SELECT chain, token_symbol, roi, pnl, net_flow
FROM ranked
WHERE dr = 1;

[User] Can you also include the avg_cost for each result?

[Assistant]
WITH ranked AS (
  SELECT *,
         DENSE_RANK() OVER (PARTITION BY chain ORDER BY roi DESC) AS dr
  FROM smart_money_token_performance
)
SELECT chain, token_symbol, roi, pnl, net_flow, avg_cost
FROM ranked
WHERE dr = 1;

[User] List all appointments for the client with ID 'client_001' showing the lawyer's ID, appointment subject, and start time.

[Assistant]
SELECT a.lawyer_id, a.subject, a.start_time
FROM legal_services.appointments a
WHERE a.client_id = 'client_001';

[User] Actually, please also include the case ID in the results.

[Assistant]
SELECT a.lawyer_id, a.subject, a.start_time, a.case_id
FROM legal_services.appointments a
WHERE a.client_id = 'client_001';

[User] Now, sort the results by start time from newest to oldest.

[Assistant]
SELECT a.lawyer_id, a.subject, a.start_time, a.case_id
FROM legal_services.appointments a
WHERE a.client_id = 'client_001'
ORDER BY a.start_time DESC;

[User] List all claims that are still pending (status = 'pending') and were reported more than 30 days ago.

[Assistant] SELECT claim_id, policy_id, customer_id, reported_date FROM insurance.claims WHERE status = 'pending' AND reported_date < CURRENT_DATE - INTERVAL '30 days';

[User] Now include only claims with estimated loss values and sort them by the oldest reported date first.

[Assistant] SELECT claim_id, policy_id, customer_id, reported_date, estimated_loss FROM insurance.claims WHERE status = 'pending' AND reported_date < CURRENT_DATE - INTERVAL '30 days' AND estimated_loss IS NOT NULL ORDER BY reported_date ASC;

[User] Show the product name, type, and creation date for products created before January 1st, 2023.

[Assistant] SELECT product_name, product_type, created_at FROM insurance.insurance_products WHERE created_at < '2023-01-01';

[User] Can you also include the base premium and only show products that are currently active?

[Assistant] SELECT product_name, product_type, created_at, base_premium FROM insurance.insurance_products WHERE created_at < '2023-01-01' AND is_active = true;

[User] I need to find all pairs of documents that were uploaded by the same lawyer within 7 days of each other.

[Assistant]
SELECT a.uploaded_by_lawyer_id,
       a.document_id AS doc1_id,
       b.document_id AS doc2_id,
       a.upload_timestamp AS ts1,
       b.upload_timestamp AS ts2
FROM legal_services.documents a
JOIN legal_services.documents b
  ON a.uploaded_by_lawyer_id = b.uploaded_by_lawyer_id
 AND a.document_id < b.document_id
 AND a.upload_timestamp BETWEEN b.upload_timestamp - INTERVAL '7 days' AND b.upload_timestamp + INTERVAL '7 days';

[User] Only include those pairs where both documents have version greater than 1.

[Assistant]
SELECT a.uploaded_by_lawyer_id,
       a.document_id AS doc1_id,
       b.document_id AS doc2_id,
       a.upload_timestamp AS ts1,
       b.upload_timestamp AS ts2
FROM legal_services.documents a
JOIN legal_services.documents b
  ON a.uploaded_by_lawyer_id = b.uploaded_by_lawyer_id
 AND a.document_id < b.document_id
 AND a.upload_timestamp BETWEEN b.upload_timestamp - INTERVAL '7 days' AND b.upload_timestamp + INTERVAL '7 days'
WHERE a.version > 1
  AND b.version > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text, license_plate text, vin text, make text, model text, year integer, type text, capacity integer, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.maintenance_logs ( log_id text, vehicle_id text, service_date date, odometer_reading integer, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
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.passengers ( passenger_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
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 web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)
##Table Structure
CREATE TABLE financial_services.loans ( loan_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL UNIQUE, loan_type character varying(50) NOT NULL, principal_amount numeric(19, 4) NOT NULL, current_principal_balance numeric(19, 4) NOT NULL, interest_rate numeric(6, 4) NOT NULL, term_months integer NOT NULL, origination_date date NOT NULL, maturity_date date NOT NULL, monthly_payment numeric(12, 4), collateral_description text, status character varying(32) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id) )
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
##Table Structure
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, status character varying(32) NOT NULL, reviewed_at timestamp NOT NULL, PRIMARY KEY (kyc_audit_id) )

[User] For each trip, can you show the trip_id, number of passengers, and the make and model of the assigned vehicle?

[Assistant]
SELECT b.trip_id, COUNT(b.passenger_id) AS passenger_count, v.make, v.model
FROM transportation.bookings b
JOIN transportation.vehicles v ON b.trip_id IN (
    SELECT DISTINCT trip_id FROM transportation.fuel_logs WHERE vehicle_id = v.vehicle_id
)
GROUP BY b.trip_id, v.make, v.model;

[User] Find pairs of users who registered on the same weekday but in different years. List the user ID and registration date for both users, and the weekday name.

[Assistant] SELECT u1.user_id, u1.created_at AS user1_created_at, u2.user_id, u2.created_at AS user2_created_at, TO_CHAR(u1.created_at, 'Day') AS registration_weekday FROM web3.users u1 JOIN web3.users u2 ON TO_CHAR(u1.created_at, 'Day') = TO_CHAR(u2.created_at, 'Day') AND EXTRACT(YEAR FROM u1.created_at) <> EXTRACT(YEAR FROM u2.created_at) AND u1.user_id < u2.user_id ORDER BY TO_CHAR(u1.created_at, 'D'), u1.created_at;

[User] Show me all patients who have non-primary insurance plans with expiration dates within the next 60 days, along with their policy numbers and subscriber names.

[Assistant] SELECT patient_id, policy_number, subscriber_name FROM healthcare.patient_insurance WHERE is_primary = false AND expiration_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '60 days');

[User] List all auto loans (loan_id, principal_amount, interest_rate) where the current principal balance is less than 40% of the original principal amount, along with the account_id and the difference between principal_amount and current_principal_balance.

[Assistant] SELECT loan_id, principal_amount, interest_rate, account_id, (principal_amount - current_principal_balance) AS amount_paid FROM financial_services.loans WHERE loan_type = 'Auto' AND current_principal_balance < (0.4 * principal_amount);

[User] Show me each department in each property, along with the total number of available services and their combined price.

[Assistant] SELECT property_id, department, COUNT(*) AS service_count, SUM(price) AS total_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, department;

[User] I want to see the number of 'buy' and 'sell' orders for each asset, along with the asset_id.

[Assistant] SELECT asset_id, order_type, COUNT(*) AS order_count FROM trading_platform.orders GROUP BY asset_id, order_type;

[User] Can you also show the average price for 'buy' and 'sell' orders for each asset?

[Assistant] SELECT asset_id, order_type, COUNT(*) AS order_count, AVG(price) AS avg_price FROM trading_platform.orders GROUP BY asset_id, order_type;

[User] Find any two policies for the same customer whose coverage dates overlap. Return the customer ID, both policy numbers, and their start and end dates.

[Assistant]
SELECT p1.customer_id,
       p1.policy_number AS policy1_number,
       p1.start_date   AS policy1_start,
       p1.end_date     AS policy1_end,
       p2.policy_number AS policy2_number,
       p2.start_date   AS policy2_start,
       p2.end_date     AS policy2_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.policy_id   <  p2.policy_id
 AND p1.start_date  <= p2.end_date
 AND p2.start_date  <= p1.end_date;

[User] Count the number of assets for each asset type.

[Assistant] SELECT type, COUNT(*) FROM trading_platform.assets GROUP BY type;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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 )
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.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 )
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.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
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.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
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 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.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text PRIMARY KEY, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
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 social_media.messages ( message_id.text, conversation_id.text, sender_user_id.text, content.text, media_url.text, media_type.text, sent_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )

[User] Could you list the route number and the name of the destination location for routes that start at a location of type 'Depot'?

[Assistant] SELECT T1.route_number ,  T2.name FROM transportation.routes AS T1 JOIN transportation.locations AS T2 ON T1.origin_location_id  =  T2.location_id WHERE T2.type  =  'Depot'

[User] Get a list of all distinct specialties found among the doctors.

[Assistant] SELECT DISTINCT specialty FROM healthcare.doctors;

[User] How many distinct tokens did smart money buy on the 'BSC' chain in 2023?

[Assistant]
SELECT COUNT(DISTINCT token_address) AS distinct_tokens_bought
FROM smart_money_token_inflow
WHERE type = 1
  AND chain = 'BSC'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') >= '2023-01-01'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') <= '2023-12-31';

[User] Can you break this down by narrative and show the count per narrative?

[Assistant]
SELECT narrative, COUNT(DISTINCT token_address) AS distinct_tokens_bought
FROM smart_money_token_inflow
WHERE type = 1
  AND chain = 'BSC'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') >= '2023-01-01'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') <= '2023-12-31'
GROUP BY narrative
ORDER BY distinct_tokens_bought DESC;

[User] List all users who currently have a 'pending' KYC status, showing their user ID and username.

[Assistant] SELECT u.user_id, u.username FROM users u JOIN kyc_audit k ON u.user_id = k.user_id WHERE k.status = 'pending';

[User] Which users participated in more than one conversation? Show their user_id and participant_id for each conversation, along with the joined_at time.

[Assistant] SELECT user_id, participant_id, conversation_id, joined_at FROM social_media.conversation_participants WHERE user_id IN (SELECT user_id FROM social_media.conversation_participants GROUP BY user_id HAVING COUNT(DISTINCT conversation_id) > 1) ORDER BY user_id, joined_at;

[User] Can you also show the last_read_at time for each participant in the result?

[Assistant] SELECT user_id, participant_id, conversation_id, joined_at, last_read_at FROM social_media.conversation_participants WHERE user_id IN (SELECT user_id FROM social_media.conversation_participants GROUP BY user_id HAVING COUNT(DISTINCT conversation_id) > 1) ORDER BY user_id, joined_at;

[User] How many unread messages does each sender have? Show sender_user_id and count of messages where read_at is null.

[Assistant]
SELECT sender_user_id, COUNT(*) AS unread_messages
FROM social_media.messages
WHERE read_at IS NULL
GROUP BY sender_user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
##Table Structure
CREATE TABLE legal_services.clients (
    client_id character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_id)
)
##Table Structure
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.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 )
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
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 )
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.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
##Table Structure
CREATE TABLE healthcare.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 )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] List the first and last names of all drivers with status 'Active' along with the route number and type of all Express routes.

[Assistant]
SELECT d.first_name, d.last_name, r.route_number, r.type
FROM transportation.drivers d
CROSS JOIN transportation.routes r
WHERE d.status = 'Active' AND r.type = 'Express';

[User] Now, only include drivers hired after '2023-01-01'.

[Assistant]
SELECT d.first_name, d.last_name, r.route_number, r.type
FROM transportation.drivers d
CROSS JOIN transportation.routes r
WHERE d.status = 'Active'
  AND r.type = 'Express'
  AND d.hire_date > '2023-01-01';

[User] What is the total balance and the number of accounts for each currency, including only accounts opened in the last 2 years?

[Assistant] SELECT currency ,  SUM(balance) AS total_balance ,  COUNT(*) AS account_count FROM financial_services.accounts WHERE opened_date  >=  CURRENT_DATE - INTERVAL '2 year' GROUP BY currency

[User] Please exclude currencies where the total balance is less than 100000.

[Assistant] SELECT currency ,  SUM(balance) AS total_balance ,  COUNT(*) AS account_count FROM financial_services.accounts WHERE opened_date  >=  CURRENT_DATE - INTERVAL '2 year' GROUP BY currency HAVING SUM(balance)  >=  100000

[User] Can you also include the average interest rate for the remaining currencies, considering only accounts with 'ACTIVE' status?

[Assistant] SELECT currency ,  SUM(balance) AS total_balance ,  COUNT(*) AS account_count ,  AVG(CASE WHEN status  =  'ACTIVE' THEN interest_rate ELSE NULL END) AS avg_active_interest_rate FROM financial_services.accounts WHERE opened_date  >=  CURRENT_DATE - INTERVAL '2 year' GROUP BY currency HAVING SUM(balance)  >=  100000

[User] Find all clients who do not have a company name listed and show their full name and email.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE company_name IS NULL;

[User] Show the full name and job title of employees whose job title includes 'Manager' and who do not have a listed manager.

[Assistant] SELECT first_name, last_name, job_title FROM government_services.employees WHERE job_title LIKE '%Manager%' AND manager_employee_id IS NULL;

[User] Show the average maintenance cost for vehicles of each make, including only vehicles that have had at least one maintenance log.

[Assistant] SELECT v.make, AVG(ml.cost) AS average_maintenance_cost FROM transportation.vehicles AS v JOIN transportation.maintenance_logs AS ml ON v.vehicle_id = ml.vehicle_id GROUP BY v.make ORDER BY average_maintenance_cost DESC;

[User] List all doctors whose last name begins with 'B', showing their doctor ID, full name, and their hospital affiliation ID.

[Assistant] SELECT doctor_id, first_name, last_name, hospital_affiliation_id FROM healthcare.doctors WHERE last_name LIKE 'B%';

[User] Could you refine the query to only include doctors whose phone_number ends with '99'?

[Assistant] SELECT doctor_id, first_name, last_name, hospital_affiliation_id FROM healthcare.doctors WHERE last_name LIKE 'B%' AND phone_number LIKE '%99';

[User] Which agencies offer services in the 'Social Assistance' category? Show the agency name and the service name.

[Assistant]
SELECT a.agency_name, s.service_name
FROM government_services.services s
JOIN government_services.agencies a ON s.agency_id = a.agency_id
WHERE s.category = 'Social Assistance';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
##Table Structure
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )
##Table Structure
CREATE TABLE web3.contracts (
    contract_id character varying(64) NOT NULL,  -- unique identifier for the contract
    address character varying(128) NOT NULL, -- address of the deployed contract
    abi text NOT NULL, -- application binary interface of the contract
    bytecode text NOT NULL, -- bytecode of the contract
    deployer_address character varying(128) NOT NULL, -- address of the deployer
    deployed_at timestamp NOT NULL, -- time when the contract was deployed
    network_id character varying(64) NOT NULL, -- identifier of the network where the contract is deployed
    status character varying(32) NOT NULL, -- status of the contract (e.g., active, deprecated)
    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.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
##Table Structure
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] What is the average commission rate for agents whose status is 'Terminated'?

[Assistant] SELECT AVG(commission_rate) FROM insurance.agents WHERE status = 'Terminated' AND commission_rate IS NOT NULL;

[User] Show me the top 5 smart money addresses by profit on the Ethereum chain, along with their most profitable token and ROI, but only include addresses with a realized profit ratio above 70%.

[Assistant] SELECT address, most_profit_token, roi FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 70 ORDER BY profit DESC LIMIT 5;

[User] Can you also include their rank and filter to only show addresses with ROI greater than 50%?

[Assistant] SELECT address, most_profit_token, roi, rank FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 70 AND roi > 50 ORDER BY profit DESC LIMIT 5;

[User] For each wallet, list its address, the user_id, and the total value of all token transfers sent from that wallet, along with the contract address of the token.

[Assistant]
SELECT w.wallet_id, w.address, w.user_id, SUM(tt.value) AS total_sent_value, t.contract_address
FROM web3.wallets w
LEFT JOIN web3.token_transfers tt ON w.address = tt.from_address
LEFT JOIN web3.tokens t ON tt.token_id = t.token_id
GROUP BY w.wallet_id, w.address, w.user_id, t.contract_address;

[User] Calculate the average number of days cases stay open before being closed, grouped by case type. Only consider cases that have a date closed.

[Assistant] SELECT case_type, AVG(DATE_PART('day', date_closed - date_opened)) AS average_duration_days FROM legal_services.cases WHERE status = 'Closed' AND date_closed IS NOT NULL GROUP BY case_type;

[User] Exclude case types where the average duration is less than 100 days and order the results by average duration descending.

[Assistant] SELECT case_type, AVG(DATE_PART('day', date_closed - date_opened)) AS average_duration_days FROM legal_services.cases WHERE status = 'Closed' AND date_closed IS NOT NULL GROUP BY case_type HAVING AVG(DATE_PART('day', date_closed - date_opened)) >= 100 ORDER BY average_duration_days DESC;

[User] Find players who own items with rarity 'Rare' or higher ('Epic', 'Legendary') and list their usernames.

[Assistant] SELECT DISTINCT T1.username FROM players AS T1 INNER JOIN player_inventory AS T2 ON T1.player_id = T2.player_id INNER JOIN items AS T3 ON T2.item_id = T3.item_id WHERE T3.rarity IN ('Rare', 'Epic', 'Legendary');

[User] Filter this list further to only include players who acquired these items after '2024-01-01'.

[Assistant] SELECT DISTINCT T1.username FROM players AS T1 INNER JOIN player_inventory AS T2 ON T1.player_id = T2.player_id INNER JOIN items AS T3 ON T2.item_id = T3.item_id WHERE T3.rarity IN ('Rare', 'Epic', 'Legendary') AND T2.acquired_at > '2024-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id character varying(64) NOT NULL, token_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128) NOT NULL, value numeric(38,14) NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (transfer_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 government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
##Table Structure
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
##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 legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )
##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.json, created_at.timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )
##Table Structure
CREATE TABLE blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )

[User] List all insurance products along with their product types and the date they were last updated, but only include products where the base premium is greater than 2000.

[Assistant]
SELECT product_id, product_name, product_type, updated_at
FROM insurance.insurance_products
WHERE base_premium > 2000;

[User] Find all addresses that have both received and sent transfers of the same token. List the address and the token ID for each such instance.

[Assistant] SELECT DISTINCT t1.to_address AS address, t1.token_id FROM web3.token_transfers t1 JOIN web3.token_transfers t2 ON t1.to_address = t2.from_address AND t1.token_id = t2.token_id;

[User] Provide a count of citizens registered per calendar year.

[Assistant] SELECT CAST(EXTRACT(YEAR FROM registration_date) AS INTEGER) AS registration_year, COUNT(*) AS citizen_count FROM government_services.citizens GROUP BY 1 ORDER BY 1;

[User] How many appointments have a status of 'Cancelled' for each service?

[Assistant] SELECT service_id, COUNT(*) AS cancelled_appointments FROM government_services.appointments WHERE status = 'Cancelled' GROUP BY service_id;

[User] Find all pairs of users who registered at exactly the same timestamp, showing both user IDs, usernames, and the shared registration timestamp.

[Assistant]
SELECT u1.user_id AS user_id_1, u1.username AS username_1, u2.user_id AS user_id_2, u2.username AS username_2, u1.created_at
FROM web3.users u1
JOIN web3.users u2
  ON u1.created_at = u2.created_at
  AND u1.user_id < u2.user_id;

[User] List the token symbol, token name, and contract address for all tokens that have no recorded transfers in the token_transfers table.

[Assistant] SELECT T.token_symbol, T.token_name, T.contract_address FROM web3.tokens AS T LEFT JOIN token_transfers AS TT ON T.token_id = TT.token_id WHERE TT.transfer_id IS NULL;

[User] Which lawyers have scheduled appointments at each location? Please list the lawyer_id, location, and the number of scheduled appointments per lawyer per location.

[Assistant]
SELECT lawyer_id, location, COUNT(*) AS scheduled_appointments
FROM legal_services.appointments
WHERE status = 'Scheduled'
GROUP BY lawyer_id, location;

[User] Provide a list of all documents and their versions for a specific case, say with case_id = 'CASE789'.

[Assistant] SELECT document_name, version FROM legal_services.documents WHERE case_id = 'CASE789';

[User] For each patient, find the date of their most recent medical record and the effective date of their current primary insurance plan. Return patient_id, last_record_date, and effective_date.

[Assistant]
SELECT m.patient_id,
       m.last_date AS last_record_date,
       pi.effective_date
FROM (
  SELECT patient_id,
         MAX(record_date) AS last_date
  FROM healthcare.medical_records
  GROUP BY patient_id
) m
JOIN healthcare.patient_insurance pi
  ON m.patient_id = pi.patient_id
WHERE pi.is_primary = TRUE;

[User] Show the total amount of tokens transferred for each token_id along with the number of transfers involving each token.

[Assistant] SELECT token_id, SUM(value) AS total_transferred, COUNT(*) AS transfer_count FROM web3.token_transfers GROUP BY token_id;

[User] Show me the top 5 users with the most wallet addresses, along with the count of their wallets.

[Assistant] SELECT user_id, COUNT(wallet_id) AS wallet_count FROM blockchain.wallets WHERE user_id IS NOT NULL GROUP BY user_id ORDER BY wallet_count DESC LIMIT 5;

[User] Now include the earliest created wallet address for each of these top 5 users.

[Assistant] Note: The wallets table doesn't have a creation timestamp column. Without this information, we cannot determine the earliest created wallet. Please provide a table with creation timestamps if you need this analysis.

[User] Then just show me these top 5 users with their wallet counts and the first wallet_id alphabetically for each user.

[Assistant] SELECT user_id, COUNT(wallet_id) AS wallet_count, MIN(wallet_id) AS first_wallet_id FROM blockchain.wallets WHERE user_id IS NOT NULL GROUP BY user_id ORDER BY wallet_count DESC LIMIT 5;

[User] Show the number of users registered each month for 2024.

[Assistant]
SELECT
  date_trunc('month', created_at) AS month,
  COUNT(*) AS user_count
FROM trading_platform.users
WHERE created_at >= '2024-01-01'
  AND created_at < '2025-01-01'
GROUP BY month
ORDER BY month;


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 blockchain.smart_contracts ( contract_id.text, creator_address.text, code.text, timestamp.timestamp )
##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 )
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )
##Table Structure
CREATE TABLE social_media.follows ( follow_id character varying(64) NOT NULL, follower_user_id character varying(64) NOT NULL, following_user_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (follow_id), CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
##Table Structure
CREATE TABLE web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
##Table Structure
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
##Table Structure
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
##Table Structure
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
##Table Structure
CREATE TABLE government_services.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 )
##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] Find all smart contracts where the contract code contains the keyword 'proxy'.

[Assistant] SELECT contract_id, creator_address, timestamp FROM blockchain.smart_contracts WHERE code LIKE '%proxy%';

[User] For these 'proxy' contracts, can you also include the total number of contracts deployed by each creator?

[Assistant] SELECT sc.contract_id, sc.creator_address, sc.timestamp, creator_counts.total_contracts FROM blockchain.smart_contracts sc JOIN ( SELECT creator_address, COUNT(*) as total_contracts FROM blockchain.smart_contracts GROUP BY creator_address ) creator_counts ON sc.creator_address = creator_counts.creator_address WHERE sc.code LIKE '%proxy%';

[User] Which employees are managers themselves? Show their employee ID, full name, and job title.

[Assistant]
SELECT DISTINCT m.employee_id, m.first_name || ' ' || m.last_name AS full_name, m.job_title
FROM government_services.employees m
JOIN government_services.employees e ON e.manager_employee_id = m.employee_id;

[User] How many beneficiaries has each unique relationship type? List relationship and the count.

[Assistant]
SELECT relationship, COUNT(*) AS beneficiary_count
FROM insurance.policy_beneficiaries
GROUP BY relationship;

[User] Show me all clients whose company name contains 'Tech' and display their email and date of registration.

[Assistant] SELECT first_name, last_name, company_name, email, date_registered FROM legal_services.clients WHERE company_name ILIKE '%Tech%';

[User] Count the number of users whose location is 'London'.

[Assistant] SELECT count(*) FROM social_media.users WHERE location = 'London';

[User] For each transaction, list the total value transferred and the number of different addresses involved (either as sender or receiver).

[Assistant]
SELECT transaction_id, SUM(value) AS total_value_transferred, COUNT(DISTINCT addr) AS num_addresses_involved
FROM (
    SELECT transaction_id, from_address AS addr, value FROM web3.token_transfers
    UNION ALL
    SELECT transaction_id, to_address AS addr, 0 as value FROM web3.token_transfers
) t
GROUP BY transaction_id;

[User] How many users is each user following? Provide follower_user_id and the count of followings.

[Assistant]
SELECT follower_user_id, COUNT(*) AS following_count
FROM social_media.follows
GROUP BY follower_user_id;

[User] Retrieve the average base premium of insurance products for each product_type, including only types that have more than 5 products.

[Assistant]
SELECT product_type, AVG(base_premium) AS avg_premium
FROM insurance.insurance_products
GROUP BY product_type
HAVING COUNT(*) > 5;

[User] List all pairs of contracts deployed on the same network on the same day, showing network_id, the date, and the two contract IDs.

[Assistant]
SELECT c1.network_id,
       DATE(c1.deployed_at) AS deploy_date,
       c1.contract_id AS contract_a,
       c2.contract_id AS contract_b
FROM web3.contracts c1
JOIN web3.contracts c2
  ON c1.network_id = c2.network_id
 AND DATE(c1.deployed_at) = DATE(c2.deployed_at)
 AND c1.contract_id < c2.contract_id;

[User] Please list the full name and status of clients who have not provided a company name.

[Assistant]
SELECT first_name, last_name, status
FROM legal_services.clients
WHERE company_name IS NULL;

[User] Show all pairs of 'Evidence' documents within the same case, listing their document names, version numbers, and the shared case_id.

[Assistant]
SELECT d1.case_id,
       d1.document_name AS doc1_name,
       d1.version      AS doc1_version,
       d2.document_name AS doc2_name,
       d2.version      AS doc2_version
FROM legal_services.documents d1
JOIN legal_services.documents d2
  ON d1.case_id = d2.case_id
 AND d1.document_id < d2.document_id
WHERE d1.document_type = 'Evidence'
  AND d2.document_type = 'Evidence';

[User] For each case type, calculate the average time to close cases in days, only including cases that have been closed.

[Assistant]
SELECT case_type,
       AVG(EXTRACT(EPOCH FROM (date_closed - date_opened)) / 86400) AS avg_close_days
FROM legal_services.cases
WHERE status = 'Closed'
  AND date_closed IS NOT NULL
GROUP BY case_type;

[User] Show me all services, their names, and their online application URLs for services that are both active and have an online application available.

[Assistant] SELECT service_name, online_application_url FROM government_services.services WHERE is_active = TRUE AND online_application_url IS NOT NULL AND online_application_url <> '';

[User] List the latitude and longitude coordinates for all service locations located in a city named 'Seattle'.

[Assistant] SELECT latitude ,  longitude FROM government_services.service_locations WHERE city = 'Seattle'

[User] Count the total number of unique insurance providers in the system.

[Assistant] SELECT COUNT(DISTINCT insurance_provider) FROM healthcare.insurance_plans;


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.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.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 )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
##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 )
##Table Structure
CREATE TABLE web3.events ( event_id text PRIMARY KEY, contract_id text, event_name text, data text, emitted_at timestamp, transaction_id text, log_index int )
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
##Table Structure
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id text, first_name text, last_name text, bar_number text, firm_id text, email text, phone text, specialization text, hire_date timestamp, is_partner boolean )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )
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 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.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )

[User] For each application that has at least one failed notification, provide the application ID, the total number of notifications received for that application, and the count of failed notifications.

[Assistant] SELECT application_id, COUNT(*) AS total_notifications, COUNT(CASE WHEN status = 'Failed' THEN 1 END) AS failed_notifications FROM government_services.notifications GROUP BY application_id HAVING COUNT(CASE WHEN status = 'Failed' THEN 1 END) > 0;

[User] What is the average commission rate for active agents?

[Assistant] SELECT AVG(commission_rate) FROM insurance.agents WHERE status = 'Active';

[User] For each user, show the date of their earliest and latest wallet creation.

[Assistant]
SELECT user_id,
       MIN(created_at) AS first_created,
       MAX(created_at) AS last_created
FROM web3.wallets
GROUP BY user_id;

[User] Actually, also include the count of wallets each user has created.

[Assistant]
SELECT user_id,
       MIN(created_at) AS first_created,
       MAX(created_at) AS last_created,
       COUNT(*) AS wallet_count
FROM web3.wallets
GROUP BY user_id;

[User] Show me all rooms on floor 4 or above together with their room number, features, and current status.

[Assistant]
SELECT room_id, room_number, features, status
FROM hospitality_technology.rooms
WHERE floor >= 4;

[User] Only include rooms that are marked as non-smoking and sort the results by floor descending.

[Assistant]
SELECT room_id, room_number, features, status, floor
FROM hospitality_technology.rooms
WHERE floor >= 4 AND is_smoking = FALSE
ORDER BY floor DESC;

[User] Show me all token transfers where the corresponding transaction also emitted an event named 'Transfer', along with the transfer value and event data.

[Assistant] SELECT tt.transfer_id, tt.value, e.data FROM web3.token_transfers tt JOIN web3.events e ON tt.transaction_id = e.transaction_id WHERE e.event_name = 'Transfer';

[User] For each citizen, how many notifications have a status of 'Read'? Please show the citizen_id and their corresponding count.

[Assistant]
SELECT citizen_id, COUNT(*) AS read_notification_count
FROM government_services.notifications
WHERE status = 'Read'
GROUP BY citizen_id;

[User] Show me the number of comments each user has made on each post.

[Assistant] SELECT post_id, user_id, COUNT(*) AS comment_count FROM social_media.comments GROUP BY post_id, user_id;

[User] Can you also show the creation time of the most recent comment for each post by each user?

[Assistant] SELECT post_id, user_id, COUNT(*) AS comment_count, MAX(created_at) AS latest_comment_time FROM social_media.comments GROUP BY post_id, user_id;

[User] Show me all time entries where the hours spent is greater than 5.

[Assistant] SELECT entry_id, date_worked, hours_spent, description FROM legal_services.time_entries WHERE hours_spent > 5;

[User] Give me a list of all specializations available at each law firm.

[Assistant]
SELECT DISTINCT firm_id, specialization
FROM legal_services.lawyers;

[User] For each specialization, show the number of lawyers in the firm who have that specialization.

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

[User] How many cases are associated with each unique lead lawyer ID? Show the lead lawyer ID and the count of cases, but only for lawyers who lead at least 5 cases. Sort the results by the case count in descending order.

[Assistant] SELECT lead_lawyer_id, count(case_id) FROM legal_services.cases GROUP BY lead_lawyer_id HAVING count(case_id) >= 5 ORDER BY count(case_id) DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
##Table Structure
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
##Table Structure
CREATE TABLE web3.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
##Table Structure
CREATE TABLE insurance.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.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 )
##Table Structure
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )
##Table Structure
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
##Table Structure
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 healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
##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 web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )

[User] List all law firms founded in the year 2015. Show their names, phone numbers, and website.

[Assistant]
SELECT firm_name, phone, website
FROM legal_services.law_firms
WHERE EXTRACT(YEAR FROM founded_date) = 2015;

[User] What is the total and average amount of unspent UTXOs per address?

[Assistant]
SELECT
  address,
  COUNT(*) AS utxo_count,
  SUM(amount) AS total_unspent_amount,
  AVG(amount) AS average_unspent_amount
FROM trading_platform.utxos
WHERE spent = FALSE
GROUP BY address;

[User] Find all pairs of users where the registration times are within 30 minutes of each other, and show both user IDs, usernames, and the time difference in minutes.

[Assistant] SELECT u1.user_id AS user1_id, u1.username AS user1_name, u2.user_id AS user2_id, u2.username AS user2_name, ROUND(ABS(EXTRACT(EPOCH FROM u1.created_at - u2.created_at))/60,2) AS diff_minutes FROM web3.users u1 JOIN web3.users u2 ON u1.user_id < u2.user_id WHERE ABS(EXTRACT(EPOCH FROM u1.created_at - u2.created_at))/60 <= 30;

[User] For policies issued in the current year, show me the total premium_amount and the average deductible grouped by policy status.

[Assistant]
SELECT status,
       SUM(premium_amount) AS total_premium,
       AVG(deductible)     AS average_deductible
FROM insurance.policies
WHERE EXTRACT(YEAR FROM issued_at) = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY status;

[User] For each agency, list the agency name and the total count of employees who have a recorded termination date.

[Assistant] SELECT a.agency_name, COUNT(e.employee_id) FROM government_services.agencies AS a LEFT JOIN government_services.employees AS e ON a.agency_id = e.agency_id AND e.termination_date IS NOT NULL GROUP BY a.agency_name;

[User] Find all notifications that were sent more than 24 hours ago and are still unread. Show the notification ID, user ID, and sent_at timestamp.

[Assistant] SELECT notification_id, user_id, sent_at FROM notifications WHERE read_at IS NULL AND sent_at < NOW() - INTERVAL '24 hour';

[User] Show the user IDs of all users whose theme is set to 'blue'.

[Assistant] SELECT user_id FROM social_media.user_settings WHERE theme = 'blue';

[User] Find patients whose emergency_contact_phone matches another patient's phone_number and show both patients' IDs, full names, and the shared phone number.

[Assistant]
SELECT p1.patient_id AS contact_of_id,
       p1.first_name || ' ' || p1.last_name AS contact_of_name,
       p2.patient_id AS phone_owner_id,
       p2.first_name || ' ' || p2.last_name AS phone_owner_name,
       p1.emergency_contact_phone AS shared_phone
FROM healthcare.patients p1
JOIN healthcare.patients p2
  ON p1.emergency_contact_phone = p2.phone_number
WHERE p1.emergency_contact_phone IS NOT NULL;

[User] List the name, type, and city for all properties located in 'Canada'.

[Assistant] SELECT property_name, property_type, city FROM hospitality_technology.properties WHERE country_code = 'CAN';

[User] Show the top 5 largest documents by file size, including document_id, claim_id, file_name, and file_size_bytes.

[Assistant]
SELECT document_id,
       claim_id,
       file_name,
       file_size_bytes
FROM insurance.claim_documents
ORDER BY file_size_bytes DESC
LIMIT 5;

[User] Get the total number of appointments grouped by status.

[Assistant]
SELECT status,
       COUNT(*) AS appointment_count
FROM healthcare.appointments
GROUP BY status;

[User] Now filter to include only statuses with more than 50 appointments.

[Assistant]
SELECT status,
       COUNT(*) AS appointment_count
FROM healthcare.appointments
GROUP BY status
HAVING COUNT(*) > 50;

[User] List all agencies that do not have a website URL specified. Return their agency_id, agency_name, and main_phone_number.

[Assistant] SELECT agency_id, agency_name, main_phone_number FROM government_services.agencies WHERE website_url IS NULL OR website_url = '';

[User] Show me all users whose username contains 'dev', including their user_id and email address.

[Assistant] SELECT user_id, username, email FROM web3.users WHERE username ILIKE '%dev%';

[User] Can you also show the registration date for each of those users?

[Assistant] SELECT user_id, username, email, created_at FROM web3.users WHERE username ILIKE '%dev%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_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 )
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )
CREATE TABLE transportation.bookings (
    booking_id character varying(64) NOT NULL,  -- unique identifier for the booking
    passenger_id character varying(64) NOT NULL, -- identifier of the passenger making the booking
    trip_id character varying(64) NOT NULL, -- identifier of the trip being booked
    seat_number character varying(16), -- assigned seat number (if applicable)
    booking_time timestamp with time zone NOT NULL, -- time when the booking was made
    status character varying(32) NOT NULL, -- e.g., Confirmed, Cancelled, Pending Payment
    fare numeric(10, 2) NOT NULL, -- price paid for the booking
    payment_transaction_id character varying(128), -- reference to the payment transaction
    special_requests text, -- any special requests from the passenger
    PRIMARY KEY (booking_id)
)
##Table Structure
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
##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 legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )

[User] Please list the top 5 players by number of achievements unlocked since 2023-01-01. Show each player's username and the total count of achievements they unlocked.

[Assistant]
SELECT p.username, COUNT(*) AS unlock_count
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa
  ON p.player_id = pa.player_id
WHERE pa.unlocked_at >= '2023-01-01'
GROUP BY p.username
ORDER BY unlock_count DESC
LIMIT 5;

[User] Show all trips, including the trip ID, vehicle license plate, and the vehicle's capacity.

[Assistant] SELECT t.trip_id, v.license_plate, v.capacity FROM transportation.trips t JOIN vehicles v ON t.vehicle_id = v.vehicle_id;

[User] Show me all messages sent after July 1, 2024, including the sender_user_id, content, and sent_at.

[Assistant]
SELECT message_id, sender_user_id, content, sent_at
FROM social_media.messages
WHERE sent_at > '2024-07-01';

[User] Can you also include the conversation_id and only show messages that have not been read yet?

[Assistant]
SELECT message_id, sender_user_id, conversation_id, content, sent_at
FROM social_media.messages
WHERE sent_at > '2024-07-01' AND read_at IS NULL;

[User] Now only show results where the message contains a media attachment and order the results by sent_at descending.

[Assistant]
SELECT message_id, sender_user_id, conversation_id, content, sent_at
FROM social_media.messages
WHERE sent_at > '2024-07-01' AND read_at IS NULL AND media_url IS NOT NULL AND media_url <> ''
ORDER BY sent_at DESC;

[User] Show all trips with their trip ID, route ID, the ID of their origin location, and the ID of their destination location, where the route ID starts with 'EX'.

[Assistant] SELECT trip_id, route_id, origin_location_id, destination_location_id FROM transportation.trips WHERE route_id LIKE 'EX%';

[User] Can you show me the total number of diagnosis records for each doctor, along with the doctor's ID? Please include only those diagnoses marked as 'chronic'.

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

[User] Now, can you also include the average number of chronic diagnoses per patient for each doctor in the results?

[Assistant] SELECT doctor_id, COUNT(*) AS total_chronic_diagnoses, COUNT(*)::FLOAT / COUNT(DISTINCT patient_id) AS avg_chronic_per_patient FROM healthcare.diagnoses WHERE is_chronic = TRUE GROUP BY doctor_id;

[User] Please filter the results to only include doctors with at least 5 chronic diagnoses.

[Assistant] SELECT doctor_id, COUNT(*) AS total_chronic_diagnoses, COUNT(*)::FLOAT / COUNT(DISTINCT patient_id) AS avg_chronic_per_patient FROM healthcare.diagnoses WHERE is_chronic = TRUE GROUP BY doctor_id HAVING COUNT(*) >= 5;

[User] List the case number, case name, and the full name of the client for cases that have uploaded documents.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

[User] Also include the full name of the lead lawyer for these cases.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name AS client_name ,  T4.full_name AS lawyer_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T4 ON T1.lead_lawyer_id  =  T4.lawyer_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )